From 1e319d50506a74526d433cf90b75694c0f6d7268 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:30:17 +0000 Subject: [PATCH] NF2: the data plane from Terraform, the schema through db-migrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four Terraform roots, each one per environment and each publishing what the Workers render their config from: infra/terraform/supabase (a Supabase project; its ref, password and URL as Orun secrets) and infra/terraform/cloudflare-hyperdrive (a Hyperdrive config over its Postgres, WIRING_CLOUDFLARE_HYPERDRIVE), as saas-starter has them; infra/terraform/cloudflare-r2 (the storage bucket, WIRING_CLOUDFLARE_R2) from blob-starter; infra/terraform/cloudflare-kv (the rate-limit namespace, WIRING_CLOUDFLARE_KV) from kv-redis-starter. All four pass terraform validate. The schema replaces `prisma migrate`: packages/db (@app/db) holds the checksummed migrations and saas-starter's runner, which infra/db-migrate runs through Supabase's Management API — 010_pages is upstream's one Prisma model under Prisma's own names, 020_row_level_security closes public to Supabase's Data API (anon, authenticated) while the apps, which own the table, keep everything. tests/db runs them on PGlite: the manifest, the offline plan, RLS on every table and the guard that refuses to lock the apps out. The Workers now wait for what they bind, enforced on a merge and advisory on a pull request: app on Hyperdrive, R2 and the migrations; api on Hyperdrive and the migrations; web on KV. `orun plan` on the push to main orders each environment supabase -> cloudflare-hyperdrive -> db-migrate -> app/api, with cloudflare-r2 -> app and cloudflare-kv -> web beside them. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- apps/api/component.yaml | 22 +++ apps/app/component.yaml | 33 ++++ apps/web/component.yaml | 15 ++ apps/web/wiring.fixture.json | 6 +- infra/db-migrate/component.yaml | 74 ++++++++ .../cloudflare-hyperdrive/component.yaml | 68 +++++++ .../terraform/.terraform.lock.hcl | 50 +++++ .../cloudflare-hyperdrive/terraform/adopt.tf | 40 ++++ .../terraform/backend.tf | 5 + .../cloudflare-hyperdrive/terraform/main.tf | 172 ++++++++++++++++++ .../terraform/outputs.tf | 2 + .../terraform/variables.tf | 2 + infra/terraform/cloudflare-kv/component.yaml | 51 ++++++ .../cloudflare-kv/terraform/adopt.tf | 43 +++++ .../cloudflare-kv/terraform/backend.tf | 5 + .../terraform/cloudflare-kv/terraform/main.tf | 136 ++++++++++++++ .../cloudflare-kv/terraform/outputs.tf | 2 + .../cloudflare-kv/terraform/variables.tf | 2 + infra/terraform/cloudflare-r2/component.yaml | 54 ++++++ .../cloudflare-r2/terraform/adopt.tf | 38 ++++ .../cloudflare-r2/terraform/backend.tf | 5 + .../terraform/cloudflare-r2/terraform/main.tf | 123 +++++++++++++ .../cloudflare-r2/terraform/outputs.tf | 2 + .../cloudflare-r2/terraform/variables.tf | 2 + infra/terraform/supabase/component.yaml | 59 ++++++ .../supabase/terraform/.terraform.lock.hcl | 73 ++++++++ infra/terraform/supabase/terraform/adopt.tf | 49 +++++ infra/terraform/supabase/terraform/main.tf | 166 +++++++++++++++++ packages/db/component.yaml | 26 +++ packages/db/eslint.config.js | 2 + packages/db/package.json | 30 +++ packages/db/src/index.ts | 3 + packages/db/src/manifest.ts | 39 ++++ packages/db/src/migrations/000_control/up.sql | 16 ++ packages/db/src/migrations/010_pages/up.sql | 10 + .../migrations/020_row_level_security/up.sql | 35 ++++ packages/db/src/runner/cli.ts | 121 ++++++++++++ packages/db/src/runner/index.ts | 5 + packages/db/src/runner/runner.ts | 140 ++++++++++++++ packages/db/src/runner/secrets.ts | 62 +++++++ .../db/src/runner/supabase-api-adapter.ts | 93 ++++++++++ packages/db/src/runner/types.ts | 41 +++++ packages/db/src/types.ts | 20 ++ packages/db/tsconfig.build.json | 7 + packages/db/tsconfig.json | 10 + packages/next-config/transpile.ts | 4 +- pnpm-lock.yaml | 44 +++++ tests/db/component.yaml | 23 +++ tests/db/eslint.config.js | 2 + tests/db/package.json | 21 +++ tests/db/src/migrations.test.ts | 40 ++++ tests/db/src/row-level-security.test.ts | 108 +++++++++++ tests/db/tsconfig.json | 11 ++ tests/db/vitest.config.ts | 8 + 54 files changed, 2216 insertions(+), 4 deletions(-) create mode 100644 infra/db-migrate/component.yaml create mode 100644 infra/terraform/cloudflare-hyperdrive/component.yaml create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/backend.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/main.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/variables.tf create mode 100644 infra/terraform/cloudflare-kv/component.yaml create mode 100644 infra/terraform/cloudflare-kv/terraform/adopt.tf create mode 100644 infra/terraform/cloudflare-kv/terraform/backend.tf create mode 100644 infra/terraform/cloudflare-kv/terraform/main.tf create mode 100644 infra/terraform/cloudflare-kv/terraform/outputs.tf create mode 100644 infra/terraform/cloudflare-kv/terraform/variables.tf create mode 100644 infra/terraform/cloudflare-r2/component.yaml create mode 100644 infra/terraform/cloudflare-r2/terraform/adopt.tf create mode 100644 infra/terraform/cloudflare-r2/terraform/backend.tf create mode 100644 infra/terraform/cloudflare-r2/terraform/main.tf create mode 100644 infra/terraform/cloudflare-r2/terraform/outputs.tf create mode 100644 infra/terraform/cloudflare-r2/terraform/variables.tf create mode 100644 infra/terraform/supabase/component.yaml create mode 100644 infra/terraform/supabase/terraform/.terraform.lock.hcl create mode 100644 infra/terraform/supabase/terraform/adopt.tf create mode 100644 infra/terraform/supabase/terraform/main.tf create mode 100644 packages/db/component.yaml create mode 100644 packages/db/eslint.config.js create mode 100644 packages/db/package.json create mode 100644 packages/db/src/index.ts create mode 100644 packages/db/src/manifest.ts create mode 100644 packages/db/src/migrations/000_control/up.sql create mode 100644 packages/db/src/migrations/010_pages/up.sql create mode 100644 packages/db/src/migrations/020_row_level_security/up.sql create mode 100644 packages/db/src/runner/cli.ts create mode 100644 packages/db/src/runner/index.ts create mode 100644 packages/db/src/runner/runner.ts create mode 100644 packages/db/src/runner/secrets.ts create mode 100644 packages/db/src/runner/supabase-api-adapter.ts create mode 100644 packages/db/src/runner/types.ts create mode 100644 packages/db/src/types.ts create mode 100644 packages/db/tsconfig.build.json create mode 100644 packages/db/tsconfig.json create mode 100644 tests/db/component.yaml create mode 100644 tests/db/eslint.config.js create mode 100644 tests/db/package.json create mode 100644 tests/db/src/migrations.test.ts create mode 100644 tests/db/src/row-level-security.test.ts create mode 100644 tests/db/tsconfig.json create mode 100644 tests/db/vitest.config.ts diff --git a/apps/api/component.yaml b/apps/api/component.yaml index 6ab45cd..2f1ca7a 100644 --- a/apps/api/component.yaml +++ b/apps/api/component.yaml @@ -21,6 +21,28 @@ spec: inputs: - packages/** - pnpm-lock.yaml + # INFRA BEFORE APP, ENFORCED ON MAIN: the Hyperdrive config its build renders + # the id of, and the migrations its keep-alive writes into, before this + # Worker deploys (a job resolves its secrets when it STARTS). Advisory on a + # pull request, which deploys nothing. + dependsOn: + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents those roots lease-publish, one per deployed + # environment; tooling/wire/live.mjs picks this job's. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://next-forge/next-forge/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://next-forge/next-forge/prod/WIRING_CLOUDFLARE_HYPERDRIVE" # Every SaaS the template wires is OPTIONAL, an Orun secret per environment # that the product's owner stores when they sign up (README, "Connecting a # service"). Best-effort, wire-now-seed-later: a key nobody has stored is diff --git a/apps/app/component.yaml b/apps/app/component.yaml index 2479697..bc4e866 100644 --- a/apps/app/component.yaml +++ b/apps/app/component.yaml @@ -21,6 +21,39 @@ spec: inputs: - packages/** - pnpm-lock.yaml + # INFRA BEFORE APP, ENFORCED ON MAIN. A merge converges the whole product in + # one run: the Supabase project, the Hyperdrive config over it and the R2 + # bucket, then the migrations, then this Worker. Its build renders the + # Hyperdrive id and the bucket name from the wiring documents those roots + # lease-publish, and its pages read the migrated table; a job resolves its + # secrets when it STARTS, so it waits on all three, `mode: enforced`. A pull + # request deploys nothing, so nothing on one waits: advisory there. + dependsOn: + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: cloudflare-r2 + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents those roots lease-publish, one per deployed + # environment; tooling/wire/live.mjs picks this job's. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://next-forge/next-forge/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://next-forge/next-forge/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_R2_STAGE: "secret://next-forge/next-forge/stage/WIRING_CLOUDFLARE_R2" + WIRING_CLOUDFLARE_R2_PROD: "secret://next-forge/next-forge/prod/WIRING_CLOUDFLARE_R2" # Every SaaS the template wires is OPTIONAL, an Orun secret per environment # that the product's owner stores when they sign up (README, "Connecting a # service"). Best-effort, wire-now-seed-later: a key nobody has stored is diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 061cd20..423aa27 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -21,6 +21,21 @@ spec: inputs: - packages/** - pnpm-lock.yaml + # INFRA BEFORE APP, ENFORCED ON MAIN: the KV namespace its build renders the + # id of, applied before this Worker deploys (a job resolves its secrets when + # it STARTS). Advisory on a pull request, which deploys nothing. + dependsOn: + - component: cloudflare-kv + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents those roots lease-publish, one per deployed + # environment; tooling/wire/live.mjs picks this job's. + secretEnv: + WIRING_CLOUDFLARE_KV_STAGE: "secret://next-forge/next-forge/stage/WIRING_CLOUDFLARE_KV" + WIRING_CLOUDFLARE_KV_PROD: "secret://next-forge/next-forge/prod/WIRING_CLOUDFLARE_KV" # Every SaaS the template wires is OPTIONAL, an Orun secret per environment # that the product's owner stores when they sign up (README, "Connecting a # service"). Best-effort, wire-now-seed-later: a key nobody has stored is diff --git a/apps/web/wiring.fixture.json b/apps/web/wiring.fixture.json index cc41c01..9f98e64 100644 --- a/apps/web/wiring.fixture.json +++ b/apps/web/wiring.fixture.json @@ -1,14 +1,14 @@ { "cloudflare-kv/dev": { "app_kv_id": "00000000000000000000000000000002", - "app_kv_title": "dev-next-forge-rate-limit-dev" + "app_kv_title": "dev-next-forge-app-kv-dev" }, "cloudflare-kv/stage": { "app_kv_id": "00000000000000000000000000000001", - "app_kv_title": "stg-next-forge-rate-limit-stage" + "app_kv_title": "stg-next-forge-app-kv-stage" }, "cloudflare-kv/prod": { "app_kv_id": "00000000000000000000000000000003", - "app_kv_title": "prod-next-forge-rate-limit-prod" + "app_kv_title": "prod-next-forge-app-kv-prod" } } diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml new file mode 100644 index 0000000..040830a --- /dev/null +++ b/infra/db-migrate/component.yaml @@ -0,0 +1,74 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-migrate + description: Applies database migrations to stage and prod Supabase instances + labels: + domain: infra + scope: database + team: platform + layer: data + +spec: + type: db-migrate + lifecycle: production + owner: platform + domain: infra + + # Migrations read the Supabase connection from the orun secrets the + # `supabase` apply lease-publishes, so on main they wait for it — and for + # the Hyperdrive config over that database. Nothing here needs Hyperdrive; + # the edge is there because a migration is the one step of a convergence a + # re-run cannot take back, so it runs only once everything the Worker needs + # besides the schema exists, immediately before the Worker deploys. The + # order on main is supabase → cloudflare-hyperdrive → db-migrate → web. + # Enforced on main, advisory on a pull request (which applies nothing). + dependsOn: + - component: db + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + path: packages/db/src/migrations + + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + owner: sourceplane + repo: next-forge + + # The migration runner's Management-API token (required in apply mode) + # resolves from orun secrets — minted fresh per run from the Supabase + # integration (management-access template). Replaces the ambient + # SUPABASE_ACCESS_TOKEN CI value. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + # The runner's DB identity (de-AWS — replaces the Secrets Manager read). + SUPABASE_PROJECT_REF: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_PROJECT_REF" + SUPABASE_DB_PASSWORD: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_DB_PASSWORD" + SUPABASE_DB_URL: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_DB_URL" + + subscribe: + environments: + - name: stage + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-hyperdrive/component.yaml b/infra/terraform/cloudflare-hyperdrive/component.yaml new file mode 100644 index 0000000..ea52248 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/component.yaml @@ -0,0 +1,68 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-hyperdrive + description: Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases + labels: + domain: infra + scope: runtime-database-gateway + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + # Hyperdrive's origin is the Supabase project's Postgres, whose ref and + # password the `supabase` apply lease-publishes (SUPABASE_PROJECT_REF, + # SUPABASE_DB_PASSWORD, read below). A job resolves its secrets when it + # starts, so on main this waits for that apply, `mode: enforced`; a pull + # request applies nothing, so there it is advisory. + dependsOn: + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + parameters: + orgName: sourceplane + stackName: cloudflare-hyperdrive + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (hyperdrive id/name) is lease-published + # post-apply; worker deploys read it back as WIRING_CLOUDFLARE_HYPERDRIVE_. + secretOutputs: "WIRING_CLOUDFLARE_HYPERDRIVE=wiring" + + # All three values resolve from orun secrets (project rung, brokered from + # the Cloudflare integration): the provider credential is minted fresh per + # run from the hyperdrive-edit template (Workers Hyperdrive Write — the + # workers-deploy token deliberately cannot touch Hyperdrive), and the + # account id is a non-secret connection fact (account-id template). + # Component-level because plan-only lanes refresh against the live API too. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_HYPERDRIVE_TOKEN" + CLOUDFLARE_ACCOUNT_ID: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + # Supabase origin, lease-published by the supabase component's + # secretOutputs — the replacement for the Secrets Manager data source. + TF_VAR_supabase_project_ref: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_PROJECT_REF" + TF_VAR_supabase_db_password: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_DB_PASSWORD" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..c133371 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl @@ -0,0 +1,50 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/cloudflare/cloudflare" { + version = "4.52.7" + constraints = "~> 4.30" + hashes = [ + "h1:pPItIWii5oymR+geZB219ROSPuSODPLTlM4S/u8xLvM=", + "h1:uUUa9dY0XQOycI8pxg16PFFtL0WCTi9uEJz8trTQ7pU=", + "h1:y3rV8KF2q6GEMANNlf5EkKJurlfbKlIKpjGcdxoy7pQ=", + "zh:0c904ce31a4c6c4a5b3bf7ff1560e77c0cc7e2450c8553ded8e8c90398e1418b", + "zh:36183d310c36373fe4cb936b83c595c6fd3b0a94bc7827f28e5789ccbf59752e", + "zh:556a568a6f0235e8f41647de9e4d3a1e7b1d6502df8b19b54ec441f1c653ea10", + "zh:633ebbd5b0245e75e500ef9be4d9e62288f97e8da3baaa51323892a786d90285", + "zh:6acfe60cf52a65ba8f044f748548d2119e7f4fd7f8ebcb14698960d87c68f529", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:904acc31ebb9d6ef68c792074b30532ee61bf515f19e0a3c75b46f126cca1f13", + "zh:a1d0a81246afc8750286d3f6fe7a8fbe6460dd2662407b28dbfbabb612e5fa9d", + "zh:a41a36fe253fc365fe2b7ffc749624688b2693b4634862fda161179ab100029f", + "zh:a7ef269e77ffa8715c8945a2c14322c7ff159ea44c15f62505f3cbb2cae3b32d", + "zh:b01aa3bed30610633b762df64332b26f8844a68c3960cebcb30f04918efc67fe", + "zh:b069cc2cd18cae10757df3ae030508eac8d55de7e49eda7a5e3e11f2f7fe6455", + "zh:b2d2c6313729ebb7465dceece374049e2d08bda34473901be9ff46a8836d42b2", + "zh:db0e114edaf4bc2f3d4769958807c83022bfbc619a00bdf4c4bd17faa4ab2d8b", + "zh:ecc0aa8b9044f664fd2aaf8fa992d976578f78478980555b4b8f6148e8d1a5fe", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf b/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf new file mode 100644 index 0000000..1c58837 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf @@ -0,0 +1,40 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# Same pattern as cloudflare-kv/terraform/adopt.tf: when the platform state +# does not yet track the Hyperdrive config but Cloudflare already has one +# under this name, import it at plan time instead of creating a duplicate. +# Fresh products resolve to id = "" and create normally; a resource already in +# state short-circuits the lookup. Note the origin password still comes from +# config — after adoption the first apply re-asserts the origin credentials +# from SUPABASE_DB_PASSWORD, which is exactly the re-sync the cutover needs. + +data "external" "adopt_hyperdrive_config" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_hyperdrive_config" and .name == "postgres")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/hyperdrive/configs")" + printf '%s' "$resp" | jq -c --arg n "$name" \ + '{id: ([.result[] | select(.name == $n) | .id] | first // "")}' + EOT + ] + query = { + name = local.hyperdrive_name + } +} + +import { + for_each = toset(compact([data.external.adopt_hyperdrive_config.result.id])) + to = cloudflare_hyperdrive_config.postgres + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf b/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/main.tf b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf new file mode 100644 index 0000000..679092b --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf @@ -0,0 +1,172 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the +# token is an orun-managed secret resolved into the job env at run time, so it +# never transits Terraform variables. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "next-forge" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-hyperdrive" +} + +variable "stackName" { + type = string + default = "cloudflare-hyperdrive" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- Supabase origin (from orun secrets, not Secrets Manager) --- +# +# The supabase component wires its outputs into the workspace's project/{{env}} +# secret rung (wireSecrets → SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD); this +# component declares them in secretEnv as TF_VAR_supabase_project_ref / +# TF_VAR_supabase_db_password. Host/port/db/user derive from the project ref — +# the same derivation the old Secrets Manager payload carried. + +variable "supabase_project_ref" { + type = string + description = "Supabase project reference (from SUPABASE_PROJECT_REF secret)" +} + +variable "supabase_db_password" { + type = string + sensitive = true + description = "Supabase database password (from SUPABASE_DB_PASSWORD secret)" +} + +locals { + database_host = "db.${var.supabase_project_ref}.supabase.co" + database_port = 5432 + database_name = "postgres" + database_user = "postgres" + + hyperdrive_name = "${var.namespacePrefix}${var.repo}-${var.environment}" +} + +# --- Create Hyperdrive resource --- + +resource "cloudflare_hyperdrive_config" "postgres" { + account_id = var.cloudflare_account_id + name = local.hyperdrive_name + + origin = { + scheme = "postgres" + host = local.database_host + port = local.database_port + database = local.database_name + user = local.database_user + password = var.supabase_db_password + } + + caching = { + disabled = false + } +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# +# The consumable outputs of this component are published by the composition's +# wire-secrets step as the WIRING_CLOUDFLARE_HYPERDRIVE secret on the +# project/{{env}} rung; worker deploys read it back as +# WIRING_CLOUDFLARE_HYPERDRIVE_ secretEnv and render committed +# @@wiring(...)@@ tokens from it (BF6). Same document shape the Secrets +# Manager path carried. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + hyperdrive_id = cloudflare_hyperdrive_config.postgres.id + hyperdrive_name = cloudflare_hyperdrive_config.postgres.name + }) +} + +# --- Outputs (non-secret) --- + +output "hyperdrive_id" { + description = "Cloudflare Hyperdrive config ID" + value = cloudflare_hyperdrive_config.postgres.id +} + +output "hyperdrive_name" { + description = "Cloudflare Hyperdrive config name" + value = cloudflare_hyperdrive_config.postgres.name +} + +output "hyperdrive_connection_string" { + description = "Hyperdrive-formatted connection string for Workers (to be used in bindings)" + # Note: actual connection string is built at binding time; this is the resource ID + value = "hyperdrive://${cloudflare_hyperdrive_config.postgres.id}" +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf b/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf b/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-kv/component.yaml b/infra/terraform/cloudflare-kv/component.yaml new file mode 100644 index 0000000..cbe8d22 --- /dev/null +++ b/infra/terraform/cloudflare-kv/component.yaml @@ -0,0 +1,51 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-kv + description: Provisions the Cloudflare KV namespace the app binds (stage and prod) + labels: + domain: infra + scope: app-kv + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-kv + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (KV namespace id/title) is lease-published + # post-apply; app deploys read it back as WIRING_CLOUDFLARE_KV_. + secretOutputs: "WIRING_CLOUDFLARE_KV=wiring" + + # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN + # env var, resolved by orun from the project-rung brokered secret (fresh per + # run, Deploy Workers scope). Declared at component level because plan-only + # lanes refresh against the live Cloudflare API too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_API_TOKEN" + # Non-secret connection fact (account-id template) — replaces the ambient + # CLOUDFLARE_ACCOUNT_ID / TF_VAR_cloudflare_account_id CI values. + CLOUDFLARE_ACCOUNT_ID: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-kv/terraform/adopt.tf b/infra/terraform/cloudflare-kv/terraform/adopt.tf new file mode 100644 index 0000000..7c1fbba --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/adopt.tf @@ -0,0 +1,43 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# When the platform state does not yet track the namespace but Cloudflare +# already has one under this title (a baseline whose state predates the +# platform backend, or a recovered workspace), the create would collide with +# the duplicate-title guard (error 10014). Instead: look the namespace up at +# plan time with the job's brokered credentials and import it. Fresh products +# resolve to id = "" and create normally, and a resource already tracked in +# state short-circuits the lookup — so this block is inert everywhere except +# the one case it exists for. Both lookups run inside the job: process env +# carries the brokered CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the +# TF_HTTP_* state credentials, so no extra secrets and no AWS access. + +data "external" "adopt_app_kv" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + title="$(jq -r .title)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_workers_kv_namespace" and .name == "app_kv")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/storage/kv/namespaces?per_page=100")" + printf '%s' "$resp" | jq -c --arg t "$title" \ + '{id: ([.result[] | select(.title == $t) | .id] | first // "")}' + EOT + ] + query = { + title = local.app_kv_title + } +} + +import { + for_each = toset(compact([data.external.adopt_app_kv.result.id])) + to = cloudflare_workers_kv_namespace.app_kv + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-kv/terraform/backend.tf b/infra/terraform/cloudflare-kv/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-kv/terraform/main.tf b/infra/terraform/cloudflare-kv/terraform/main.tf new file mode 100644 index 0000000..88321fc --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/main.tf @@ -0,0 +1,136 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the +# token is an orun-managed secret resolved into the job env at run time, so it +# never transits Terraform variables. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "next-forge" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-kv" +} + +variable "stackName" { + type = string + default = "cloudflare-kv" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- The KV namespace the page's counter lives in --- +# +# Bound by apps/web as VIEWS. Keys are the app's (`views`); any expiry is +# per-PUT (`expirationTtl`), owned by the Worker — no Terraform-side TTL knob +# exists for KV namespaces themselves. + +locals { + # Built on var.repo (the product's repository slug) so the title is unique per + # product. Cloudflare KV namespace titles must be unique per account, and two + # products may share an account — without the slug the second create fails + # with "a namespace with this account ID and title already exists" (10014). + # The Worker binds this namespace by ID via the wiring secret, so the title is + # free to change. + app_kv_title = "${var.namespacePrefix}${var.repo}-app-kv-${var.environment}" +} + +resource "cloudflare_workers_kv_namespace" "app_kv" { + account_id = var.cloudflare_account_id + title = local.app_kv_title +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# The consumable outputs are published by the composition's wire-secrets step +# as the WIRING_CLOUDFLARE_KV secret on the project/{{env}} rung; worker +# deploys read it back as WIRING_CLOUDFLARE_KV_ secretEnv (BF6). Same +# document shape the Secrets Manager path carried. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + app_kv_id = cloudflare_workers_kv_namespace.app_kv.id + app_kv_title = cloudflare_workers_kv_namespace.app_kv.title + }) +} + +# --- Outputs (non-secret) --- + +output "app_kv_id" { + description = "Cloudflare Workers KV namespace ID the page's counter lives in" + value = cloudflare_workers_kv_namespace.app_kv.id +} + +output "app_kv_title" { + description = "Cloudflare Workers KV namespace title (human-readable identifier)" + value = cloudflare_workers_kv_namespace.app_kv.title +} diff --git a/infra/terraform/cloudflare-kv/terraform/outputs.tf b/infra/terraform/cloudflare-kv/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-kv/terraform/variables.tf b/infra/terraform/cloudflare-kv/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-r2/component.yaml b/infra/terraform/cloudflare-r2/component.yaml new file mode 100644 index 0000000..6dae28e --- /dev/null +++ b/infra/terraform/cloudflare-r2/component.yaml @@ -0,0 +1,54 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-r2 + description: Provisions the Cloudflare R2 bucket the app binds (stage and prod) + labels: + domain: infra + scope: app-object-store + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-r2 + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (R2 bucket name) is lease-published + # post-apply; app deploys read it back as WIRING_CLOUDFLARE_R2_. + secretOutputs: "WIRING_CLOUDFLARE_R2=wiring" + + # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN + # env var, resolved by orun from the project-rung brokered secret — minted + # fresh per run from the r2-data template (Workers R2 Storage Write; the + # workers-deploy token the app deploys with deliberately cannot touch R2). + # adopt.tf's bucket lookup reads the same variable. Declared at component + # level because plan-only lanes refresh against the live Cloudflare API + # too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_R2_TOKEN" + # Non-secret connection fact (account-id template) — replaces the ambient + # CLOUDFLARE_ACCOUNT_ID / TF_VAR_cloudflare_account_id CI values. + CLOUDFLARE_ACCOUNT_ID: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://next-forge/next-forge/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-r2/terraform/adopt.tf b/infra/terraform/cloudflare-r2/terraform/adopt.tf new file mode 100644 index 0000000..cc3b2ec --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/adopt.tf @@ -0,0 +1,38 @@ +# --- Self-healing adoption --- +# +# When the platform state does not yet track the bucket but Cloudflare already +# has one under this name (a re-bootstrap over a torn-down workspace), import +# it at plan time instead of colliding with the duplicate-name guard. Fresh +# products resolve to id = "" and create normally; a resource already in state +# short-circuits the lookup. + +data "external" "adopt_app_bucket" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_r2_bucket" and .name == "app")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/r2/buckets?per_page=1000")" + printf '%s' "$resp" | jq -c --arg n "$name" \ + '{id: ([.result.buckets[]? | select(.name == $n) | .name] | first // "")}' + EOT + ] + query = { + name = local.bucket_name + } +} + +import { + for_each = toset(compact([data.external.adopt_app_bucket.result.id])) + to = cloudflare_r2_bucket.app + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-r2/terraform/backend.tf b/infra/terraform/cloudflare-r2/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-r2/terraform/main.tf b/infra/terraform/cloudflare-r2/terraform/main.tf new file mode 100644 index 0000000..f9dbd3c --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/main.tf @@ -0,0 +1,123 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform: the runner exports TF_HTTP_* per job, so this + # block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the +# token is an orun-managed secret resolved into the job env at run time — +# CLOUDFLARE_R2_TOKEN, minted from the r2-data template (component.yaml). +provider "cloudflare" {} + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "next-forge" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-r2" +} + +variable "stackName" { + type = string + default = "cloudflare-r2" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- The bucket the uploads live in --- +# +# One R2 bucket per environment, bound by apps/web as BLOB: the upload route +# writes the images it accepts, the delivery route streams them back. It +# stands in for Vercel Blob. The bucket is private — nothing is served from it +# but through the Worker. + +locals { + # Built on var.repo (the product's repository slug) so the name is unique per + # product. R2 bucket names are unique per account, and two products may + # share an account — without the slug the second product's create would + # find the name taken. The Worker binds the bucket by this name, via the + # wiring secret. + bucket_name = "${var.namespacePrefix}${var.repo}-${var.environment}" +} + +resource "cloudflare_r2_bucket" "app" { + account_id = var.cloudflare_account_id + name = local.bucket_name +} + +# --- Wiring manifest (via orun secrets) --- +# Published post-apply as the WIRING_CLOUDFLARE_R2 secret on the project/{{env}} +# rung; the app's deploy reads it back as WIRING_CLOUDFLARE_R2_ and +# renders its wrangler template from it. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + r2_bucket_name = cloudflare_r2_bucket.app.name + }) +} + +output "r2_bucket_name" { + description = "Cloudflare R2 bucket name (the Workers binding's bucket_name)" + value = cloudflare_r2_bucket.app.name +} diff --git a/infra/terraform/cloudflare-r2/terraform/outputs.tf b/infra/terraform/cloudflare-r2/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-r2/terraform/variables.tf b/infra/terraform/cloudflare-r2/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml new file mode 100644 index 0000000..9c8edff --- /dev/null +++ b/infra/terraform/supabase/component.yaml @@ -0,0 +1,59 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: supabase + description: Provisions Supabase projects for stage and prod and wires credentials into orun secrets + labels: + domain: infra + scope: database + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: supabase + terraformDir: terraform + terraformVersion: "1.15.3" + # Supabase region is surfaced to Terraform as TF_VAR_supabaseRegion by the + # terraform composition's parameter→TF_VAR loop. The org id is NOT committed + # here: it is account-specific and injected as TF_VAR_supabaseOrgId from the + # SUPABASE_ORG_ID CI secret (see .github/workflows/ci.yml). Keeping it out of + # parameters also prevents the param→TF_VAR loop from overriding the secret. + supabaseRegion: ap-southeast-1 + # SEC-JOB: post-apply, these outputs are queued on the runner's sink and + # lease-published onto the project/{{env}} rung by the runner. Exactly + # what the tree reads (Lumen's three): cloudflare-hyperdrive takes the ref + # and the password, db-migrate all three. This app reaches Supabase only + # as Postgres, so no API key is published. + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri" + + # Both values resolve from orun secrets (project rung, brokered from the + # Supabase integration): a short-lived Management-API access token minted + # fresh per run (management-access template — the provider reads + # SUPABASE_ACCESS_TOKEN from env natively), and the org id as a non-secret + # connection fact (org-id template) surfaced straight to Terraform. The + # SUPABASE_ORG_ID CI secret and its TF_VAR mapping are retired. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + TF_VAR_supabaseOrgId: "secret://next-forge/next-forge/{{ .environment }}/SUPABASE_ORG_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/supabase/terraform/.terraform.lock.hcl b/infra/terraform/supabase/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..5b4468d --- /dev/null +++ b/infra/terraform/supabase/terraform/.terraform.lock.hcl @@ -0,0 +1,73 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.9.0" + constraints = "~> 3.0" + hashes = [ + "h1:OO+IuvQJSPmWdN8AyyIEvPJbLvDQpgX/zbktoa9KsJE=", + "h1:UlBuNVuCGJ39tTv2c5gz2NRZnQbXfbIWbTzWcth5o74=", + "h1:lVDv+0AjDjrLfpmaJbWqUmIw/k3/AHXLc3N4m55SNdo=", + "zh:161ad0bd9a75768c82f53fb6e7172a9d8be2d4889b012645a34795031aaf1bf1", + "zh:19dc9a5b17729725ccfc4f45b0500af0ee5bc6b6b160c7adb8f2bf617d2c80ea", + "zh:269eda8fe42daa7974d5a34d166c3ba9defe80cde86c01e4dadcfdf2e1f05e5f", + "zh:373f7c65566f8f2cc7f45d698654feb9d988996957e1266a69ca00c52d6d16d0", + "zh:5599d16804c41c83009ec621b6d6b6f74e102f5827678a4750f8809055546b61", + "zh:583be0440469a22bff70dcfa56593b01566860b29607437264adb51060cf46fc", + "zh:5f211d8ec3f2e1f414870d9584bfe26e6995560ef81c748f8447a48164767398", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7b547fd16216761ef86efc3ed516ac5ac0c5c42b7c7eb24a08cef2d93f69ed5e", + "zh:7e7c0679daf2a382151d05068c8c3f0dae6b7b7dccf818827b73dd08638df2ef", + "zh:8089dec888a8038b9b4fb23b3df7e1057293dbc5b60b42cc47ff690d69d4b61b", + "zh:c51f15a031edfd6f23ce8ced3446ca7f8d8d647e2499890d7d5d10d5016d7257", + "zh:c94784f005708890dc6895afd53636ec00ec1e430b15d41e5aebfb1d4b39bd04", + ] +} + +provider "registry.terraform.io/supabase/supabase" { + version = "1.5.1" + constraints = "~> 1.5.1" + hashes = [ + "h1:A4kqrLbrPeyfOXuk2eN8L15ue7JSRtkV/FhqFyY9Dzg=", + "h1:X1mvSyjaWyaJmhijgpsXMP7UMIE5kuwbq4wfjpfcxBA=", + "h1:rTxTmQ7IGlQNi5H1oS8e2+AgmiXeWM+jnJN5TNS69vU=", + "zh:1834f1cfbab811ca53eae9bdb6485032a674aef5d84fa7fe65342f72e50e3880", + "zh:1d53f3c0c6d82c50a7a29d658f77f3e44db0c0196714f0891ec2cadfdeb58764", + "zh:1f4dda08ccb39790f3c11fb6b4006827f09bfb8fb85082886eb46803f44b1722", + "zh:38dcad29e57c4d06374f4b557108d0877bb3ba628878c6648508110ff34f3d0f", + "zh:63782085e8da25d78de2a080072e7cc6a35c781c2bdb04f5ca46f65a6d6988d6", + "zh:79d7e5fe9d1571aa5357f98b97e3f12e61f68500e4270e855c1bc5e4cc772a56", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:8c8560f8df33c087ab9133fc32b68c4c16c8c1bc32b546c91dc98c2b39f80c3a", + "zh:ab4189d0c843166a1b4eaefe817192c8cee954c441a3a86ef5118931ce0e9d71", + "zh:c9037e7cfadc468ac961786af7e3004c08196543416842746f95b929e6118fd6", + "zh:ca9546b9ca3a27634a6eb37e069e58a44a26fe8c3c6539a17dc4b628ad6e7ae0", + "zh:d0301164210ea4ed0567c9c1c751d1e250ab163a8b0edd8cf256d25d54e4d1e5", + "zh:f048d76cca0083a2b91bef304949d182b3395b3bc013cc8aa1505219538953a1", + "zh:f85b905aa8f049a8769bac933a56ae0ca9c5bb74a6c2376cf9ee4ac8ecf50126", + "zh:fd26c6f338bfab77b145e0755dc39d9873aec8219b3b53909da418250d013973", + ] +} diff --git a/infra/terraform/supabase/terraform/adopt.tf b/infra/terraform/supabase/terraform/adopt.tf new file mode 100644 index 0000000..b5d6feb --- /dev/null +++ b/infra/terraform/supabase/terraform/adopt.tf @@ -0,0 +1,49 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# Same pattern as cloudflare-kv/terraform/adopt.tf: when the platform state +# does not yet track the Supabase project but the organization already has one +# under this name, import it by ref at plan time instead of colliding with the +# duplicate-name guard. Fresh products resolve to id = "" and create normally; +# a resource already in state short-circuits the lookup. +# +# Cutover caveat: database_password is config-driven (random_password). After +# adoption the first apply RESETS the database password to the newly generated +# one and publishes it through the job-output secrets — db-migrate, hyperdrive +# and the worker fleet re-wire from those in the same run, but anything still +# consuming the pre-adoption credentials breaks until that run converges. + +data "external" "adopt_project" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "supabase_project" and .name == "this")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects")" + # The org id reaches this job as TF_VAR_supabaseOrgId (the component maps + # the SUPABASE_ORG_ID secret to the terraform variable); plain + # SUPABASE_ORG_ID exists only in older wirings. Accept either; with + # neither set, match by name alone. + org="$${TF_VAR_supabaseOrgId:-$${SUPABASE_ORG_ID:-}}" + printf '%s' "$resp" | jq -c --arg n "$name" --arg org "$org" \ + '{id: ([.[] | select(.name == $n and ($org == "" or .organization_id == $org)) | .id] | first // "")}' + EOT + ] + query = { + name = local.project_name + } +} + +import { + for_each = toset(compact([data.external.adopt_project.result.id])) + to = supabase_project.this + id = each.value +} diff --git a/infra/terraform/supabase/terraform/main.tf b/infra/terraform/supabase/terraform/main.tf new file mode 100644 index 0000000..0ea5c60 --- /dev/null +++ b/infra/terraform/supabase/terraform/main.tf @@ -0,0 +1,166 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job + # (address = …/state/tfstate/{component}/{env}, run token as password), so + # this block stays empty — no S3 bucket, no AWS role, no workspaces (the + # environment is in the address). + backend "http" {} + + required_providers { + supabase = { + source = "supabase/supabase" + # Pinned below 1.6: from 1.6.0 the provider reads /billing/addons on + # every project create/read, and Supabase does not serve billing + # endpoints to OAuth tokens yet ("does not support oauth access") — + # which is exactly the credential the platform brokers. + version = "~> 1.5.1" + } + random = { + source = "hashicorp/random" + version = "~> 3.0" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the SUPABASE_ACCESS_TOKEN env var (provider-native): a +# short-lived Management-API token minted per run from the workspace's +# Supabase integration, resolved into the job env by orun. +provider "supabase" {} + +# --- Variables (standard Orun parameters) --- + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "next-forge" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "supabase" +} + +variable "stackName" { + type = string + default = "supabase" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# Supabase target identity. supabaseRegion comes from the component's +# `spec.parameters`; supabaseOrgId is injected as TF_VAR_supabaseOrgId from the +# workspace's SUPABASE_ORG_ID secret (org-id connection fact). Both are +# required (no default) so a missing value fails plan loudly instead of +# silently pointing at the wrong org or region. +variable "supabaseOrgId" { + type = string +} + +variable "supabaseRegion" { + type = string +} + +# --- Locals --- + +locals { + supabase_org_id = var.supabaseOrgId + supabase_region = var.supabaseRegion + project_name = "${var.repo}-${var.environment}" +} + +# --- Generate database password --- + +resource "random_password" "db_password" { + length = 32 + special = true + # Avoid characters that cause issues in connection strings + override_special = "!#$%&*()-_=+[]{}|:,.<>?" +} + +# --- Supabase project --- + +resource "supabase_project" "this" { + organization_id = local.supabase_org_id + name = local.project_name + database_password = random_password.db_password.result + region = local.supabase_region +} + +# --- Outputs --- +# +# Credentials leave this module ONLY through the composition's wire-secrets +# step (component.yaml `wireSecrets`), which pushes each named output into the +# workspace's project/{{env}} secret rung via `orun secrets set` (value over +# stdin, never argv). Consumers (cloudflare-hyperdrive, db-migrate, workers) +# read the same keys back as secretEnv references. No Secrets Manager. + +output "project_ref" { + description = "Supabase project reference ID" + value = supabase_project.this.id +} + +output "project_name" { + description = "Supabase project name" + value = supabase_project.this.name +} + +output "project_url" { + description = "Supabase project URL" + value = "https://${supabase_project.this.id}.supabase.co" +} + +output "database_password" { + description = "Generated database password (sensitive; wired to orun secrets)" + value = random_password.db_password.result + sensitive = true +} + +output "connection_uri" { + description = "Direct Postgres connection URI (sensitive; wired to orun secrets)" + value = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" + sensitive = true +} diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..d6bf94c --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,26 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db + description: The database migrations and their runner (built by the db-migrate component before it plans or applies) +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: data + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: data diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..f9d5256 --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,30 @@ +{ + "name": "@app/db", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The database migrations and their runner (the db-migrate composition builds this package and runs dist/runner/cli.js plan|apply)", + "exports": { + ".": "./src/index.ts", + "./manifest": "./src/manifest.ts", + "./types": "./src/types.ts", + "./runner": "./src/runner/index.ts" + }, + "bin": { + "db-migrate": "./dist/runner/cli.js" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && cp -r src/migrations dist/", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "manifest:check": "node ../../tooling/migrations/manifest.mjs check", + "manifest:fix": "node ../../tooling/migrations/manifest.mjs fix", + "migrate:plan": "node dist/runner/cli.js plan" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@types/node": "25.3.5", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..9b5ee07 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,3 @@ +export { manifest } from "./manifest.js"; +export type { MigrationEntry, MigrationManifest, BoundedContext } from "./types.js"; +export { BOUNDED_CONTEXTS } from "./types.js"; diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts new file mode 100644 index 0000000..c69c7a7 --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,39 @@ +import type { MigrationManifest } from "./types.js"; + +// Every migration the runner applies, in order, with the sha256 of its file. +// `pnpm --filter @app/db run manifest:check` verifies the checksums; +// `manifest:fix` rewrites them after a migration file changes (only ever +// before that migration has been applied anywhere — an applied migration's +// checksum is immutable). +export const manifest: MigrationManifest = { + version: 1, + migrations: [ + { + id: "000_control_baseline", + context: "control", + path: "000_control/up.sql", + checksum: + "2a5d7f30684c99e3ff441ca8a2c38038dedd1bab4db4a40e92cd36bb22be297f", + description: + "Baseline control migration — creates the migration tracking schema", + }, + { + id: "010_pages", + context: "app", + path: "010_pages/up.sql", + checksum: + "5a470a82a50d5fb84703b090d1b6987508fcb33087e12962a942eedde231d3bc", + description: + "The template's schema: upstream's one Prisma model, the stub Page table, with Prisma's table and key names", + }, + { + id: "020_row_level_security", + context: "app", + path: "020_row_level_security/up.sql", + checksum: + "08bd7f0a84d5ebef70195b6bbb51fa9ac3c1c11d0263c2352a3ae9fa9f6a0546", + description: + "Row-level security, with no policies, on every table in public — closed to Supabase's Data API (anon, authenticated), open to the apps, which own them; refuses to run if the apps' role would be locked out", + }, + ], +}; diff --git a/packages/db/src/migrations/000_control/up.sql b/packages/db/src/migrations/000_control/up.sql new file mode 100644 index 0000000..1764562 --- /dev/null +++ b/packages/db/src/migrations/000_control/up.sql @@ -0,0 +1,16 @@ +-- Baseline control migration +-- Creates the migration tracking schema used by the migration runner. +-- Owner: control bounded context + +CREATE SCHEMA IF NOT EXISTS _migrations; + +CREATE TABLE IF NOT EXISTS _migrations.applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now(), + applied_by TEXT NOT NULL DEFAULT current_user +); + +COMMENT ON TABLE _migrations.applied IS + 'Tracks which migrations have been applied to the database.'; diff --git a/packages/db/src/migrations/010_pages/up.sql b/packages/db/src/migrations/010_pages/up.sql new file mode 100644 index 0000000..7e10642 --- /dev/null +++ b/packages/db/src/migrations/010_pages/up.sql @@ -0,0 +1,10 @@ +-- The template's schema: upstream's one Prisma model +-- (packages/database/prisma/schema.prisma), the stub `Page` its app lists and +-- its keep-alive cron writes, as `prisma migrate` would create it — the table +-- and its key keep Prisma's names, so a product that brings Prisma back finds +-- the table it expects. @repo/database reads and writes it over Hyperdrive. +CREATE TABLE IF NOT EXISTS "Page" ( + "id" SERIAL NOT NULL, + "name" TEXT NOT NULL, + CONSTRAINT "Page_pkey" PRIMARY KEY ("id") +); diff --git a/packages/db/src/migrations/020_row_level_security/up.sql b/packages/db/src/migrations/020_row_level_security/up.sql new file mode 100644 index 0000000..bd05192 --- /dev/null +++ b/packages/db/src/migrations/020_row_level_security/up.sql @@ -0,0 +1,35 @@ +-- Row-level security on every table in `public`, and no policies. +-- +-- Supabase's Data API (PostgREST) serves `public` to anyone holding the +-- project's anon key, which is public by Supabase's design. Upstream assumed +-- a private Neon database, so its tables had no RLS, and the Data API would +-- hand them out. With RLS enabled and no policy, `anon` and `authenticated` +-- read and write NOTHING through it. The apps are not affected: they connect +-- through Hyperdrive as `postgres` (the cloudflare-hyperdrive root's database +-- user), which created and owns these tables, and a table's owner is not +-- subject to its RLS unless FORCE is set (it is not). The migration ledger +-- (`_migrations`) is a schema the Data API does not expose. tests/db fails if +-- any table in `public` is left without RLS after the migrations. +-- +-- FIRST, the guard. If `postgres` neither owns every table here nor has +-- SUPERUSER or BYPASSRLS, enabling RLS would lock the apps out of their own +-- data: stop. The guard changes nothing and runs before the first ALTER, so +-- a refusal enables nothing. Idempotent: ENABLE on an enabled table is a +-- no-op. +DO $$ +DECLARE + app_bypasses boolean; + not_owned text; +BEGIN + SELECT rolsuper OR rolbypassrls INTO app_bypasses FROM pg_roles WHERE rolname = 'postgres'; + SELECT string_agg(c.relname, ', ' ORDER BY c.relname) INTO not_owned + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') + AND pg_get_userbyid(c.relowner) <> 'postgres'; + IF NOT coalesce(app_bypasses, false) AND not_owned IS NOT NULL THEN + RAISE EXCEPTION 'row-level security would lock the app out of %: postgres (the role Hyperdrive connects as) neither owns them nor has SUPERUSER or BYPASSRLS', not_owned; + END IF; +END +$$; + +ALTER TABLE "Page" ENABLE ROW LEVEL SECURITY; diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..c4df1bf --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,121 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadSecretFromEnv } from "./secrets.js"; +import { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +import type { MigrationAdapter, RunMode } from "./types.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); + +const SUPABASE_ACCESS_TOKEN = process.env["SUPABASE_ACCESS_TOKEN"]; + +function usage(): never { + process.stderr.write( + `Usage: db-migrate --env [--connection-uri ]\n` + + `\n` + + `Modes:\n` + + ` plan — report pending migrations without mutating the database\n` + + ` apply — apply pending migrations\n` + + `\n` + + `Options:\n` + + ` --env target environment (required)\n` + + `\n` + + `Environment:\n` + + ` SUPABASE_ACCESS_TOKEN Supabase management API token (required for apply)\n` + + ` SUPABASE_PROJECT_REF Supabase project ref (required for apply; wired from orun secrets)\n`, + ); + process.exit(1); +} + +interface ParsedArgs { + mode: RunMode; + env: string; +} + +function parseArgs(argv: string[]): ParsedArgs { + const args = argv.slice(2); + + const mode = args[0] as RunMode | undefined; + if (mode !== "plan" && mode !== "apply") { + usage(); + } + + let env: string | undefined; + + for (let i = 1; i < args.length; i++) { + if (args[i] === "--env" && args[i + 1]) { + env = args[++i]; + } + } + + if (!env) { + const envFromEnv = process.env["MIGRATION_ENV"]; + if (envFromEnv) { + env = envFromEnv; + } + } + + if (!env || !["stage", "prod"].includes(env)) { + process.stderr.write("Error: --env must be 'stage' or 'prod'\n"); + process.exit(1); + } + + return { mode, env }; +} + +async function resolveAdapter( + mode: RunMode, + _env: string, +): Promise { + if (mode === "plan") { + return null; + } + + if (!SUPABASE_ACCESS_TOKEN) { + throw new Error("SUPABASE_ACCESS_TOKEN is required for apply mode"); + } + + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const secret = loadSecretFromEnv(); + + return new SupabaseApiAdapter(secret.project_ref, SUPABASE_ACCESS_TOKEN); +} + +async function main(): Promise { + const { mode, env } = parseArgs(process.argv); + + process.stderr.write(`db-migrate: mode=${mode} env=${env}\n`); + + const adapter = await resolveAdapter(mode, env); + + const result = await runMigrations(manifest, { + mode, + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + if (result.failed) { + process.stderr.write( + `FAILED: migration ${result.failed.id} — ${result.failed.error}\n`, + ); + process.exit(1); + } + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + }; + + process.stdout.write(JSON.stringify(output, null, 2) + "\n"); +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`db-migrate: fatal error — ${message}\n`); + process.exit(1); +}); diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts new file mode 100644 index 0000000..88d97fa --- /dev/null +++ b/packages/db/src/runner/index.ts @@ -0,0 +1,5 @@ +export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, MigrationPlan, MigrationResult } from "./types.js"; +export { runMigrations, buildPlan } from "./runner.js"; +export { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +export { loadConnectionUriFromEnv, loadSecretFromEnv } from "./secrets.js"; +export type { SupabaseSecret } from "./secrets.js"; diff --git a/packages/db/src/runner/runner.ts b/packages/db/src/runner/runner.ts new file mode 100644 index 0000000..9574ca9 --- /dev/null +++ b/packages/db/src/runner/runner.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { MigrationEntry, MigrationManifest } from "../types.js"; +import type { + MigrationPlan, + MigrationResult, + RunnerConfig, +} from "./types.js"; + +const ADVISORY_LOCK_ID = 839_201_008; + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +export function buildPlan( + manifest: MigrationManifest, + appliedMap: Map, + migrationsDir: string, +): MigrationPlan { + const alreadyApplied: string[] = []; + const pending: MigrationEntry[] = []; + const checksumMismatches: MigrationPlan["checksumMismatches"] = []; + + for (const entry of manifest.migrations) { + const appliedChecksum = appliedMap.get(entry.id); + + if (appliedChecksum !== undefined) { + alreadyApplied.push(entry.id); + + const fileChecksum = computeChecksum( + resolve(migrationsDir, entry.path), + ); + + if (appliedChecksum !== fileChecksum || appliedChecksum !== entry.checksum) { + checksumMismatches.push({ + id: entry.id, + expected: appliedChecksum, + actual: fileChecksum, + }); + } + } else { + pending.push(entry); + } + } + + return { alreadyApplied, pending, checksumMismatches }; +} + +export async function runMigrations( + manifest: MigrationManifest, + config: RunnerConfig, +): Promise { + const { adapter, mode, migrationsDir } = config; + const result: MigrationResult = { applied: [], skipped: [], failed: null }; + + // Offline plan: verify checksums then report all migrations as pending. + if (mode === "plan" && adapter === null) { + for (const entry of manifest.migrations) { + const filePath = resolve(migrationsDir, entry.path); + const fileChecksum = computeChecksum(filePath); + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + } + result.applied = manifest.migrations.map((m) => m.id); + return result; + } + + if (!adapter) { + throw new Error("adapter is required for apply mode"); + } + + await adapter.connect(); + + try { + const locked = await adapter.acquireAdvisoryLock(ADVISORY_LOCK_ID); + if (!locked) { + throw new Error( + "Could not acquire migration advisory lock — another runner may be active", + ); + } + + try { + const appliedRows = await adapter.getAppliedMigrations(); + const appliedMap = new Map(appliedRows.map((r) => [r.id, r.checksum])); + + const plan = buildPlan(manifest, appliedMap, migrationsDir); + + if (plan.checksumMismatches.length > 0) { + const ids = plan.checksumMismatches.map((m) => m.id).join(", "); + throw new Error( + `Checksum mismatch for already-applied migrations: ${ids}`, + ); + } + + result.skipped = plan.alreadyApplied; + + if (mode === "plan") { + result.applied = plan.pending.map((m) => m.id); + return result; + } + + for (const entry of plan.pending) { + const sqlPath = resolve(migrationsDir, entry.path); + const sql = readFileSync(sqlPath, "utf-8"); + const fileChecksum = computeChecksum(sqlPath); + + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + + await adapter.beginTransaction(); + try { + await adapter.executeSql(sql); + await adapter.recordMigration(entry); + await adapter.commitTransaction(); + result.applied.push(entry.id); + } catch (err: unknown) { + await adapter.rollbackTransaction(); + const message = err instanceof Error ? err.message : String(err); + result.failed = { id: entry.id, error: message }; + return result; + } + } + } finally { + await adapter.releaseAdvisoryLock(ADVISORY_LOCK_ID); + } + } finally { + await adapter.disconnect(); + } + + return result; +} diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts new file mode 100644 index 0000000..e575b57 --- /dev/null +++ b/packages/db/src/runner/secrets.ts @@ -0,0 +1,62 @@ +// Supabase credentials from the ENVIRONMENT (de-AWS): the supabase terraform +// component wires its outputs into the workspace's project/env secret rung +// (composition wire-secrets step), and orun resolves the keys this runner +// declares in its component secretEnv into the job env — SUPABASE_PROJECT_REF, +// SUPABASE_DB_PASSWORD, SUPABASE_DB_URL. No Secrets Manager, no AWS SDK. + +export interface SupabaseSecret { + project_ref: string; + project_url: string; + database_host: string; + database_port: string; + database_name: string; + database_user: string; + database_password: string; + connection_uri: string; +} + +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv (wired from the supabase component's outputs)`, + ); + } + return value; +} + +/** Assembles the credential document from the wired env vars. The derived + * fields (host/port/db/user) follow the same convention the supabase + * component's payload always used. */ +export function loadSecretFromEnv(): SupabaseSecret { + const projectRef = requireEnv("SUPABASE_PROJECT_REF"); + const password = requireEnv("SUPABASE_DB_PASSWORD"); + const host = `db.${projectRef}.supabase.co`; + const connectionUri = + process.env["SUPABASE_DB_URL"]?.trim() || + `postgresql://postgres:${encodeURIComponent(password)}@${host}:5432/postgres`; + return { + project_ref: projectRef, + project_url: `https://${projectRef}.supabase.co`, + database_host: host, + database_port: "5432", + database_name: "postgres", + database_user: "postgres", + database_password: password, + connection_uri: connectionUri, + }; +} + +/** Direct or pooler connection URI. When a pooler region is provided, use the + * Supabase session pooler to avoid IPv6 connectivity issues with the direct + * database host — the pooler has IPv4 addresses and supports session-level + * advisory locks and transactions. */ +export function loadConnectionUriFromEnv(poolerRegion?: string): string { + const secret = loadSecretFromEnv(); + if (poolerRegion) { + const poolerHost = `aws-0-${poolerRegion}.pooler.supabase.com`; + const user = `postgres.${secret.project_ref}`; + return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(secret.database_password)}@${poolerHost}:6543/${secret.database_name}`; + } + return secret.connection_uri; +} diff --git a/packages/db/src/runner/supabase-api-adapter.ts b/packages/db/src/runner/supabase-api-adapter.ts new file mode 100644 index 0000000..e7e400c --- /dev/null +++ b/packages/db/src/runner/supabase-api-adapter.ts @@ -0,0 +1,93 @@ +import type { MigrationEntry } from "../types.js"; +import type { AppliedMigration, MigrationAdapter } from "./types.js"; + +// The Management API's origin. SUPABASE_API_URL overrides it so a test can +// put a local Postgres behind a stand-in for the one endpoint used here; a +// deployment never sets it. +const SUPABASE_API_BASE = (process.env["SUPABASE_API_URL"] ?? "https://api.supabase.com").replace(/\/+$/, ""); + +export class SupabaseApiAdapter implements MigrationAdapter { + private projectRef: string; + private accessToken: string; + + constructor(projectRef: string, accessToken: string) { + this.projectRef = projectRef; + this.accessToken = accessToken; + } + + async connect(): Promise { /* stateless HTTP — no persistent connection */ } + async disconnect(): Promise { /* no-op */ } + + // Advisory locks are session-scoped and can't be held across HTTP calls. + // Idempotent ON CONFLICT DO NOTHING in recordMigration protects against + // duplicate application when concurrent runners are unlikely. + async acquireAdvisoryLock(_lockId: number): Promise { return true; } + async releaseAdvisoryLock(_lockId: number): Promise { /* no-op */ } + + async getAppliedMigrations(): Promise { + try { + const rows = await this.query( + `SELECT id, context, checksum, applied_at::text AS applied_at + FROM _migrations.applied ORDER BY id`, + ); + return rows as unknown as AppliedMigration[]; + } catch (err: unknown) { + const msg = err instanceof Error ? err.message : String(err); + // Table doesn't exist yet — first-ever run. + if (msg.includes("does not exist")) { + return []; + } + throw err; + } + } + + // Transactions: each step is sent immediately in autocommit mode. + // The migration SQL and record insertion are sent as separate calls. + // Migrations must be idempotent; the runner's ON CONFLICT DO NOTHING + // in recordMigration ensures safe re-runs. + async beginTransaction(): Promise { /* no-op */ } + async commitTransaction(): Promise { /* no-op */ } + async rollbackTransaction(): Promise { /* no-op */ } + + async executeSql(sql: string): Promise { + await this.query(sql); + } + + async recordMigration(entry: MigrationEntry): Promise { + const id = entry.id.replace(/'/g, "''"); + const context = entry.context.replace(/'/g, "''"); + const checksum = entry.checksum.replace(/'/g, "''"); + await this.query( + `INSERT INTO _migrations.applied (id, context, checksum) + VALUES ('${id}', '${context}', '${checksum}') + ON CONFLICT (id) DO NOTHING`, + ); + } + + private async query(sql: string): Promise[]> { + const url = `${SUPABASE_API_BASE}/v1/projects/${this.projectRef}/database/query`; + const response = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ query: sql }), + }); + + if (!response.ok) { + const body = await response.text(); + let message = `HTTP ${response.status}`; + try { + const parsed = JSON.parse(body) as { message?: string; error?: string }; + message = parsed.message ?? parsed.error ?? body; + } catch { + message = body || message; + } + throw new Error(message); + } + + const data = await response.json(); + return Array.isArray(data) ? data as Record[] : []; + } +} diff --git a/packages/db/src/runner/types.ts b/packages/db/src/runner/types.ts new file mode 100644 index 0000000..849d74a --- /dev/null +++ b/packages/db/src/runner/types.ts @@ -0,0 +1,41 @@ +import type { MigrationEntry } from "../types.js"; + +export interface AppliedMigration { + id: string; + context: string; + checksum: string; + applied_at: string; +} + +export interface MigrationAdapter { + connect(): Promise; + disconnect(): Promise; + acquireAdvisoryLock(lockId: number): Promise; + releaseAdvisoryLock(lockId: number): Promise; + getAppliedMigrations(): Promise; + beginTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + executeSql(sql: string): Promise; + recordMigration(entry: MigrationEntry): Promise; +} + +export type RunMode = "plan" | "apply"; + +export interface RunnerConfig { + mode: RunMode; + migrationsDir: string; + adapter: MigrationAdapter | null; +} + +export interface MigrationPlan { + alreadyApplied: string[]; + pending: MigrationEntry[]; + checksumMismatches: Array<{ id: string; expected: string; actual: string }>; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + failed: { id: string; error: string } | null; +} diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts new file mode 100644 index 0000000..fad6973 --- /dev/null +++ b/packages/db/src/types.ts @@ -0,0 +1,20 @@ +// The migration manifest's shape. A "context" names the slice of the schema +// a migration belongs to: `control` is the runner's own tracking schema, +// `app` is the template's. Add contexts here when a port grows bounded +// contexts of its own. +export const BOUNDED_CONTEXTS = ["control", "app"] as const; + +export type BoundedContext = (typeof BOUNDED_CONTEXTS)[number]; + +export interface MigrationEntry { + id: string; + context: BoundedContext; + path: string; + checksum: string; + description: string; +} + +export interface MigrationManifest { + version: 1; + migrations: MigrationEntry[]; +} diff --git a/packages/db/tsconfig.build.json b/packages/db/tsconfig.build.json new file mode 100644 index 0000000..c6fb252 --- /dev/null +++ b/packages/db/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + } +} diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..5a609a8 --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/next-config/transpile.ts b/packages/next-config/transpile.ts index 484659d..eeea1d7 100644 --- a/packages/next-config/transpile.ts +++ b/packages/next-config/transpile.ts @@ -15,7 +15,9 @@ export const workspacePackages = (appDir: string): string[] => { const manifest = JSON.parse( readFileSync(path.join(root, entry.name, "package.json"), "utf8") ) as { name?: string }; - return manifest.name ? [manifest.name] : []; + // The upstream packages, which the apps import; not this repository's + // own (`@app/db`, the migration runner, is no app's dependency). + return manifest.name?.startsWith("@repo/") ? [manifest.name] : []; } catch { return []; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 90005b0..0ee568a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -582,6 +582,21 @@ importers: specifier: ^5.9.3 version: 5.9.3 + packages/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: 25.3.5 + version: 25.3.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + packages/design-system: dependencies: '@hookform/resolvers': @@ -1206,6 +1221,30 @@ importers: specifier: ^3.2.4 version: 3.2.4(@types/debug@4.1.13)(@types/node@25.3.5)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.36.0)(yaml@2.9.1) + tests/db: + devDependencies: + '@app/db': + specifier: workspace:* + version: link:../../packages/db + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@electric-sql/pglite': + specifier: 0.5.8 + version: 0.5.8 + '@types/node': + specifier: 25.3.5 + version: 25.3.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.13)(@types/node@25.3.5)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.36.0)(yaml@2.9.1) + tests/web: devDependencies: '@app/eslint-config': @@ -1778,6 +1817,9 @@ packages: '@egjs/list-differ@1.0.1': resolution: {integrity: sha512-OTFTDQcWS+1ZREOdCWuk5hCBgYO4OsD30lXcOCyVOAjXMhgL5rBRDnt/otb6Nz8CzU0L/igdcaQBDLWc4t9gvg==} + '@electric-sql/pglite@0.5.8': + resolution: {integrity: sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==} + '@emnapi/core@1.10.0': resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} @@ -8839,6 +8881,8 @@ snapshots: '@egjs/list-differ@1.0.1': {} + '@electric-sql/pglite@0.5.8': {} + '@emnapi/core@1.10.0': dependencies: '@emnapi/wasi-threads': 1.2.1 diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..ca3c0e0 --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests + description: The migrations' tests (the manifest and its checksums, each migration the twin of the app's drizzle-kit one, and row-level security on every table in public after every migration, on an in-process Postgres) +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/db/package.json b/tests/db/package.json new file mode 100644 index 0000000..373b645 --- /dev/null +++ b/tests/db/package.json @@ -0,0 +1,21 @@ +{ + "name": "@app/db-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "lint": "eslint src" + }, + "devDependencies": { + "@app/db": "workspace:*", + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@electric-sql/pglite": "0.5.8", + "@types/node": "25.3.5", + "typescript": "^5.8.3", + "vitest": "^3.2.4" + } +} diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..6eeec39 --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { manifest } from "@app/db/manifest"; +import { buildPlan, runMigrations } from "@app/db/runner"; + +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +describe("the migration manifest (packages/db)", () => { + it("starts with the control migration and names every file with its checksum", () => { + expect(manifest.migrations[0]?.id).toBe("000_control_baseline"); + for (const entry of manifest.migrations) { + const file = readFileSync(path.join(migrationsDir, entry.path)); + expect(createHash("sha256").update(file).digest("hex"), entry.id).toBe(entry.checksum); + } + }); + + it("plans every migration as pending offline", async () => { + const result = await runMigrations(manifest, { mode: "plan", migrationsDir, adapter: null }); + expect(result.failed).toBeNull(); + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + }); + + it("creates upstream's Prisma model under Prisma's own names", () => { + const sql = readFileSync(path.join(migrationsDir, "010_pages/up.sql"), "utf8"); + expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS "Page"/); + expect(sql).toMatch(/"id" SERIAL NOT NULL/); + expect(sql).toMatch(/"name" TEXT NOT NULL/); + expect(sql).toMatch(/CONSTRAINT "Page_pkey" PRIMARY KEY \("id"\)/); + }); + + it("skips what the database already recorded", () => { + const applied = new Map([[manifest.migrations[0]!.id, manifest.migrations[0]!.checksum]]); + const plan = buildPlan(manifest, applied, migrationsDir); + expect(plan.alreadyApplied).toEqual([manifest.migrations[0]!.id]); + expect(plan.pending.map((m) => m.id)).toEqual(manifest.migrations.slice(1).map((m) => m.id)); + expect(plan.checksumMismatches).toEqual([]); + }); +}); diff --git a/tests/db/src/row-level-security.test.ts b/tests/db/src/row-level-security.test.ts new file mode 100644 index 0000000..39d626f --- /dev/null +++ b/tests/db/src/row-level-security.test.ts @@ -0,0 +1,108 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { PGlite } from "@electric-sql/pglite"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { manifest } from "@app/db/manifest"; + +// Supabase's Data API (PostgREST) serves the `public` schema to anyone holding +// the project's anon key. Migration 020 enables row-level security, with no +// policy, on every table there: `anon` and `authenticated` get nothing, and the +// app — which owns the tables — keeps everything. These run every migration +// db-migrate applies, in the manifest's order, on a real Postgres in process +// (PGlite: Postgres compiled to WASM), and read the catalog it leaves. +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); +const sqlOf = (rel: string) => readFileSync(path.join(migrationsDir, rel), "utf8"); + +async function migrated(): Promise { + const db = new PGlite(); + for (const entry of manifest.migrations) { + await db.exec(sqlOf(entry.path)); + } + return db; +} + +type Rel = { relname: string; relrowsecurity: boolean; relforcerowsecurity: boolean }; +const PUBLIC_TABLES = ` + select c.relname, c.relrowsecurity, c.relforcerowsecurity + from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind in ('r', 'p') + order by c.relname`; + +describe("row-level security on public (after every migration)", () => { + let db: PGlite; + beforeAll(async () => { + db = await migrated(); + }, 60_000); + + it("leaves no table in public without row-level security", async () => { + const { rows } = await db.query(PUBLIC_TABLES); + // Not vacuous: the template's table is there. + expect(rows.map((r) => r.relname)).toEqual(["Page"]); + expect(rows.filter((r) => !r.relrowsecurity).map((r) => r.relname)).toEqual([]); + }); + + it("adds no policy and forces none — the owner is never subject to it", async () => { + const { rows } = await db.query(PUBLIC_TABLES); + expect(rows.filter((r) => r.relforcerowsecurity).map((r) => r.relname)).toEqual([]); + const policies = await db.query<{ n: number }>( + "select count(*)::int as n from pg_policies where schemaname = 'public'", + ); + expect(policies.rows[0]!.n).toBe(0); + }); + + it("gives a role with the Data API's grants nothing, and the owner everything", async () => { + await db.exec(`insert into "Page" (name) values ('owner row')`); + // What Supabase grants `anon` on public by default — so a refusal below is + // row-level security's, not a missing grant's. + await db.exec(` + create role anon nologin; + grant usage on schema public to anon; + grant select, insert, update, delete on all tables in schema public to anon; + grant usage on all sequences in schema public to anon;`); + await db.exec("set role anon"); + try { + const seen = await db.query<{ n: number }>(`select count(*)::int as n from "Page"`); + expect(seen.rows[0]!.n).toBe(0); + await expect(db.exec(`insert into "Page" (name) values ('anon row')`)).rejects.toThrow( + /row-level security/, + ); + } finally { + await db.exec("reset role"); + } + const owner = await db.query<{ n: number }>(`select count(*)::int as n from "Page"`); + expect(owner.rows[0]!.n).toBe(1); + }); +}); + +describe("migration 020's guard", () => { + // The guard names `postgres`, the role Hyperdrive connects as, which PGlite + // cannot take SUPERUSER from. Pointed instead at a role that neither owns the + // tables nor bypasses RLS, it must refuse — and enable nothing. + const migration = sqlOf("020_row_level_security/up.sql"); + const aimedAt = (role: string) => + migration.replaceAll("rolname = 'postgres'", `rolname = '${role}'`).replaceAll("<> 'postgres'", `<> '${role}'`); + + async function beforeRls(): Promise { + const db = new PGlite(); + for (const entry of manifest.migrations.filter((m) => m.id < "020")) { + await db.exec(sqlOf(entry.path)); + } + return db; + } + + it("refuses when the app's role would be locked out, enabling nothing", async () => { + const db = await beforeRls(); + await db.exec("create role app_without_bypass nologin"); + await expect(db.exec(aimedAt("app_without_bypass"))).rejects.toThrow(/would lock the app out/); + const { rows } = await db.query(PUBLIC_TABLES); + expect(rows.filter((r) => r.relrowsecurity)).toEqual([]); + }, 60_000); + + it("passes for a role with BYPASSRLS", async () => { + const db = await beforeRls(); + await db.exec("create role app_with_bypass nologin bypassrls"); + await db.exec(aimedAt("app_with_bypass")); + const { rows } = await db.query(PUBLIC_TABLES); + expect(rows.every((r) => r.relrowsecurity)).toBe(true); + }, 60_000); +}); diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json new file mode 100644 index 0000000..47d9ecc --- /dev/null +++ b/tests/db/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/tests/db/vitest.config.ts b/tests/db/vitest.config.ts new file mode 100644 index 0000000..ce36a74 --- /dev/null +++ b/tests/db/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["src/**/*.test.ts"], + environment: "node", + }, +});