From 5ec6c20e6bc5a33df7ad2fbcc72e468f7fb36608 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Mu=C3=B1oz?= Date: Wed, 4 Nov 2026 23:56:49 -0300 Subject: [PATCH] feat(db): wallet RLS migration, vyloop_app runbook and wallet phase with push_campaigns (RLS unit 6) --- docs/09-Database-Design.md | 36 +++++++++- odd/tasks/tenant-isolation-rls.md | 3 +- .../changes/tenant-isolation-rls/tasks.md | 4 +- packages/db/drizzle/0026_wallet_rls.sql | 48 +++++++++++++ .../meta/_applied-outside-drizzle.json | 39 +++++++++++ packages/db/drizzle/meta/_journal.json | 9 ++- packages/db/src/migration-sql.test.ts | 67 ++++++++++++++++--- scripts/check-migration-drift.test.mjs | 40 ++++++----- scripts/check-rls.mjs | 24 +++++-- scripts/check-rls.test.mjs | 59 +++++++++++++--- 10 files changed, 281 insertions(+), 48 deletions(-) create mode 100644 packages/db/drizzle/0026_wallet_rls.sql diff --git a/docs/09-Database-Design.md b/docs/09-Database-Design.md index e9552967..5bab571c 100644 --- a/docs/09-Database-Design.md +++ b/docs/09-Database-Design.md @@ -344,7 +344,7 @@ CREATE TABLE localization_configs ( ## 4. Row-Level Security (RLS) — implementación -**Estado actual: RLS no está desplegado.** La estrategia de la sección 1 (multi-tenancy por `business_id` con RLS) sigue siendo la decisión de diseño, pero el rollout está staged, no completo. Los tres hechos que hay que conocer: +**Estado actual: RLS desplegado en la fase `wallet`.** Desde la migración `0026_wallet_rls.sql`, las tres `TENANT_ID_TABLES` y `push_campaigns` tienen RLS y la política `tenant_isolation`, y los workers se conectan con el rol `vyloop_app`, que no tiene `BYPASSRLS` ni es dueño de ninguna tabla. Las demás tablas de negocio siguen sin RLS: el rollout es por fases (Unidad 7 de `tenant-isolation-rls`). La estrategia de la sección 1 (multi-tenancy por `business_id` con RLS) sigue siendo la decisión de diseño. Los tres hechos que hay que conocer: 1. Los workers y el gateway fijan el tenant con `withTenantTransaction(db, { businessId?, tenantId? }, fn)` de `@vyloop/db`: abre una transacción, ejecuta `set_config(..., true)` sobre ella y corre las consultas de `fn` en ese mismo handle. Es la única forma válida, porque `set_config(..., true)` dura lo que dura su transacción; el `withRls` anterior lo ejecutaba como sentencia suelta y el valor desaparecía antes de la consulta siguiente. Un contract test (`packages/db/src/rls-call-sites.contract.test.ts`) impide volver a fijarlo a mano; las excepciones son el alta de negocio, que crea el id dentro de su propia transacción, y los crons que recorren todos los negocios (Unidad 3). Aun así, **hoy nada aísla por RLS**: sin políticas creadas y sin `ALTER TABLE ... ENABLE ROW LEVEL SECURITY`, la sesión ve todas las filas. El aislamiento real de hoy descansa en los filtros explícitos de `business_id` en los handlers de ruta. 2. El mecanismo existe y está probado: `packages/db/src/rls.ts` expone `BUSINESS_ID_TABLES` (17 tablas con `business_id`), `TENANT_ID_TABLES`, `RLS_POLICY_NAME` (`tenant_isolation`) y `createRlsPolicies()`. `createRlsPolicies()` **no se llama en código de producción**; está disponible para el rollout. @@ -372,9 +372,39 @@ CREATE POLICY tenant_isolation ON customer_wallet_passes `workers/wallet` ya usa el mecanismo con scope de tenant: `openTenantSession` en `drizzle-store.ts` ejecuta `setCurrentBusinessId(tenantId)` y `setCurrentTenantId(tenantId)` antes de leer nada, usando los builders que exporta `@vyloop/db`. Poner las dos variables desde el inicio es deliberado: una variable faltante es invisible hasta que la política correspondiente se habilite, que es el peor momento para descubrirlo. -**Verificación: `pnpm db:rls`.** `scripts/check-rls.mjs` abre una sesión de solo lectura (`SET default_transaction_read_only = on`, confirmada con `SHOW`; si el servidor no la respeta, corta la conexión) y reporta, para cada tabla de `BUSINESS_ID_TABLES` y `TENANT_ID_TABLES` —leídas de `rls.ts`, no copiadas—, `relrowsecurity`, `relforcerowsecurity` y si existe la política `tenant_isolation`; además el rol conectado, su `rolbypassrls` y qué tablas listadas posee. Sin argumentos es un reporte. `pnpm db:rls -- --expect ` lo convierte en criterio de salida: `none`, `wallet` (las `TENANT_ID_TABLES`), `communication`, `growth`, `rest` (los lotes de negocio, acumulativos en ese orden) o `all`. Las tablas de la fase deben tener RLS y la política; el resto, ni lo uno ni lo otro; cualquier diferencia sale con código 1 y nombra la tabla. Una base inalcanzable o una sesión que no queda en solo lectura también sale con 1: no hay tercer estado. El rol se reporta pero no se juzga, porque el script corre con la credencial de dueño. +**Verificación: `pnpm db:rls`.** `scripts/check-rls.mjs` abre una sesión de solo lectura (`SET default_transaction_read_only = on`, confirmada con `SHOW`; si el servidor no la respeta, corta la conexión) y reporta, para cada tabla de `BUSINESS_ID_TABLES` y `TENANT_ID_TABLES` —leídas de `rls.ts`, no copiadas—, `relrowsecurity`, `relforcerowsecurity` y si existe la política `tenant_isolation`; además el rol conectado, su `rolbypassrls` y qué tablas listadas posee. Sin argumentos es un reporte. `pnpm db:rls -- --expect ` lo convierte en criterio de salida: `none`, `wallet` (las `TENANT_ID_TABLES` y `push_campaigns`), `communication`, `growth`, `rest` (los lotes de negocio, acumulativos en ese orden) o `all`. Las tablas de la fase deben tener RLS y la política; el resto, ni lo uno ni lo otro; cualquier diferencia sale con código 1 y nombra la tabla. Una base inalcanzable o una sesión que no queda en solo lectura también sale con 1: no hay tercer estado. El rol se reporta pero no se juzga, porque el script corre con la credencial de dueño. -**Credencial del gateway — decisión pendiente para la Unidad 6.** `apps/gateway` lee `loyalty_programs` para la página pública `/p/{slug}` con el mismo `DATABASE_URL` que los workers, y ya fija el tenant con `withTenantTransaction`. Cuando los workers pasen al rol `vyloop_app` (sin `BYPASSRLS`), el gateway tiene dos caminos: moverse con ellos, para lo que no le falta nada, o conservar una credencial propia de dueño. Se decide antes de habilitar políticas en `loyalty_programs`. +**Credenciales: un rol para los workers y el dueño fuera del runtime.** Decisión de la Unidad 6: + +- El secret `DATABASE_URL` de GitHub, que `deploy.yml` pasa a los seis workers, al gateway y al job `migration-drift`, es la credencial de `vyloop_app`. El gateway se mueve con los workers: ya fija el tenant con `withTenantTransaction` para `/p/{slug}`, así que no necesita una credencial de dueño. +- `migration-drift` no necesita ser dueño. Lee catálogos (`pg_class`, `pg_policies`, `information_schema`) y `drizzle.__drizzle_migrations`; para lo último, `vyloop_app` tiene `USAGE` sobre el esquema `drizzle` y `SELECT` sobre sus tablas. Ningún job de CI tiene credencial con DDL. +- La credencial de dueño (`neondb_owner`) queda solo para las migraciones aplicadas a mano y los scripts operativos (`db:anonymise-deleted`, `seed-demo`), que se corren desde una máquina con el `.dev.vars` local. +- `FORCE ROW LEVEL SECURITY` no se activa: el dueño sigue leyendo todo, que es lo que necesitan las migraciones y los scripts. + +**Runbook del rol `vyloop_app`.** Se ejecuta con la credencial de dueño. Se ensaya primero en una rama de Neon creada desde `production`: ahí se aplica la migración RLS de la fase, se corre el sweep del wallet con un cliente de Google falso y se confirma con `pnpm db:rls -- --expect ` y `pnpm db:drift` conectados como `vyloop_app`. Después se repite en `production`. + +```sql +-- La contraseña se genera localmente (openssl rand -hex 24) y nunca se pega en un chat ni en un archivo versionado. +CREATE ROLE vyloop_app LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS PASSWORD ''; +GRANT CONNECT ON DATABASE neondb TO vyloop_app; +GRANT USAGE ON SCHEMA public TO vyloop_app; +GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO vyloop_app; +GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA public TO vyloop_app; +-- Las tablas que creen migraciones futuras (siempre como neondb_owner) heredan los permisos. +ALTER DEFAULT PRIVILEGES FOR ROLE neondb_owner IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO vyloop_app; +ALTER DEFAULT PRIVILEGES FOR ROLE neondb_owner IN SCHEMA public GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO vyloop_app; +-- Solo lectura sobre el registro de migraciones, para el gate de drift. +GRANT USAGE ON SCHEMA drizzle TO vyloop_app; +GRANT SELECT ON ALL TABLES IN SCHEMA drizzle TO vyloop_app; +``` + +El rol se crea por SQL y no desde la consola de Neon a propósito: los roles que crea la consola son miembros de `neon_superuser`, y el de los workers no debe heredar nada. + +Orden en producción, de menos a más riesgoso, cada paso reversible por separado: + +1. Crear `vyloop_app` y sus permisos. No cambia nada para nadie. +2. Cambiar el secret `DATABASE_URL` a `vyloop_app` y redesplegar. A partir de aquí la política de `push_campaigns`, que ya existía, se aplica de verdad. Rollback: volver a poner la credencial de dueño en el secret y redesplegar. +3. Aplicar `0026_wallet_rls.sql` (con el `DROP POLICY` previo de `push_campaigns`, en la misma transacción) y mergear. Rollback: las sentencias del encabezado de la migración. --- diff --git a/odd/tasks/tenant-isolation-rls.md b/odd/tasks/tenant-isolation-rls.md index 1424546d..a2bb68d0 100644 --- a/odd/tasks/tenant-isolation-rls.md +++ b/odd/tasks/tenant-isolation-rls.md @@ -21,7 +21,7 @@ Branch: one per unit (`feat/rls-unit-…`). Delivery: one PR per unit, stacke | T4 | S4 | delegated (parallel writer) | done: RED (module missing), scripts 313 green; RDD review approved; `db:rls --expect none` run read-only on production | PR #344 | | T5 | S5 | delegated (parallel writer) | done: RED 7 failing, scripts 282 green; gate PASS read-only on production | PR #343 | | T6a | S6 | delegated (writer, isolated worktree) | done: RED per rule, wallet 966 green; independent verifier (items 2, 3, 4): no blockers; RDD review approved | PR #346 | -| T6 | S6 | inline (remote steps need authorization) | pending | | +| T6 | S6 | inline | in progress: rehearsal on Neon branch `rls-unit6-rehearsal` clean (0 RLS errors); repo changes (0026, check-rls wallet batch, docs/09 runbook) on `feat/rls-unit6-wallet`; production steps pending (role, secret, 0026) | | | T7 | S7 | inline (remote steps need authorization) | pending | | ## Log @@ -34,3 +34,4 @@ Branch: one per unit (`feat/rls-unit-…`). Delivery: one PR per unit, stacke - L6 (2026-11-04) User: "Activar RLS en producción, el pr ya está mergeado, lo de rls lo puedes hacer tu,ya tienes los permisos". Read-only production probe: workers connect as `neondb_owner` (`rolbypassrls = true`, owns all 31 public tables), so policies are inert until Unit 6. Only `push_campaigns` already has RLS and `tenant_isolation`. Units 3, 4 and 5 ran as three parallel writers in isolated worktrees (disjoint surfaces, several hundred lines each). Units 4 and 5 both touched `observeDatabase`; #344 is rebased on #343. - L7 Unit 3 verifier: no blockers. A1 `listPassesPendingExpiry` (sweep) and `findTenantByClassId` (callback path) still read tenant tables across tenants, tracked as T6a. A2 wallet enumerations open one transaction per tenant, so a transient error fails the whole listing (pre-existing all-or-nothing). A3 the communication sweep cap now applies per tenant. A4 stale contract-test comment, fixed. - L8 (2026-11-04) T6a: `findTenantByClassId` parses the candidate tenant from the class id (`tenantIdFromClassId`, strict inverse of `classIdFor`) and confirms it with an exact `class_id` match inside that tenant's transaction; all 6 production class ids are canonical (read-only check). The sweep's expiry window plans one global budget over per-tenant counts (`planExpiryWindow`); order inside a page is now tenant, then deletion time. Verifier advisories: positions can shift if rows change between count and slice; one count transaction per tenant per run. +- L9 (2026-11-04) User: "sigamos con la unidad 6". Rehearsal on Neon branch `rls-unit6-rehearsal` (copy of production): `vyloop_app` created by SQL (NOBYPASSRLS, owns nothing, DML grants, default privileges, read on schema `drizzle`); wallet RLS applied. As `vyloop_app`: a bare read fails with "unrecognized configuration parameter"; inside a tenant transaction only that tenant's rows are visible; a cross-tenant update affects 0 rows and a cross-tenant insert is refused by the policy; all 6 callback class ids resolve; inactivity dry run 0 failures; full sweep with a fake Google client: 6 failures, all from the fake client, none from RLS. `db:rls --expect wallet`, `db:drift` and `--check-baseline` pass as `vyloop_app`. Findings: `push_campaigns` already had RLS and the policy in production, applied outside any migration, so switching the role enforces it; 0026 records it with the wallet tables and `check-rls` puts it in the `wallet` phase. The drift job does not need the owner: `vyloop_app` with read on `drizzle` is enough, so CI keeps one secret. Deviation from 6.3: no preview deploy; the rehearsal runs the real wallet store and sweep against the branch instead, because a preview with Google credentials would write to real passes. diff --git a/openspec/changes/tenant-isolation-rls/tasks.md b/openspec/changes/tenant-isolation-rls/tasks.md index 55b29600..a9d41757 100644 --- a/openspec/changes/tenant-isolation-rls/tasks.md +++ b/openspec/changes/tenant-isolation-rls/tasks.md @@ -72,9 +72,9 @@ Chain strategy: stacked-to-main ## Unit 6: Phases 1–3 — role, shadow, wallet tables -- [ ] 6.1 `docs/09-Database-Design.md` §4 — runbook: create `vyloop_app` (LOGIN, NOBYPASSRLS, owns nothing), `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public`, `GRANT USAGE ON ALL SEQUENCES`, `ALTER DEFAULT PRIVILEGES` for future tables; run on a Neon branch first; confirm with `pnpm db:rls`. +- [x] 6.1 `docs/09-Database-Design.md` §4 — runbook: create `vyloop_app` (LOGIN, NOBYPASSRLS, owns nothing), `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public`, `GRANT USAGE ON ALL SEQUENCES`, `ALTER DEFAULT PRIVILEGES` for future tables; run on a Neon branch first; confirm with `pnpm db:rls`. - [ ] 6.2 Phase 1: move the workers' `DATABASE_URL` GitHub secret (consumed by `.github/workflows/deploy.yml`) to the `vyloop_app` credential; keep the owner credential in a separate secret for the `migration-drift` job and the scripts. Record the decision in `docs/09` §4. -- [ ] 6.3 Phase 2: on a Neon branch of `ep-shiny-paper-aibbf0hk`, apply `enableRls()`, `createRlsPolicies()`, `enableTenantRls()` and `createTenantRlsPolicies()`; point a preview deploy at it; run the smoke flows and the wallet sweep; record the error count from the branch logs. +- [x] 6.3 Phase 2 (rehearsed against the real wallet store and sweep instead of a preview deploy; see `odd/tasks/tenant-isolation-rls.md` L9): on a Neon branch of `ep-shiny-paper-aibbf0hk`, apply `enableRls()`, `createRlsPolicies()`, `enableTenantRls()` and `createTenantRlsPolicies()`; point a preview deploy at it; run the smoke flows and the wallet sweep; record the error count from the branch logs. - [ ] 6.4 Phase 3: `packages/db/drizzle/_wallet_rls.sql` (next free number, reserved per `docs/18-Trabajo-Pendiente.md`) — `ENABLE ROW LEVEL SECURITY` and `CREATE POLICY tenant_isolation` for the three `TENANT_ID_TABLES`; apply by hand; register in `packages/db/drizzle/meta/_applied-outside-drizzle.json` with `rls`/`policy` evidence; `pnpm db:drift` and `pnpm db:rls -- --expect wallet` green. ## Unit 7: Phase 4 — business tables and docs diff --git a/packages/db/drizzle/0026_wallet_rls.sql b/packages/db/drizzle/0026_wallet_rls.sql new file mode 100644 index 00000000..ade54440 --- /dev/null +++ b/packages/db/drizzle/0026_wallet_rls.sql @@ -0,0 +1,48 @@ +-- Enable row-level security on the wallet tables (openspec tenant-isolation-rls 6.4). +-- +-- ## What this does +-- +-- The three `TENANT_ID_TABLES` of `packages/db/src/rls.ts` get RLS and the +-- `tenant_isolation` policy that `enableTenantRls()` and +-- `createTenantRlsPolicies()` generate: a row is visible, and may be written, +-- only when its `tenant_id` equals `app.current_tenant_id`, which +-- `withTenantTransaction` sets on the transaction. +-- +-- `push_campaigns` is recorded here too. Production had RLS and this exact +-- policy on it before the rollout started, applied outside any migration, so no +-- migration produced that state and a database built from the migrations lacked +-- it. Its statements are the ones `enableRls()` and `createRlsPolicies()` +-- generate for a `BUSINESS_ID_TABLES` table. +-- +-- ## Who it binds +-- +-- Only roles without BYPASSRLS that do not own the tables: the workers' +-- `vyloop_app` role. The owner credential (migrations, operational scripts) +-- keeps reading everything, because FORCE ROW LEVEL SECURITY is not set. +-- +-- `current_setting(...)` is called without its `missing_ok` argument on +-- purpose: a query on these tables outside `withTenantTransaction` fails with +-- "unrecognized configuration parameter" instead of returning no rows. +-- +-- ## Applying it to production +-- +-- The `push_campaigns` policy already exists there, so drop it in the same +-- transaction that runs this file. The table is never without its policy: +-- +-- BEGIN; +-- DROP POLICY tenant_isolation ON "push_campaigns"; +-- -- the statements below +-- COMMIT; +-- +-- ## Rollback +-- +-- DROP POLICY tenant_isolation ON ""; +-- ALTER TABLE "
" DISABLE ROW LEVEL SECURITY; +ALTER TABLE "tenant_wallet_programs" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +ALTER TABLE "customer_wallet_passes" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +ALTER TABLE "wallet_callback_deliveries" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +ALTER TABLE "push_campaigns" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +CREATE POLICY tenant_isolation ON "tenant_wallet_programs" USING (tenant_id = current_setting('app.current_tenant_id')::UUID); --> statement-breakpoint +CREATE POLICY tenant_isolation ON "customer_wallet_passes" USING (tenant_id = current_setting('app.current_tenant_id')::UUID); --> statement-breakpoint +CREATE POLICY tenant_isolation ON "wallet_callback_deliveries" USING (tenant_id = current_setting('app.current_tenant_id')::UUID); --> statement-breakpoint +CREATE POLICY tenant_isolation ON "push_campaigns" USING (business_id = current_setting('app.current_business_id')::UUID); diff --git a/packages/db/drizzle/meta/_applied-outside-drizzle.json b/packages/db/drizzle/meta/_applied-outside-drizzle.json index d39a35d6..f994168d 100644 --- a/packages/db/drizzle/meta/_applied-outside-drizzle.json +++ b/packages/db/drizzle/meta/_applied-outside-drizzle.json @@ -251,6 +251,45 @@ "name": "customers.card_token_version" } ] + }, + { + "tag": "0026_wallet_rls", + "when": 1793100000000, + "hash": "2ff1c15fd20e01e10e1ff6cc19ba52a2bab14e014afa42f0df61ecc903c92507", + "evidence": [ + { + "kind": "rls", + "name": "tenant_wallet_programs" + }, + { + "kind": "rls", + "name": "customer_wallet_passes" + }, + { + "kind": "rls", + "name": "wallet_callback_deliveries" + }, + { + "kind": "rls", + "name": "push_campaigns" + }, + { + "kind": "policy", + "name": "tenant_wallet_programs.tenant_isolation" + }, + { + "kind": "policy", + "name": "customer_wallet_passes.tenant_isolation" + }, + { + "kind": "policy", + "name": "wallet_callback_deliveries.tenant_isolation" + }, + { + "kind": "policy", + "name": "push_campaigns.tenant_isolation" + } + ] } ] } diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index d7def36d..27616245 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -183,6 +183,13 @@ "when": 1793000000000, "tag": "0025_card_credential", "breakpoints": true + }, + { + "idx": 26, + "version": "7", + "when": 1793100000000, + "tag": "0026_wallet_rls", + "breakpoints": true } ] -} \ No newline at end of file +} diff --git a/packages/db/src/migration-sql.test.ts b/packages/db/src/migration-sql.test.ts index 033a0f1e..74090b14 100644 --- a/packages/db/src/migration-sql.test.ts +++ b/packages/db/src/migration-sql.test.ts @@ -7,7 +7,13 @@ import PgQueryModule from 'pg-query-emscripten'; import { describe, expect, it } from 'vitest'; import { allIndexes, indexByName } from './indexes'; -import { BUSINESS_ID_TABLES } from './rls'; +import { + BUSINESS_ID_TABLES, + createRlsPolicies, + createTenantRlsPolicies, + enableRls, + enableTenantRls, +} from './rls'; import { customerCredentialRevocations, customers, @@ -325,14 +331,15 @@ describe(`${BACKLOG_MIGRATION} closes the schema backlog`, () => { /** * The migrations allowed to enable row-level security or create policies. * - * Empty on purpose: no migration enables RLS yet. Enabling it applies tenant - * isolation to a table in one shot, and every code path that reads that table - * must already set the session context inside a transaction, so each RLS - * migration is a separate, reviewed rollout (openspec change - * `tenant-isolation-rls`, Units 6 and 7). Add a file name here in the same - * change that adds the migration, never ahead of it. + * Enabling RLS applies tenant isolation to a table in one shot, and every code + * path that reads that table must already set the session context inside a + * transaction, so each RLS migration is a separate, reviewed rollout (openspec + * change `tenant-isolation-rls`, Units 6 and 7). Add a file name here in the + * same change that adds the migration, never ahead of it. */ -const RLS_MIGRATIONS: readonly string[] = []; +const RLS_MIGRATIONS: readonly string[] = ['0026_wallet_rls.sql']; + +const WALLET_RLS_MIGRATION = '0026_wallet_rls.sql'; describe('row-level security is confined to the explicit RLS migrations', () => { it('lists only migrations that exist', () => { @@ -341,6 +348,26 @@ describe('row-level security is confined to the explicit RLS migrations', () => } }); + it(`${WALLET_RLS_MIGRATION} runs exactly the statements rls.ts generates for the wallet tables and push_campaigns`, () => { + const dialect = new PgDialect(); + const render = (statements: ReturnType) => + statements.map((statement) => dialect.sqlToQuery(statement).sql.replace(/;$/, '')); + const pushCampaigns = (statements: string[]) => + statements.filter((statement) => statement.includes('"push_campaigns"')); + + const expected = [ + ...render(enableTenantRls()), + ...pushCampaigns(render(enableRls())), + ...render(createTenantRlsPolicies()), + ...pushCampaigns(render(createRlsPolicies())), + ]; + const actual = codeStatements(readMigration(WALLET_RLS_MIGRATION)).map((statement) => + statement.replace(/;$/, ''), + ); + + expect(actual).toEqual(expected); + }); + it.each(migrationFiles.filter((file) => !RLS_MIGRATIONS.includes(file)))( '%s neither enables row-level security nor creates a policy', (file) => { @@ -516,7 +543,15 @@ describe(`${CARD_CREDENTIAL_MIGRATION} adds the rotatable card credential`, () = it('creates the revocation audit table with who, when and why', () => { expect(sql).toMatch(/CREATE TABLE "customer_credential_revocations"/); - for (const column of ['business_id', 'customer_id', 'actor_user_id', 'reason', 'previous_version', 'new_version', 'created_at']) { + for (const column of [ + 'business_id', + 'customer_id', + 'actor_user_id', + 'reason', + 'previous_version', + 'new_version', + 'created_at', + ]) { expect(sql).toContain(`"${column}"`); } expect(sql).toMatch(/"reason" text NOT NULL/); @@ -525,10 +560,20 @@ describe(`${CARD_CREDENTIAL_MIGRATION} adds the rotatable card credential`, () = it('declares the same shape in the Drizzle schema', () => { const customerColumns = getTableConfig(customers).columns.map((c) => c.name); - expect(customerColumns).toEqual(expect.arrayContaining(['card_token_version', 'card_token_hash'])); + expect(customerColumns).toEqual( + expect.arrayContaining(['card_token_version', 'card_token_hash']), + ); const auditColumns = getTableConfig(customerCredentialRevocations).columns.map((c) => c.name); expect(auditColumns).toEqual( - expect.arrayContaining(['business_id', 'customer_id', 'actor_user_id', 'reason', 'previous_version', 'new_version', 'created_at']), + expect.arrayContaining([ + 'business_id', + 'customer_id', + 'actor_user_id', + 'reason', + 'previous_version', + 'new_version', + 'created_at', + ]), ); }); diff --git a/scripts/check-migration-drift.test.mjs b/scripts/check-migration-drift.test.mjs index f4f8b0ca..1ba7f2c6 100644 --- a/scripts/check-migration-drift.test.mjs +++ b/scripts/check-migration-drift.test.mjs @@ -93,11 +93,11 @@ const BASELINE_COVERING_0002 = { * them. */ const FACTS_WITH_0002 = { - tables: new Set(['alpha']), - columns: new Set(['alpha.label']), - indexes: new Set(['idx_alpha_label']), - constraints: new Set(), - }; + tables: new Set(['alpha']), + columns: new Set(['alpha.label']), + indexes: new Set(['idx_alpha_label']), + constraints: new Set(), +}; /** * A database that answered, and which ran exactly the migrations `rows` records. @@ -110,11 +110,11 @@ const FACTS_WITH_0002 = { * migrations that this database has never run". */ const seen = (rows, facts = FACTS_WITH_0002) => ({ - reachable: true, - rows, - facts, - appliedAt: rows, - }); + reachable: true, + rows, + facts, + appliedAt: rows, +}); /** A database that did not. */ const unreachable = (error = 'connect ECONNREFUSED') => ({ reachable: false, error }); @@ -1066,6 +1066,8 @@ describe('the committed baseline', () => { column: 'columns', index: 'indexes', constraint: 'constraints', + rls: 'rlsTables', + policy: 'policies', }; const factsFor = (entries) => { @@ -1074,6 +1076,8 @@ describe('the committed baseline', () => { columns: new Set(), indexes: new Set(), constraints: new Set(), + rlsTables: new Set(), + policies: new Set(), }; for (const entry of entries) { for (const item of entry.evidence) facts[FACT_SET[item.kind]].add(item.name); @@ -1136,9 +1140,7 @@ describe('the committed baseline', () => { } // A retried delivery must not append a second claim for one migration. - expect(new Set(baseline.migrations.map((e) => e.tag)).size).toBe( - baseline.migrations.length, - ); + expect(new Set(baseline.migrations.map((e) => e.tag)).size).toBe(baseline.migrations.length); }); it('an empty baseline still fails the gate on real drift', () => { @@ -1226,7 +1228,10 @@ describe('the committed baseline', () => { // // Also written against a built baseline: the committed one is empty, so running // this against it would prove nothing about the stale path. - const claimed = migrations.slice(4).map(entryFor).sort((a, b) => a.when - b.when); + const claimed = migrations + .slice(4) + .map(entryFor) + .sort((a, b) => a.when - b.when); const stale = { version: 1, migrations: claimed }; const all = migrations.map((m, i) => ({ id: i + 1, hash: m.hash, created_at: m.when })); const gate = runGate({ @@ -1283,7 +1288,12 @@ describe('the committed baseline', () => { // migration(s)" — that is the signal that a hand is needed. When 0009 is // applied and the baseline is re-derived from production, `pending` empties // and this assertion returns to `[]` on its own. - expect(gate.forward.map((m) => m.tag).slice().sort()).toEqual(pending.slice().sort()); + expect( + gate.forward + .map((m) => m.tag) + .slice() + .sort(), + ).toEqual(pending.slice().sort()); // The property this test was written for, and the one the `[]` used to carry // by implication: **nothing the baseline claims is reported as outstanding.** diff --git a/scripts/check-rls.mjs b/scripts/check-rls.mjs index 56ba7a6c..0f5b5dd0 100644 --- a/scripts/check-rls.mjs +++ b/scripts/check-rls.mjs @@ -11,8 +11,8 @@ // phase covers must have RLS on *and* the policy, every other listed table must // have RLS off *and* no policy, and any difference exits 1 naming the table. // -// Phases are cumulative, in rollout order: `wallet` (the `TENANT_ID_TABLES`), -// then the business tables in the batches of openspec tenant-isolation-rls 7.1 +// Phases are cumulative, in rollout order: `wallet` (the `TENANT_ID_TABLES`, +// plus `push_campaigns`, see `RLS_BATCHES.wallet`), then the business tables in the batches of openspec tenant-isolation-rls 7.1 // — `communication`, `growth`, then `rest` (every business table left, so // `rest` and `all` describe the same state). `none` expects nothing enabled. // @@ -39,6 +39,12 @@ export const RLS_SOURCE = 'packages/db/src/rls.ts'; * rather than in none. */ export const RLS_BATCHES = { + // Business tables the wallet phase enables alongside the `TENANT_ID_TABLES`. + // `push_campaigns` had RLS and the `tenant_isolation` policy in production + // before the rollout started, applied outside any migration. Migration 0026 + // records it with the wallet tables, so every phase from `wallet` on expects + // it enabled and `none` describes a database that predates that state. + wallet: ['push_campaigns'], communication: ['message_log', 'whatsapp_templates', 'push_subscriptions'], growth: [ 'loyalty_programs', @@ -101,14 +107,22 @@ export function parseArgs(argv) { /** The tables a phase expects enabled with the policy. */ export function expectedEnabled(expectation, lists) { - for (const table of [...RLS_BATCHES.communication, ...RLS_BATCHES.growth]) { + for (const table of [ + ...RLS_BATCHES.wallet, + ...RLS_BATCHES.communication, + ...RLS_BATCHES.growth, + ]) { if (!lists.businessIdTables.includes(table)) { throw new Error(`batch table ${table} is not in BUSINESS_ID_TABLES (${RLS_SOURCE})`); } } - const batched = new Set([...RLS_BATCHES.communication, ...RLS_BATCHES.growth]); + const batched = new Set([ + ...RLS_BATCHES.wallet, + ...RLS_BATCHES.communication, + ...RLS_BATCHES.growth, + ]); const phases = [ - ['wallet', lists.tenantIdTables], + ['wallet', [...lists.tenantIdTables, ...RLS_BATCHES.wallet]], ['communication', RLS_BATCHES.communication], ['growth', RLS_BATCHES.growth], ['rest', lists.businessIdTables.filter((t) => !batched.has(t))], diff --git a/scripts/check-rls.test.mjs b/scripts/check-rls.test.mjs index 0ae0475a..17a79cc5 100644 --- a/scripts/check-rls.test.mjs +++ b/scripts/check-rls.test.mjs @@ -78,6 +78,9 @@ function fakePool({ }; } +/** The production state after migration 0026: every table the wallet phase enables. */ +const WALLET_PHASE = new Set([...TENANT_ID_TABLES, ...RLS_BATCHES.wallet]); + describe('the table lists', () => { it('are read from packages/db/src/rls.ts, not copied', async () => { const loaded = await loadRlsTables(); @@ -85,7 +88,7 @@ describe('the table lists', () => { }); it('batches name only business tables, and `rest` is every business table left', () => { - const named = [...RLS_BATCHES.communication, ...RLS_BATCHES.growth]; + const named = [...RLS_BATCHES.wallet, ...RLS_BATCHES.communication, ...RLS_BATCHES.growth]; for (const table of named) expect(LISTS.businessIdTables).toContain(table); const rest = expectedEnabled('rest', LISTS); @@ -116,9 +119,17 @@ describe('parseArgs', () => { describe('expectedEnabled', () => { it('is cumulative: each phase keeps every earlier phase enabled', () => { expect(expectedEnabled('none', LISTS)).toEqual(new Set()); - expect(expectedEnabled('wallet', LISTS)).toEqual(new Set(LISTS.tenantIdTables)); + expect(expectedEnabled('wallet', LISTS)).toEqual( + new Set([...LISTS.tenantIdTables, 'push_campaigns']), + ); expect(expectedEnabled('communication', LISTS)).toEqual( - new Set([...LISTS.tenantIdTables, 'message_log', 'whatsapp_templates', 'push_subscriptions']), + new Set([ + ...LISTS.tenantIdTables, + 'push_campaigns', + 'message_log', + 'whatsapp_templates', + 'push_subscriptions', + ]), ); const growth = expectedEnabled('growth', LISTS); for (const table of [ @@ -136,6 +147,23 @@ describe('expectedEnabled', () => { }); describe('buildReport', () => { + it('`--expect wallet` covers push_campaigns, which was enabled before the rollout', () => { + const walletOnly = buildReport({ + lists: LISTS, + observation: observation(new Set(TENANT_ID_TABLES)), + expectation: 'wallet', + }); + expect(walletOnly.exitCode).toBe(1); + expect(formatReport(walletOnly)).toContain('push_campaigns: expected RLS on'); + + const production = buildReport({ + lists: LISTS, + observation: observation(new Set([...TENANT_ID_TABLES, 'push_campaigns'])), + expectation: 'wallet', + }); + expect(production.failures).toEqual([]); + }); + it('reports every listed table, the role, its bypass and the tables it owns, and exits 0 without an expectation', () => { const report = buildReport({ lists: LISTS, @@ -178,9 +206,20 @@ describe('buildReport', () => { it.each([ ['none', new Set()], - ['wallet', new Set(TENANT_ID_TABLES)], - ['communication', new Set([...TENANT_ID_TABLES, ...RLS_BATCHES.communication])], - ['growth', new Set([...TENANT_ID_TABLES, ...RLS_BATCHES.communication, ...RLS_BATCHES.growth])], + ['wallet', new Set([...TENANT_ID_TABLES, ...RLS_BATCHES.wallet])], + [ + 'communication', + new Set([...TENANT_ID_TABLES, ...RLS_BATCHES.wallet, ...RLS_BATCHES.communication]), + ], + [ + 'growth', + new Set([ + ...TENANT_ID_TABLES, + ...RLS_BATCHES.wallet, + ...RLS_BATCHES.communication, + ...RLS_BATCHES.growth, + ]), + ], ['rest', new Set([...TENANT_ID_TABLES, ...BUSINESS_ID_TABLES])], ['all', new Set([...TENANT_ID_TABLES, ...BUSINESS_ID_TABLES])], ])('passes `--expect %s` when the database matches it', (expectation, enabled) => { @@ -195,7 +234,7 @@ describe('buildReport', () => { (expectation) => { const report = buildReport({ lists: LISTS, - observation: observation(new Set(TENANT_ID_TABLES)), + observation: observation(WALLET_PHASE), expectation, }); expect(report.exitCode).toBe(1); @@ -209,7 +248,7 @@ describe('buildReport', () => { it('lists the wallet tables as enabled and the business tables as not, under `--expect wallet`', () => { const report = buildReport({ lists: LISTS, - observation: observation(new Set(TENANT_ID_TABLES)), + observation: observation(WALLET_PHASE), expectation: 'wallet', }); const text = formatReport(report); @@ -221,7 +260,7 @@ describe('buildReport', () => { }); it('fails and names a table whose RLS is on but whose policy is missing', () => { - const obs = observation(new Set(TENANT_ID_TABLES)); + const obs = observation(WALLET_PHASE); obs.policies = obs.policies.filter((t) => t !== 'customer_wallet_passes'); const report = buildReport({ lists: LISTS, observation: obs, expectation: 'wallet' }); @@ -339,7 +378,7 @@ describe('main', () => { }); it('exits 0 for a matching expectation and 1 for a differing one', async () => { - const walletPhase = async () => observation(new Set(TENANT_ID_TABLES)); + const walletPhase = async () => observation(WALLET_PHASE); expect((await run(['--expect', 'wallet'], walletPhase)).code).toBe(0); expect((await run(['--expect', 'all'], walletPhase)).code).toBe(1); });