From 7572ca371fd77757cb4363dacd229b6e6f79f386 Mon Sep 17 00:00:00 2001 From: Rahul Varghese Date: Thu, 29 Oct 2026 01:24:41 +0000 Subject: [PATCH] SL2: the Supabase project from Terraform, the schema through db-migrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit infra/terraform/supabase (supabase-starter's root, named for this repository) creates a Supabase project per environment, points its Auth at the Worker with email confirmation off, and publishes WIRING_SUPABASE (the URL and publishable key) and the three database credentials — no service-role key. packages/db (@saas/db) carries upstream's two migrations and its seed byte for byte as 010_init, 020_auth_hook and 030_seed, applied by db-migrate over the Management API's query endpoint, each checked against its manifest checksum. Then the runner switches on the custom access-token hook upstream's config.toml asks for — a PATCH of the project's Auth config, read back — after the migrations that create its function, so Auth never points at one that does not exist yet. The app now waits on supabase and db-migrate, enforced on main and advisory on a pull request, and reads its wiring per environment. tests/db proves the schema on PGlite: the roles trigger, the hook's claims and grants, every policy by role, the Realtime publication and its replica identity. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- apps/web/component.yaml | 49 ++- apps/web/docs/architecture.md | 7 + apps/web/docs/overview.md | 3 +- infra/db-migrate/component.yaml | 76 +++++ infra/db-migrate/docs/architecture.md | 19 ++ infra/db-migrate/docs/overview.md | 20 ++ infra/db-migrate/docs/runbook.md | 19 ++ infra/terraform/supabase/component.yaml | 76 +++++ infra/terraform/supabase/docs/architecture.md | 34 +++ infra/terraform/supabase/docs/overview.md | 20 ++ infra/terraform/supabase/docs/runbook.md | 20 ++ .../supabase/terraform/.terraform.lock.hcl | 73 +++++ infra/terraform/supabase/terraform/adopt.tf | 50 ++++ infra/terraform/supabase/terraform/main.tf | 280 ++++++++++++++++++ packages/db/component.yaml | 33 +++ packages/db/docs/architecture.md | 11 + packages/db/docs/overview.md | 20 ++ packages/db/docs/runbook.md | 25 ++ packages/db/eslint.config.js | 2 + packages/db/package.json | 30 ++ packages/db/src/auth-config.ts | 21 ++ packages/db/src/index.ts | 5 + packages/db/src/manifest.ts | 48 +++ packages/db/src/migrations/000_control/up.sql | 16 + packages/db/src/migrations/010_init/up.sql | 164 ++++++++++ .../db/src/migrations/020_auth_hook/up.sql | 58 ++++ packages/db/src/migrations/030_seed/up.sql | 23 ++ packages/db/src/runner/cli.ts | 130 ++++++++ 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 | 120 ++++++++ packages/db/src/runner/types.ts | 41 +++ packages/db/src/types.ts | 20 ++ packages/db/tsconfig.build.json | 7 + packages/db/tsconfig.json | 10 + pnpm-lock.yaml | 50 +++- specs/epics/supabase-slack-clone/README.md | 2 +- tests/db/component.yaml | 31 ++ tests/db/docs/architecture.md | 9 + tests/db/docs/overview.md | 20 ++ tests/db/docs/runbook.md | 26 ++ tests/db/eslint.config.js | 2 + tests/db/package.json | 21 ++ tests/db/src/auth-config.test.ts | 57 ++++ tests/db/src/migrations.test.ts | 86 ++++++ tests/db/src/schema.test.ts | 178 +++++++++++ tests/db/src/supabase.ts | 56 ++++ tests/db/tsconfig.json | 11 + tests/db/vitest.config.ts | 8 + tooling/migrations/manifest.mjs | 42 +++ 51 files changed, 2324 insertions(+), 12 deletions(-) create mode 100644 infra/db-migrate/component.yaml create mode 100644 infra/db-migrate/docs/architecture.md create mode 100644 infra/db-migrate/docs/overview.md create mode 100644 infra/db-migrate/docs/runbook.md create mode 100644 infra/terraform/supabase/component.yaml create mode 100644 infra/terraform/supabase/docs/architecture.md create mode 100644 infra/terraform/supabase/docs/overview.md create mode 100644 infra/terraform/supabase/docs/runbook.md 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/docs/architecture.md create mode 100644 packages/db/docs/overview.md create mode 100644 packages/db/docs/runbook.md create mode 100644 packages/db/eslint.config.js create mode 100644 packages/db/package.json create mode 100644 packages/db/src/auth-config.ts 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_init/up.sql create mode 100644 packages/db/src/migrations/020_auth_hook/up.sql create mode 100644 packages/db/src/migrations/030_seed/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/docs/architecture.md create mode 100644 tests/db/docs/overview.md create mode 100644 tests/db/docs/runbook.md create mode 100644 tests/db/eslint.config.js create mode 100644 tests/db/package.json create mode 100644 tests/db/src/auth-config.test.ts create mode 100644 tests/db/src/migrations.test.ts create mode 100644 tests/db/src/schema.test.ts create mode 100644 tests/db/src/supabase.ts create mode 100644 tests/db/tsconfig.json create mode 100644 tests/db/vitest.config.ts create mode 100644 tooling/migrations/manifest.mjs diff --git a/apps/web/component.yaml b/apps/web/component.yaml index a641089..a7602ca 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -22,10 +22,42 @@ spec: # Its own lane per environment: the Next.js build is the longest job in the # plan, and a shared lane would wait on it. lane: isolated - # The Supabase project this Worker talks to arrives in SL2, from the - # `supabase` Terraform root: until then every build inlines the committed - # fixture render of the wrangler config, whose placeholder project nothing - # calls. + # INFRA BEFORE APP. The Worker's config carries its project's URL and anon + # key, rendered in the build from the wiring document the `supabase` root + # lease-publishes after its apply, and the browser reads the tables — and + # signs in through the access-token hook — that db-migrate creates and + # enables in that project. A job resolves its secrets when it STARTS, so on + # a merge to main this deploy waits for both (enforced) — one convergence + # runs supabase → db-migrate → web per environment, and the document and the + # schema are there. A pull request deploys nothing, so nothing on one waits + # (advisory). + dependsOn: + - component: supabase + 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 the supabase root lease-publishes, one per deployed + # environment: the project's URL and publishable (anon) key, rendered into + # wrangler.jsonc by the build and inlined into the bundle; + # tooling/wire/live.mjs picks this job's and fails loudly when it is not + # there. OPTIONAL references, so a job resolves the ones that exist: stage's + # deploy waits on stage's chain only, and while the bootstrap runs stage and + # prod side by side, prod's document may not be published yet when stage's + # deploy starts (a required reference would fail that job). The dev verify + # lane renders nothing and reads neither. The chat needs no server secret: + # the browser talks to Supabase with the publishable key, and row-level + # security is what protects the data. + optionalSecretEnv: + WIRING_SUPABASE_STAGE: "secret://supabase-slack-clone/supabase-slack-clone/stage/WIRING_SUPABASE" + WIRING_SUPABASE_PROD: "secret://supabase-slack-clone/supabase-slack-clone/prod/WIRING_SUPABASE" subscribe: environments: - name: dev @@ -69,9 +101,12 @@ spec: installCommand: pnpm install --frozen-lockfile # wrangler.jsonc is COMMITTED — the fixture render, so the composition's # structure check (`test -f wrangler.jsonc`, before the build, in a fresh - # checkout) passes, and `next build` inlines the project it names - # (next.config.ts). - buildCommand: pnpm exec turbo run build --filter=@app/web + # checkout) passes. Stage and prod re-render it here, in their own job + # tree, from this environment's wiring document, so the Worker's vars and + # the URL and key `next build` inlines (next.config.ts) are the real + # project's; dev verifies with the fixture and has no wiring. + # ${ORUN_ENVIRONMENT} the runner sets for every step. + buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components supabase --env "${ORUN_ENVIRONMENT}"; fi && pnpm exec turbo run build --filter=@app/web # Smoke: the sign-in page renders, its password field included, and /api/health # answers ok — which only the Worker can, by asking the project's Auth with diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md index b5caa2c..e9706ad 100644 --- a/apps/web/docs/architecture.md +++ b/apps/web/docs/architecture.md @@ -18,3 +18,10 @@ Built by the turbo pipeline from `apps/web` and deployed with wrangler. ## Variables `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, `NEXT_PUBLIC_SUPABASE_URL`. + +## Wiring + +Resolved at deploy time from secrets the infrastructure lanes publish (names only): + +- `WIRING_SUPABASE_PROD` (optional) +- `WIRING_SUPABASE_STAGE` (optional) diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md index e14b4f9..a0f472c 100644 --- a/apps/web/docs/overview.md +++ b/apps/web/docs/overview.md @@ -13,7 +13,8 @@ A Cloudflare Worker with Static Assets (server rendering plus static files), dep ## Depends on -- (none) +- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the chat, and wires the URL and key into orun secrets +- **db-migrate** — Applies the chat schema (packages/db's migrations) to the stage and prod Supabase projects, then switches on the access-token hook it needs ## Depended on by diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml new file mode 100644 index 0000000..0e7fe3f --- /dev/null +++ b/infra/db-migrate/component.yaml @@ -0,0 +1,76 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-migrate + description: Applies the chat schema (packages/db's migrations) to the stage and prod Supabase projects, then switches on the access-token hook it needs + labels: + domain: infra + scope: database + team: platform + layer: data + +spec: + type: db-migrate + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: infra + + # THE SCHEMA BETWEEN THE PROJECT AND THE APP. Migrations reach the project + # the `supabase` component creates through the Management API, with the + # project ref and credentials that component lease-publishes after its + # apply — and a job resolves its secrets when it STARTS, so on a merge to + # main this waits for that environment's apply (enforced). apps/web waits on + # this the same way, so one convergence runs supabase → db-migrate → web per + # environment. A pull request applies nothing (this plans offline there), so + # nothing on one waits (advisory). `db` is the package this builds and runs; + # a change to it re-plans this. + dependsOn: + - component: db + - component: supabase + 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: supabase-slack-clone + + # Everything the runner needs, all resolved from orun secrets: a short-lived + # Management-API token minted fresh per run from the Supabase integration + # (management-access template), and the project ref and its database + # credentials, which the `supabase` component lease-publishes. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://supabase-slack-clone/supabase-slack-clone/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + SUPABASE_PROJECT_REF: "secret://supabase-slack-clone/supabase-slack-clone/{{ .environment }}/SUPABASE_PROJECT_REF" + SUPABASE_DB_PASSWORD: "secret://supabase-slack-clone/supabase-slack-clone/{{ .environment }}/SUPABASE_DB_PASSWORD" + SUPABASE_DB_URL: "secret://supabase-slack-clone/supabase-slack-clone/{{ .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/db-migrate/docs/architecture.md b/infra/db-migrate/docs/architecture.md new file mode 100644 index 0000000..793d40a --- /dev/null +++ b/infra/db-migrate/docs/architecture.md @@ -0,0 +1,19 @@ +# db-migrate — architecture + +Applies the migrations under `packages/db/src/migrations` in order, recording each one +it applies so a run only ever applies what is new. An already-applied migration +is never edited: a change is a new, later migration. + +## Migrations + +- `000_control` +- `010_init` +- `020_auth_hook` +- `030_seed` + +## Resolved at run time (names only) + +- `SUPABASE_ACCESS_TOKEN` +- `SUPABASE_DB_PASSWORD` +- `SUPABASE_DB_URL` +- `SUPABASE_PROJECT_REF` diff --git a/infra/db-migrate/docs/overview.md b/infra/db-migrate/docs/overview.md new file mode 100644 index 0000000..fcead13 --- /dev/null +++ b/infra/db-migrate/docs/overview.md @@ -0,0 +1,20 @@ +# db-migrate + +Applies the chat schema (packages/db's migrations) to the stage and prod Supabase projects, then switches on the access-token hook it needs + +Applies this repository's ordered database migrations per environment: plan on pull requests, apply on merge to `main`. + +| | | +| ------------ | ------------------------------------------------------------------------------------------ | +| Type | `db-migrate` | +| Source | `infra/db-migrate` | +| Environments | `stage`: `plan`, `apply` on a push to `main` · `prod`: `plan`, `apply` on a push to `main` | + +## Depends on + +- **db** — The schema as migrations, and the runner that applies them over the Supabase Management API (built by the db-migrate component before it plans or applies) +- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the chat, and wires the URL and key into orun secrets + +## Depended on by + +- **web** — The team chat (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) diff --git a/infra/db-migrate/docs/runbook.md b/infra/db-migrate/docs/runbook.md new file mode 100644 index 0000000..04a50d1 --- /dev/null +++ b/infra/db-migrate/docs/runbook.md @@ -0,0 +1,19 @@ +# db-migrate — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **An applied migration's file changed**: the run stops rather than guess. + Restore the file and write the change as a new migration. +- **The database is unreachable**: the infrastructure lane it depends on has + not applied for this environment; that lane runs first in a convergence. diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml new file mode 100644 index 0000000..9ce7681 --- /dev/null +++ b/infra/terraform/supabase/component.yaml @@ -0,0 +1,76 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: supabase + description: Provisions Supabase projects for stage and prod, points their Auth at the chat, and wires the URL and key into orun secrets + labels: + domain: infra + scope: database + +spec: + type: terraform + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + 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 + # The app's Worker, which Auth's Site URL and redirect allow-list name: + # -web- on this workers.dev subdomain — the same value + # apps/web/component.yaml carries (TF_VAR_workersDevSubdomain). + workersDevSubdomain: your-workers-subdomain + # "false": sign-up signs the user straight in, because a project without + # SMTP of its own emails only its organization's members. "true" once the + # project sends email (the product's README, "Email"). + authEmailConfirmation: "false" + # SEC-JOB: post-apply, these outputs are queued on the runner's sink and + # lease-published onto the project/{{env}} rung by the runner. The + # project's three database credentials (db-migrate reads them); + # and WIRING_SUPABASE — the project URL and the publishable (anon) key, + # the document the app's build renders into its config. Nothing reads a + # service-role key, so none is published. + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri,WIRING_SUPABASE=wiring" + + # 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://supabase-slack-clone/supabase-slack-clone/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + TF_VAR_supabaseOrgId: "secret://supabase-slack-clone/supabase-slack-clone/{{ .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/docs/architecture.md b/infra/terraform/supabase/docs/architecture.md new file mode 100644 index 0000000..86f94a7 --- /dev/null +++ b/infra/terraform/supabase/docs/architecture.md @@ -0,0 +1,34 @@ +# supabase — architecture + +A `terraform` root at `infra/terraform/supabase/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `random_password.db_password` +- `supabase_project.this` +- `terraform_data.project_ready` +- `supabase_settings.this` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +| ---------------------- | ------------------- | +| `SUPABASE_PROJECT_REF` | `project_ref` | +| `SUPABASE_DB_PASSWORD` | `database_password` | +| `SUPABASE_DB_URL` | `connection_uri` | +| `WIRING_SUPABASE` | `wiring` | + +## Resolved at run time (names only) + +- `SUPABASE_ACCESS_TOKEN` +- `TF_VAR_supabaseOrgId` diff --git a/infra/terraform/supabase/docs/overview.md b/infra/terraform/supabase/docs/overview.md new file mode 100644 index 0000000..1803a24 --- /dev/null +++ b/infra/terraform/supabase/docs/overview.md @@ -0,0 +1,20 @@ +# supabase + +Provisions Supabase projects for stage and prod, points their Auth at the chat, and wires the URL and key into orun secrets + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/supabase` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **db-migrate** — Applies the chat schema (packages/db's migrations) to the stage and prod Supabase projects, then switches on the access-token hook it needs +- **web** — The team chat (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) diff --git a/infra/terraform/supabase/docs/runbook.md b/infra/terraform/supabase/docs/runbook.md new file mode 100644 index 0000000..d240972 --- /dev/null +++ b/infra/terraform/supabase/docs/runbook.md @@ -0,0 +1,20 @@ +# supabase — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. 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..c7a0731 --- /dev/null +++ b/infra/terraform/supabase/terraform/adopt.tf @@ -0,0 +1,50 @@ +# --- 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 re-wires +# from those in the same run (the Worker reaches the project over HTTPS with +# its keys, not the password), 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..f0250e2 --- /dev/null +++ b/infra/terraform/supabase/terraform/main.tf @@ -0,0 +1,280 @@ +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 = "supabase-slack-clone" +} + +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 +} + +# The workers.dev subdomain the app's Worker answers on (the component's +# `workersDevSubdomain` parameter, surfaced as TF_VAR_workersDevSubdomain — +# the same value apps/web/component.yaml carries). Required, like the two +# above: Supabase Auth sends its links to this origin. +variable "workersDevSubdomain" { + type = string +} + +# Whether a new user must confirm their email before signing in (the +# component's `authEmailConfirmation` parameter). Off by default, because a +# fresh project sends email only to its organization's own members until it +# has an SMTP server of its own: with confirmation on, nobody else could sign +# up. Turn it on once SMTP is set (the product's README, "Email"). +variable "authEmailConfirmation" { + type = bool + default = false +} + +# --- Locals --- + +# The product's own origin when the environment has a custom domain: SITE_URL +# under its `env:` in intent.yaml, which the runner exports to this job as it +# does to the app's build (apps/web/component.yaml) — one setting, so Auth's +# links and the app's absolute URLs name the same origin. Empty when unset. +data "external" "site_url" { + program = ["bash", "-c", "jq -n --arg url \"$${SITE_URL:-}\" '{url: $url}'"] +} + +locals { + supabase_org_id = var.supabaseOrgId + supabase_region = var.supabaseRegion + project_name = "${var.repo}-${var.environment}" + # The environment's Worker, as apps/web/component.yaml names it: + # -web- on the account's workers.dev subdomain — unless SITE_URL + # names the environment's custom domain. + worker_origin = "https://${var.repo}-web-${var.environment}.${var.workersDevSubdomain}.workers.dev" + app_origin = coalesce(trimsuffix(data.external.site_url.result.url, "/"), local.worker_origin) +} + +# --- 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 outputs component.yaml's +# `secretOutputs` names, which the runner lease-publishes onto the project's +# environment rung after the apply (never argv, never a log). The project's +# three database credentials below are published for the owner and for any +# later step that migrates the database; the app reads the `wiring` document +# further down. 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 +} + +# --- The project, up --- +# +# The provider returns from a create as soon as the Management API accepts it, +# and a project takes minutes to come up. Its API keys and its Auth +# configuration are read and written below; both wait here until the project +# reports ACTIVE_HEALTHY (ten minutes at most). On an adopted or existing +# project this answers at once. Same tools as adopt.tf: bash, curl, jq and the +# brokered SUPABASE_ACCESS_TOKEN in the environment. + +resource "terraform_data" "project_ready" { + triggers_replace = [supabase_project.this.id] + + provisioner "local-exec" { + interpreter = ["bash", "-c"] + environment = { + PROJECT_REF = supabase_project.this.id + } + command = <<-EOT + set -uo pipefail + for _ in $(seq 1 60); do + status="$(curl -fsS --retry 2 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects/$PROJECT_REF" | jq -r '.status // empty')" + [ "$status" = ACTIVE_HEALTHY ] && { echo "supabase: $PROJECT_REF is $status"; exit 0; } + echo "supabase: $PROJECT_REF is $${status:-not answering yet}; waiting" + sleep 10 + done + echo "supabase: $PROJECT_REF did not report ACTIVE_HEALTHY within ten minutes" >&2 + exit 1 + EOT + } +} + +# --- API keys --- +# +# The chat talks to Supabase from the browser — Auth, the Data API and +# Realtime — with the project URL and the publishable (anon) key; row-level +# security is what protects the data, the key is public by design. Both leave +# this module in ONE wiring document, WIRING_SUPABASE, which the app's deploy +# renders into its wrangler config and inlines into its build. The +# service-role key is not read: nothing in this product runs with it. + +data "supabase_apikeys" "this" { + project_ref = supabase_project.this.id + depends_on = [terraform_data.project_ready] +} + +output "wiring" { + description = "Wiring document for the app's deploy-time configuration (pushed to orun secrets as WIRING_SUPABASE)" + value = jsonencode({ + supabase_url = "https://${supabase_project.this.id}.supabase.co" + supabase_anon_key = data.supabase_apikeys.this.anon_key + }) + sensitive = true +} + +# --- Auth --- +# +# A fresh project's Auth sends its links to http://localhost:3000 and asks +# every new user to confirm an email address it can only deliver to the +# organization's own members. So the app's Worker is the Site URL and the one +# allowed redirect origin, and sign-up signs the user straight in unless +# `authEmailConfirmation` is on. Only these three keys are managed; every +# other Auth setting stays the project's own, and the dashboard can change it. +# +# NOT the access-token hook the chat's roles need: it names a function a +# migration creates, so the migration runner switches it on right after the +# migrations (packages/db/src/auth-config.ts) — set here, Auth would point at +# a function that does not exist yet on a project's first apply. The two never +# write the same key. + +resource "supabase_settings" "this" { + project_ref = supabase_project.this.id + + auth = jsonencode({ + site_url = local.app_origin + uri_allow_list = "${local.app_origin}/**" + mailer_autoconfirm = !var.authEmailConfirmation + }) + + depends_on = [terraform_data.project_ready] +} diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..b50d8c7 --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,33 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db + description: The schema as migrations, and the runner that applies them over the Supabase Management API (built by the db-migrate component before it plans or applies) +spec: + type: turbo-package + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: data + # Verified where the code is checked — on dev, by every pull request. On a + # merge the db-migrate component builds this package itself in its own job + # before it applies, so stage and prod need no job of their own here. + 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=./ + labels: + team: platform + layer: data diff --git a/packages/db/docs/architecture.md b/packages/db/docs/architecture.md new file mode 100644 index 0000000..3f9b079 --- /dev/null +++ b/packages/db/docs/architecture.md @@ -0,0 +1,11 @@ +# db — architecture + +A workspace package at `packages/db`, consumed by the components that depend +on it. It has no deployed surface of its own. + +## Exports + +- `.` +- `./manifest` +- `./runner` +- `./types` diff --git a/packages/db/docs/overview.md b/packages/db/docs/overview.md new file mode 100644 index 0000000..1179b15 --- /dev/null +++ b/packages/db/docs/overview.md @@ -0,0 +1,20 @@ +# db + +The schema as migrations, and the runner that applies them over the Supabase Management API (built by the db-migrate component before it plans or applies) + +A workspace package built by the turbo pipeline. It deploys nothing itself: its lane type-checks, lints, tests and builds it. + +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `packages/db` | +| Package | `@saas/db` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- **db-migrate** — Applies the chat schema (packages/db's migrations) to the stage and prod Supabase projects, then switches on the access-token hook it needs diff --git a/packages/db/docs/runbook.md b/packages/db/docs/runbook.md new file mode 100644 index 0000000..3fa7445 --- /dev/null +++ b/packages/db/docs/runbook.md @@ -0,0 +1,25 @@ +# db — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @saas/db build +pnpm --filter @saas/db typecheck +pnpm --filter @saas/db lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. 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..6616a77 --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,30 @@ +{ + "name": "@saas/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": "^22.9.0", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/auth-config.ts b/packages/db/src/auth-config.ts new file mode 100644 index 0000000..ce4f6ef --- /dev/null +++ b/packages/db/src/auth-config.ts @@ -0,0 +1,21 @@ +// The Supabase Auth settings this schema needs switched on in the project, +// applied by the migration runner right after the migrations — never before, +// because each names a database object a migration creates. +// +// Upstream sets this in supabase/config.toml ([auth.hook.custom_access_token]) +// and pushes it with `supabase config push`. Here the runner PATCHes the +// project's Auth config through the Management API (the endpoint +// `config push` itself calls) once 020_auth_hook has created +// public.custom_access_token_hook — so from the first sign-in every access +// token carries the user's `user_role` claim, which the row-level security +// policies' public.authorize() and the app's delete buttons read. +// +// Only these keys are written; every other Auth setting stays the project's +// own (the `supabase` Terraform root manages site_url, uri_allow_list and +// mailer_autoconfirm, and never these). +export const authConfig = { + hook_custom_access_token_enabled: true, + hook_custom_access_token_uri: "pg-functions://postgres/public/custom_access_token_hook", +} as const; + +export type AuthConfig = typeof authConfig; diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..dfbcffa --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,5 @@ +export { manifest } from "./manifest.js"; +export { authConfig } from "./auth-config.js"; +export type { AuthConfig } from "./auth-config.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..30bafae --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,48 @@ +import type { MigrationManifest } from "./types.js"; + +// Every migration the runner applies, in order, with the sha256 of its file. +// `pnpm --filter @saas/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_init", + context: "app", + path: "010_init/up.sql", + checksum: + "aa334acde2ceed2169b499969bdf7cba6eb2ee3fb70d8f9a3441d8c6ed625fd9", + description: + "The example's schema (supabase/migrations/20240214102356_init.sql, verbatim): users, channels, messages, user_roles and role_permissions with row-level security, public.authorize() for role-based deletes, the trigger that gives every new auth.users row a profile (and a role by plus-address), and the supabase_realtime publication over channels, messages and users", + }, + { + id: "020_auth_hook", + context: "app", + path: "020_auth_hook/up.sql", + checksum: + "4da1507129a1d0f73658577f9852b9969b501cf8f1dc65133ca89788fd4bfff6", + description: + "The custom access-token hook (supabase/migrations/20240214114147_auth-hook.sql, verbatim): public.custom_access_token_hook adds the user's role to every access token, readable by supabase_auth_admin only; the runner enables it in the project's Auth config after this applies (src/auth-config.ts)", + }, + { + id: "030_seed", + context: "app", + path: "030_seed/up.sql", + checksum: + "4786f8af13181723968fde859a617e9cd0fcd9f94e937d45e96327e02b99a46d", + description: + "The example's seed (supabase/seed.sql, verbatim): the admin and moderator permissions, and the #public and #random channels with a first message each, posted by a bot user who cannot sign in", + }, + ], +}; 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_init/up.sql b/packages/db/src/migrations/010_init/up.sql new file mode 100644 index 0000000..a1ae972 --- /dev/null +++ b/packages/db/src/migrations/010_init/up.sql @@ -0,0 +1,164 @@ +-- +-- For use with https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone +-- + +-- Custom types +create type public.app_permission as enum ('channels.delete', 'messages.delete'); +create type public.app_role as enum ('admin', 'moderator'); +create type public.user_status as enum ('ONLINE', 'OFFLINE'); + +-- USERS +create table public.users ( + id uuid references auth.users not null primary key, -- UUID from auth.users + username text, + status user_status default 'OFFLINE'::public.user_status +); +comment on table public.users is 'Profile data for each user.'; +comment on column public.users.id is 'References the internal Supabase Auth user.'; + +-- CHANNELS +create table public.channels ( + id bigint generated by default as identity primary key, + inserted_at timestamp with time zone default timezone('utc'::text, now()) not null, + slug text not null unique, + created_by uuid references public.users not null +); +comment on table public.channels is 'Topics and groups.'; + +-- MESSAGES +create table public.messages ( + id bigint generated by default as identity primary key, + inserted_at timestamp with time zone default timezone('utc'::text, now()) not null, + message text, + user_id uuid references public.users not null, + channel_id bigint references public.channels on delete cascade not null +); +comment on table public.messages is 'Individual messages sent by each user.'; + +-- USER ROLES +create table public.user_roles ( + id bigint generated by default as identity primary key, + user_id uuid references public.users on delete cascade not null, + role app_role not null, + unique (user_id, role) +); +comment on table public.user_roles is 'Application roles for each user.'; + +-- ROLE PERMISSIONS +create table public.role_permissions ( + id bigint generated by default as identity primary key, + role app_role not null, + permission app_permission not null, + unique (role, permission) +); +comment on table public.role_permissions is 'Application permissions for each role.'; + +-- authorize with role-based access control (RBAC) +create function public.authorize( + requested_permission app_permission +) +returns boolean as $$ +declare + bind_permissions int; +begin + select count(*) + from public.role_permissions + where role_permissions.permission = authorize.requested_permission + and role_permissions.role = (auth.jwt() ->> 'user_role')::public.app_role + into bind_permissions; + + return bind_permissions > 0; +end; +$$ language plpgsql security definer set search_path = public; + +-- Secure the tables +alter table public.users enable row level security; +alter table public.channels enable row level security; +alter table public.messages enable row level security; +alter table public.user_roles enable row level security; +alter table public.role_permissions enable row level security; +create policy "Allow logged-in read access" on public.users for select using ( auth.role() = 'authenticated' ); +create policy "Allow individual insert access" on public.users for insert with check ( auth.uid() = id ); +create policy "Allow individual update access" on public.users for update using ( auth.uid() = id ); +create policy "Allow logged-in read access" on public.channels for select using ( auth.role() = 'authenticated' ); +create policy "Allow individual insert access" on public.channels for insert with check ( auth.uid() = created_by ); +create policy "Allow individual delete access" on public.channels for delete using ( auth.uid() = created_by ); +create policy "Allow authorized delete access" on public.channels for delete using ( authorize('channels.delete') ); +create policy "Allow logged-in read access" on public.messages for select using ( auth.role() = 'authenticated' ); +create policy "Allow individual insert access" on public.messages for insert with check ( auth.uid() = user_id ); +create policy "Allow individual update access" on public.messages for update using ( auth.uid() = user_id ); +create policy "Allow individual delete access" on public.messages for delete using ( auth.uid() = user_id ); +create policy "Allow authorized delete access" on public.messages for delete using ( authorize('messages.delete') ); +create policy "Allow individual read access" on public.user_roles for select using ( auth.uid() = user_id ); + +-- Send "previous data" on change +alter table public.users replica identity full; +alter table public.channels replica identity full; +alter table public.messages replica identity full; + +-- inserts a row into public.users and assigns roles +create function public.handle_new_user() +returns trigger as $$ +declare is_admin boolean; +begin + insert into public.users (id, username) + values (new.id, new.email); + + select count(*) = 1 from auth.users into is_admin; + + if position('+supaadmin@' in new.email) > 0 then + insert into public.user_roles (user_id, role) values (new.id, 'admin'); + elsif position('+supamod@' in new.email) > 0 then + insert into public.user_roles (user_id, role) values (new.id, 'moderator'); + end if; + + return new; +end; +$$ language plpgsql security definer set search_path = auth, public; + +-- trigger the function every time a user is created +create trigger on_auth_user_created + after insert on auth.users + for each row execute procedure public.handle_new_user(); + +/** + * REALTIME SUBSCRIPTIONS + * Only allow realtime listening on public tables. + */ + +begin; + -- remove the realtime publication + drop publication if exists supabase_realtime; + + -- re-create the publication but don't enable it for any tables + create publication supabase_realtime; +commit; + +-- add tables to the publication +alter publication supabase_realtime add table public.channels; +alter publication supabase_realtime add table public.messages; +alter publication supabase_realtime add table public.users; + +/** + * HELPER FUNCTIONS + * Create test user helper method. + */ +create or replace function public.create_user( + email text +) returns uuid + security definer + set search_path = auth +as $$ + declare + user_id uuid; +begin + user_id := extensions.uuid_generate_v4(); + + insert into auth.users (id, email) + values (user_id, email) + returning id into user_id; + + return user_id; +end; +$$ language plpgsql; + diff --git a/packages/db/src/migrations/020_auth_hook/up.sql b/packages/db/src/migrations/020_auth_hook/up.sql new file mode 100644 index 0000000..4ee152b --- /dev/null +++ b/packages/db/src/migrations/020_auth_hook/up.sql @@ -0,0 +1,58 @@ +/** + * AUTH HOOKS + * Create an auth hook to add a custom claim to the access token jwt. + */ + +-- Create the auth hook function +-- https://supabase.com/docs/guides/auth/auth-hooks/custom-access-token-hook +create or replace function public.custom_access_token_hook(event jsonb) +returns jsonb +language plpgsql +stable +as $$ + declare + claims jsonb; + user_role public.app_role; + begin + -- Check if the user is marked as admin in the profiles table + select role into user_role from public.user_roles where user_id = (event->>'user_id')::uuid; + + claims := event->'claims'; + + if user_role is not null then + -- Set the claim + claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role)); + else + claims := jsonb_set(claims, '{user_role}', 'null'); + end if; + + -- Update the 'claims' object in the original event + event := jsonb_set(event, '{claims}', claims); + + -- Return the modified or original event + return event; + end; +$$; + +grant usage on schema public to supabase_auth_admin; + +grant execute + on function public.custom_access_token_hook + to supabase_auth_admin; + +revoke execute + on function public.custom_access_token_hook + from authenticated, anon; + +grant all + on table public.user_roles +to supabase_auth_admin; + +revoke all + on table public.user_roles + from authenticated, anon; + +create policy "Allow auth admin to read user roles" ON public.user_roles +as permissive for select +to supabase_auth_admin +using (true) diff --git a/packages/db/src/migrations/030_seed/up.sql b/packages/db/src/migrations/030_seed/up.sql new file mode 100644 index 0000000..5e20801 --- /dev/null +++ b/packages/db/src/migrations/030_seed/up.sql @@ -0,0 +1,23 @@ +insert into public.role_permissions (role, permission) +values + ('admin', 'channels.delete'), + ('admin', 'messages.delete'), + ('moderator', 'messages.delete'); + +DO $$ +DECLARE + user_id uuid; +BEGIN + user_id := public.create_user('supabot+supaadmin@example.com'); + + insert into public.channels (slug, created_by) + values + ('public', user_id), + ('random', user_id); + + insert into public.messages (message, channel_id, user_id) + values + ('Hello World 👋', 1, user_id), + ('Perfection is attained, not when there is nothing more to add, but when there is nothing left to take away.', 2, user_id); +END $$; + diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..7207a4c --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,130 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { authConfig } from "../auth-config.js"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadSecretFromEnv } from "./secrets.js"; +import { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +import type { 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); + } + + // The Auth settings the schema needs, switched on only now that every + // migration — and so every object they name — is in the database + // (src/auth-config.ts). A plan reports them and changes nothing. + const auth = adapter + ? { configured: await adapter.configureAuth(authConfig) } + : { pending: Object.keys(authConfig) }; + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + auth, + }; + + 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..30b7b25 --- /dev/null +++ b/packages/db/src/runner/supabase-api-adapter.ts @@ -0,0 +1,120 @@ +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`, + ); + } + + /** + * PATCH the project's Auth config with exactly these keys (the Management + * API merges them into the rest), then read it back and refuse a project + * that did not keep them. Idempotent: the same body on every apply. + */ + async configureAuth(config: Record): Promise { + const url = `${SUPABASE_API_BASE}/v1/projects/${this.projectRef}/config/auth`; + const headers = { + Authorization: `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }; + const patched = await fetch(url, { method: "PATCH", headers, body: JSON.stringify(config) }); + if (!patched.ok) { + throw new Error(`PATCH config/auth answered HTTP ${patched.status}: ${await patched.text()}`); + } + const read = await fetch(url, { headers }); + if (!read.ok) { + throw new Error(`GET config/auth answered HTTP ${read.status}: ${await read.text()}`); + } + const now = (await read.json()) as Record; + const missed = Object.entries(config).filter(([k, v]) => now[k] !== v).map(([k]) => k); + if (missed.length > 0) { + throw new Error(`the project's Auth config did not keep ${missed.join(", ")}`); + } + return Object.keys(config); + } + + 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/pnpm-lock.yaml b/pnpm-lock.yaml index cdc7e66..687055d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -79,6 +79,45 @@ importers: specifier: ^4.151.0 version: 4.155.0(@types/node@22.20.5) + packages/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/db: + devDependencies: + '@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 + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@22.20.5)(jiti@1.21.7)(sass@1.107.0)(terser@5.36.0)(yaml@2.9.1) + tests/web: devDependencies: '@app/eslint-config': @@ -496,6 +535,9 @@ packages: '@dotenvx/tooling@1.0.6': resolution: {integrity: sha512-d1AhKqlprzjR7+/7YTYbf9lTjeIUxr2WN+gYL5jf9O25wymlVWzuwOujq9IWJOt33sGWcLjr1eswSOmqm4SRMg==} + '@electric-sql/pglite@0.5.8': + resolution: {integrity: sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==} + '@emnapi/core@1.10.0': resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} @@ -4480,6 +4522,8 @@ snapshots: '@dotenvx/tooling@1.0.6': {} + '@electric-sql/pglite@0.5.8': {} + '@emnapi/core@1.10.0': dependencies: '@emnapi/wasi-threads': 1.2.1 @@ -6114,7 +6158,7 @@ snapshots: eslint: 9.39.5(jiti@1.21.7) eslint-import-resolver-node: 0.3.10 eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)) - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@1.21.7)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)) eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.5(jiti@1.21.7)) eslint-plugin-react: 7.37.5(eslint@9.39.5(jiti@1.21.7)) eslint-plugin-react-hooks: 7.1.1(eslint@9.39.5(jiti@1.21.7)) @@ -6147,7 +6191,7 @@ snapshots: tinyglobby: 0.2.17 unrs-resolver: 1.12.2 optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@1.21.7)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)) transitivePeerDependencies: - supports-color @@ -6162,7 +6206,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@1.21.7)): + eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.72.1(eslint@9.39.5(jiti@1.21.7))(typescript@5.9.3))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)))(eslint@9.39.5(jiti@1.21.7)): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.2.0 diff --git a/specs/epics/supabase-slack-clone/README.md b/specs/epics/supabase-slack-clone/README.md index f738110..e174b6c 100644 --- a/specs/epics/supabase-slack-clone/README.md +++ b/specs/epics/supabase-slack-clone/README.md @@ -8,7 +8,7 @@ The upstream code stays the code: `lib/Store.js` (the client, the data hooks, th | Field | Value | |-------|-------| -| Status | In progress — SL0 shipped ([#1](https://github.com/sourceplane/supabase-slack-clone/pull/1)), SL1 in review | +| Status | In progress — SL0–SL1 shipped ([#1](https://github.com/sourceplane/supabase-slack-clone/pull/1), [#2](https://github.com/sourceplane/supabase-slack-clone/pull/2)), SL2 in review | | Cluster | **SL** (SL0–SL4) | | Owner(s) | `apps/web` (the app) · `tests/web` · `infra/terraform/supabase` (the project) · `packages/db` + `infra/db-migrate` (the schema) · `tests/db` | | Builds on | `supabase-starter` — the shape of the repository and of the baseline, the `supabase` Terraform root, the stand-in; `sveltekit-saas` — the db-migrate lane on a Supabase project | diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..f036b67 --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,31 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests + description: The migrations' tests (the manifest, upstream's three SQL files byte for byte, the Auth config the runner sets, and the schema they leave on a Supabase-shaped Postgres in process — the roles trigger, the access-token hook, row-level security by role and the Realtime publication) +spec: + type: turbo-package + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + 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/docs/architecture.md b/tests/db/docs/architecture.md new file mode 100644 index 0000000..71b4d37 --- /dev/null +++ b/tests/db/docs/architecture.md @@ -0,0 +1,9 @@ +# db-tests — architecture + +A test package at `tests/db`. Its lane runs the suite before it builds. + +## Suites (3) + +- `auth-config.test.ts` +- `migrations.test.ts` +- `schema.test.ts` diff --git a/tests/db/docs/overview.md b/tests/db/docs/overview.md new file mode 100644 index 0000000..4a5a85f --- /dev/null +++ b/tests/db/docs/overview.md @@ -0,0 +1,20 @@ +# db-tests + +The migrations' tests (the manifest, upstream's three SQL files byte for byte, the Auth config the runner sets, and the schema they leave on a Supabase-shaped Postgres in process — the roles trigger, the access-token hook, row-level security by role and the Realtime publication) + +The test suite for **db**. It deploys nothing: its lane installs, builds and runs the tests. + +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/db` | +| Package | `@app/db-tests` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/db/docs/runbook.md b/tests/db/docs/runbook.md new file mode 100644 index 0000000..aa64499 --- /dev/null +++ b/tests/db/docs/runbook.md @@ -0,0 +1,26 @@ +# db-tests — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/db-tests build +pnpm --filter @app/db-tests test +pnpm --filter @app/db-tests typecheck +pnpm --filter @app/db-tests lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. 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..ad6e1e3 --- /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/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@electric-sql/pglite": "0.5.8", + "@saas/db": "workspace:*", + "@types/node": "^22.9.0", + "typescript": "^5.8.3", + "vitest": "^3.2.4" + } +} diff --git a/tests/db/src/auth-config.test.ts b/tests/db/src/auth-config.test.ts new file mode 100644 index 0000000..ec197df --- /dev/null +++ b/tests/db/src/auth-config.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { authConfig } from "@saas/db"; +import { SupabaseApiAdapter } from "@saas/db/runner"; + +// The Auth setting this schema needs and upstream sets in config.toml: the +// custom access-token hook, pointed at the function 020_auth_hook creates. +// The runner switches it on through the Management API after the migrations +// (src/runner/cli.ts), and refuses a project that did not keep it. +afterEach(() => vi.unstubAllGlobals()); + +describe("the Auth config the runner applies (packages/db/src/auth-config.ts)", () => { + it("is upstream's hook, by the URI Auth resolves to the migrated function", () => { + expect(authConfig).toEqual({ + hook_custom_access_token_enabled: true, + hook_custom_access_token_uri: "pg-functions://postgres/public/custom_access_token_hook", + }); + }); + + it("names a function a migration creates", async () => { + const { readFileSync } = await import("node:fs"); + const path = await import("node:path"); + const sql = readFileSync(path.resolve(__dirname, "../../../packages/db/src/migrations/020_auth_hook/up.sql"), "utf8"); + expect(sql).toMatch(/create or replace function public\.custom_access_token_hook\(event jsonb\)/); + expect(sql).toMatch(/grant execute\s+on function public\.custom_access_token_hook\s+to supabase_auth_admin/); + }); + + it("PATCHes exactly those keys to the project's Auth config, then checks the project kept them", async () => { + const seen: Array<{ method: string; url: string; body?: unknown; auth: string | null }> = []; + let stored: Record = { site_url: "https://x.example" }; + vi.stubGlobal("fetch", vi.fn(async (url: string, init: RequestInit = {}) => { + const method = init.method ?? "GET"; + const body = init.body ? JSON.parse(String(init.body)) : undefined; + seen.push({ method, url, body, auth: new Headers(init.headers).get("authorization") }); + if (method === "PATCH") stored = { ...stored, ...body }; + return Response.json(stored); + })); + const keys = await new SupabaseApiAdapter("abcdefghijklmnopqrst", "sbp_token").configureAuth(authConfig); + expect(keys).toEqual(Object.keys(authConfig)); + expect(seen).toEqual([ + { method: "PATCH", url: "https://api.supabase.com/v1/projects/abcdefghijklmnopqrst/config/auth", body: authConfig, auth: "Bearer sbp_token" }, + { method: "GET", url: "https://api.supabase.com/v1/projects/abcdefghijklmnopqrst/config/auth", body: undefined, auth: "Bearer sbp_token" }, + ]); + }); + + it("refuses a project whose Auth config did not keep the hook", async () => { + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit = {}) => + (init.method === "PATCH" ? Response.json({}) : Response.json({ hook_custom_access_token_enabled: false })))); + await expect(new SupabaseApiAdapter("ref", "t").configureAuth(authConfig)).rejects.toThrow( + /did not keep hook_custom_access_token_enabled, hook_custom_access_token_uri/, + ); + }); + + it("names the status when the Management API refuses the PATCH", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("forbidden", { status: 403 }))); + await expect(new SupabaseApiAdapter("ref", "t").configureAuth(authConfig)).rejects.toThrow(/PATCH config\/auth answered HTTP 403: forbidden/); + }); +}); diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..488ef75 --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { PGlite } from "@electric-sql/pglite"; +import { manifest } from "@saas/db/manifest"; +import { runMigrations } from "@saas/db/runner"; +import type { MigrationAdapter } from "@saas/db/runner"; +import { SUPABASE_PRELUDE } from "./supabase"; + +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +// supabase/supabase's examples/slack-clone/nextjs-slack-clone/supabase at +// 9eaae4c, by sha256: the app migrations are upstream's files byte for byte — +// its two migrations, then its seed. +const UPSTREAM = { + "010_init": "aa334acde2ceed2169b499969bdf7cba6eb2ee3fb70d8f9a3441d8c6ed625fd9", // migrations/20240214102356_init.sql + "020_auth_hook": "4da1507129a1d0f73658577f9852b9969b501cf8f1dc65133ca89788fd4bfff6", // migrations/20240214114147_auth-hook.sql + "030_seed": "4786f8af13181723968fde859a617e9cd0fcd9f94e937d45e96327e02b99a46d", // seed.sql +}; + +// The runner's adapter over an in-process Postgres (PGlite): the same calls +// the Management API adapter makes, one statement batch per call. +function pgliteAdapter(db: PGlite): MigrationAdapter { + return { + async connect() {}, + async disconnect() {}, + async acquireAdvisoryLock() { return true; }, + async releaseAdvisoryLock() {}, + async getAppliedMigrations() { + try { + const { rows } = await db.query<{ id: string; context: string; checksum: string; applied_at: string }>( + "select id, context, checksum, applied_at::text as applied_at from _migrations.applied order by id", + ); + return rows; + } catch (e) { + if (String(e).includes("does not exist")) return []; + throw e; + } + }, + async beginTransaction() {}, + async commitTransaction() {}, + async rollbackTransaction() {}, + async executeSql(sql) { await db.exec(sql); }, + async recordMigration(entry) { + await db.query( + "insert into _migrations.applied (id, context, checksum) values ($1, $2, $3) on conflict (id) do nothing", + [entry.id, entry.context, entry.checksum], + ); + }, + }; +} + +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("applies upstream's two migrations and its seed, byte for byte, in upstream's order", () => { + const app = manifest.migrations.filter((m) => m.context === "app"); + expect(app.map((m) => m.id)).toEqual(Object.keys(UPSTREAM)); + for (const entry of app) expect(entry.checksum, entry.id).toBe(UPSTREAM[entry.id as keyof typeof UPSTREAM]); + }); + + 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("applies every migration once to a Supabase-shaped Postgres, and a second apply applies nothing", async () => { + const db = new PGlite(); + await db.exec(SUPABASE_PRELUDE); + const first = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter: pgliteAdapter(db) }); + expect(first.failed).toBeNull(); + expect(first.applied).toEqual(manifest.migrations.map((m) => m.id)); + const again = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter: pgliteAdapter(db) }); + expect(again.failed).toBeNull(); + expect(again.applied).toEqual([]); + expect(again.skipped).toEqual(manifest.migrations.map((m) => m.id)); + }, 60_000); +}); diff --git a/tests/db/src/schema.test.ts b/tests/db/src/schema.test.ts new file mode 100644 index 0000000..61c745e --- /dev/null +++ b/tests/db/src/schema.test.ts @@ -0,0 +1,178 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { PGlite } from "@electric-sql/pglite"; +import { manifest } from "@saas/db/manifest"; +import { SUPABASE_PRELUDE } from "./supabase"; + +// The schema the chat reads, as every migration db-migrate applies leaves it +// on a Supabase-shaped Postgres (PGlite, in process): five tables with +// row-level security, profiles and roles made by the trigger on auth.users, +// deletes decided by the `user_role` claim the access-token hook adds, the +// realtime publication over the three tables the browser listens to, and the +// seed's two channels. +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +async function migrated(): Promise { + const db = new PGlite(); + await db.exec(SUPABASE_PRELUDE); + for (const entry of manifest.migrations) { + await db.exec(readFileSync(path.join(migrationsDir, entry.path), "utf8")); + } + return db; +} + +type Claims = { sub?: string; role: string; user_role?: string | null }; + +async function as(db: PGlite, claims: Claims, fn: () => Promise): Promise { + await db.exec(`set role ${claims.role}`); + await db.query("select set_config('request.jwt.claims', $1, false)", [JSON.stringify(claims)]); + try { + return await fn(); + } finally { + await db.exec("reset role"); + await db.query("select set_config('request.jwt.claims', '', false)"); + } +} + +async function denied(p: Promise): Promise { + try { + await p; + return "allowed"; + } catch (e) { + return String(e); + } +} + +const ALICE = "00000000-0000-4000-8000-00000000a11c"; // a member +const ADMIN = "00000000-0000-4000-8000-0000000ad111"; // signed up with +supaadmin@ +const MOD = "00000000-0000-4000-8000-00000000600d"; // signed up with +supamod@ + +describe("the chat's schema after every migration", () => { + let db: PGlite; + beforeAll(async () => { + db = await migrated(); + await db.query( + "insert into auth.users (id, email) values ($1, 'alice@example.invalid'), ($2, 'ann+supaadmin@example.invalid'), ($3, 'mo+supamod@example.invalid')", + [ALICE, ADMIN, MOD], + ); + }, 60_000); + + it("has upstream's five tables, each with row-level security", async () => { + const { rows } = await db.query<{ relname: string; relrowsecurity: boolean }>( + "select relname, relrowsecurity from pg_class where relnamespace = 'public'::regnamespace and relkind = 'r' order by relname", + ); + expect(rows).toEqual( + ["channels", "messages", "role_permissions", "user_roles", "users"].map((relname) => ({ relname, relrowsecurity: true })), + ); + }); + + it("gives every new auth user a profile, and a role by plus-address", async () => { + const users = await db.query<{ id: string; username: string; status: string }>( + "select id, username, status from public.users where id = any($1) order by username", + [[ALICE, ADMIN, MOD]], + ); + expect(users.rows.map((u) => u.username)).toEqual([ + "alice@example.invalid", + "ann+supaadmin@example.invalid", + "mo+supamod@example.invalid", + ]); + expect(new Set(users.rows.map((u) => u.status))).toEqual(new Set(["OFFLINE"])); + const roles = await db.query<{ user_id: string; role: string }>( + "select user_id, role::text from public.user_roles order by role", + ); + expect(roles.rows).toEqual( + expect.arrayContaining([ + { user_id: ADMIN, role: "admin" }, + { user_id: MOD, role: "moderator" }, + ]), + ); + expect(roles.rows.find((r) => r.user_id === ALICE)).toBeUndefined(); + }); + + it("seeds the #public and #random channels with a message each, and the role permissions", async () => { + const channels = await db.query<{ id: number; slug: string }>("select id, slug from public.channels order by id"); + expect(channels.rows).toEqual([ + { id: 1, slug: "public" }, + { id: 2, slug: "random" }, + ]); + const messages = await db.query<{ n: number }>("select count(*)::int as n from public.messages"); + expect(messages.rows[0]?.n).toBe(2); + const perms = await db.query<{ role: string; permission: string }>( + "select role::text, permission::text from public.role_permissions order by role, permission", + ); + expect(perms.rows).toEqual([ + { role: "admin", permission: "channels.delete" }, + { role: "admin", permission: "messages.delete" }, + { role: "moderator", permission: "messages.delete" }, + ]); + }); + + it("adds the user's role to an access token through the hook, as Auth runs it", async () => { + const event = (uid: string) => JSON.stringify({ user_id: uid, claims: { sub: uid, role: "authenticated" } }); + await db.exec("set role supabase_auth_admin"); + try { + const run = async (uid: string) => + (await db.query<{ e: { claims: { user_role: string | null } } }>( + "select public.custom_access_token_hook($1::jsonb) as e", + [event(uid)], + )).rows[0]?.e.claims.user_role; + expect(await run(ADMIN)).toBe("admin"); + expect(await run(MOD)).toBe("moderator"); + expect(await run(ALICE)).toBeNull(); + } finally { + await db.exec("reset role"); + } + }); + + it("lets nobody but Auth run the hook or read the roles table", async () => { + for (const role of ["anon", "authenticated"]) { + expect(await as(db, { role, sub: ALICE }, () => denied(db.query("select public.custom_access_token_hook('{}'::jsonb)")))).toMatch(/permission denied/); + expect(await as(db, { role, sub: ADMIN }, () => denied(db.query("select * from public.user_roles")))).toMatch(/permission denied/); + } + }); + + it("shows the anon key nothing", async () => { + for (const table of ["users", "channels", "messages", "role_permissions"]) { + const { rows } = await as(db, { role: "anon" }, () => db.query(`select * from public.${table}`)); + expect(rows, table).toEqual([]); + } + }); + + it("lets a signed-in member read everything, post as themselves only, and delete only their own message", async () => { + const alice: Claims = { role: "authenticated", sub: ALICE, user_role: null }; + const seen = await as(db, alice, () => db.query<{ n: number }>("select count(*)::int as n from public.messages")); + expect(seen.rows[0]?.n).toBeGreaterThanOrEqual(2); + const mine = await as(db, alice, () => + db.query<{ id: number }>("insert into public.messages (message, user_id, channel_id) values ('hi', $1, 1) returning id", [ALICE]), + ); + expect(await as(db, alice, () => denied(db.query("insert into public.messages (message, user_id, channel_id) values ('as admin', $1, 1)", [ADMIN])))).toMatch(/row-level security/); + // Someone else's message: the delete matches nothing under RLS. + const theirs = await db.query<{ id: number }>("select id from public.messages where user_id <> $1 order by id limit 1", [ALICE]); + const gone = await as(db, alice, () => db.query("delete from public.messages where id = $1", [theirs.rows[0]!.id])); + expect(gone.affectedRows).toBe(0); + const own = await as(db, alice, () => db.query("delete from public.messages where id = $1", [mine.rows[0]!.id])); + expect(own.affectedRows).toBe(1); + }); + + it("lets a moderator delete any message and an admin any channel, by the token's user_role", async () => { + const msg = await db.query<{ id: number }>("insert into public.messages (message, user_id, channel_id) values ('spam', $1, 2) returning id", [ALICE]); + const mod: Claims = { role: "authenticated", sub: MOD, user_role: "moderator" }; + expect((await as(db, mod, () => db.query("delete from public.messages where id = $1", [msg.rows[0]!.id]))).affectedRows).toBe(1); + const chan = await db.query<{ id: number }>("insert into public.channels (slug, created_by) values ('alices', $1) returning id", [ALICE]); + expect((await as(db, mod, () => db.query("delete from public.channels where id = $1", [chan.rows[0]!.id]))).affectedRows).toBe(0); + const admin: Claims = { role: "authenticated", sub: ADMIN, user_role: "admin" }; + expect((await as(db, admin, () => db.query("delete from public.channels where id = $1", [chan.rows[0]!.id]))).affectedRows).toBe(1); + }); + + it("publishes channels, messages and users to Realtime, with their previous rows", async () => { + const pub = await db.query<{ tablename: string }>( + "select tablename from pg_publication_tables where pubname = 'supabase_realtime' order by tablename", + ); + expect(pub.rows.map((r) => r.tablename)).toEqual(["channels", "messages", "users"]); + const ident = await db.query<{ relname: string; relreplident: string }>( + "select relname, relreplident from pg_class where relname in ('channels', 'messages', 'users') and relnamespace = 'public'::regnamespace order by relname", + ); + expect(ident.rows.every((r) => r.relreplident === "f")).toBe(true); + }); +}); diff --git a/tests/db/src/supabase.ts b/tests/db/src/supabase.ts new file mode 100644 index 0000000..61dadbf --- /dev/null +++ b/tests/db/src/supabase.ts @@ -0,0 +1,56 @@ +// What a Supabase project has before any migration runs, as far as this +// schema touches it: the API roles and Auth's own role, `auth.users` with +// `auth.uid()`, `auth.role()` and `auth.jwt()`, the `extensions` schema's +// uuid_generate_v4(), and the empty `supabase_realtime` publication Supabase +// creates for every project. Supabase creates these itself; a test database +// needs them for upstream's migrations to mean here what they mean there (a +// trigger on auth.users, policies keyed on the request's JWT, a hook function +// only Auth may run, a publication the migration re-creates). +// +// auth.uid(), auth.role() and auth.jwt() read the request's JWT the way +// Supabase's own do: PostgREST sets `request.jwt.claims` for every request. +export const SUPABASE_PRELUDE = ` +create role anon nologin; +create role authenticated nologin; +create role service_role nologin bypassrls; +create role supabase_auth_admin nologin; + +create schema auth; +create table auth.users ( + id uuid primary key default gen_random_uuid(), + email text, + encrypted_password text, + raw_user_meta_data jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now() +); +create function auth.uid() returns uuid language sql stable as $$ + select nullif( + coalesce( + current_setting('request.jwt.claim.sub', true), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub') + ), + '' + )::uuid +$$; +create function auth.role() returns text language sql stable as $$ + select coalesce( + nullif(current_setting('request.jwt.claim.role', true), ''), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role') + )::text +$$; +create function auth.jwt() returns jsonb language sql stable as $$ + select coalesce(nullif(current_setting('request.jwt.claims', true), ''), '{}')::jsonb +$$; + +create schema extensions; +create function extensions.uuid_generate_v4() returns uuid language sql volatile as $$ + select gen_random_uuid() +$$; + +create publication supabase_realtime; + +grant usage on schema public, auth to anon, authenticated, service_role; +grant usage on schema auth to supabase_auth_admin; +grant execute on all functions in schema auth to anon, authenticated, supabase_auth_admin; +alter default privileges in schema public grant all on tables to anon, authenticated, service_role; +`; 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", + }, +}); diff --git a/tooling/migrations/manifest.mjs b/tooling/migrations/manifest.mjs new file mode 100644 index 0000000..ea8d7a5 --- /dev/null +++ b/tooling/migrations/manifest.mjs @@ -0,0 +1,42 @@ +#!/usr/bin/env node +// Keeps packages/db/src/manifest.ts honest: every entry's `checksum` is the +// sha256 of its migration file. +// +// node manifest.mjs check # exit 1 and list every mismatch +// node manifest.mjs fix # rewrite the checksums in manifest.ts +// +// Run from packages/db (the package scripts do). An applied migration's +// checksum is immutable — `fix` is for a migration that has not been applied +// anywhere yet. +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const mode = process.argv[2]; +if (mode !== "check" && mode !== "fix") { + console.error("usage: manifest.mjs "); + process.exit(2); +} +const manifestPath = resolve("src/manifest.ts"); +const migrationsDir = resolve("src/migrations"); +let source = readFileSync(manifestPath, "utf8"); + +const entryRe = /path:\s*"([^"]+)",\s*checksum:\s*"([0-9a-f]{64})"/g; +const mismatches = []; +source = source.replace(entryRe, (whole, path, recorded) => { + const actual = createHash("sha256").update(readFileSync(resolve(migrationsDir, path))).digest("hex"); + if (actual !== recorded) mismatches.push({ path, recorded, actual }); + return mode === "fix" ? whole.replace(recorded, actual) : whole; +}); + +if (mismatches.length === 0) { + console.log("manifest: every checksum matches its file"); + process.exit(0); +} +if (mode === "fix") { + writeFileSync(manifestPath, source); + for (const m of mismatches) console.log(`manifest: ${m.path} ${m.recorded.slice(0, 8)} → ${m.actual.slice(0, 8)}`); + process.exit(0); +} +for (const m of mismatches) console.error(`manifest: ${m.path} recorded ${m.recorded} but the file hashes to ${m.actual}`); +process.exit(1);