diff --git a/odd/tasks/tenant-isolation-rls.md b/odd/tasks/tenant-isolation-rls.md index a2bb68d..3be63d5 100644 --- a/odd/tasks/tenant-isolation-rls.md +++ b/odd/tasks/tenant-isolation-rls.md @@ -21,8 +21,12 @@ 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 | 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 | | +| T6 | S6 | inline | done: rehearsal clean; `vyloop_app` created in production, `DATABASE_URL` secret switched and redeployed, 0026 applied (with the `push_campaigns` policy drop in the same transaction); `db:rls --expect wallet` and `db:drift` pass as `vyloop_app`; read-only production probe clean | PR #347 | +| T7a | S7 | delegated (writer, isolated worktree; context backstop + runs alongside T7b) | in progress: SECURITY DEFINER lookups for login, refresh, signup email check and POS token (migration 0028), plus tenant transactions for the customer phone token, consents and POS `last_seen_at` | | +| T7b | S7 | inline | done locally: 0027 communication batch; rehearsal clean as `vyloop_app` (routes 200, history counts match, sweep ok); production apply pending | | +| T7c | S7 | inline | pending: growth batch, after T7a (`pos_terminals`) | | +| T7d | S7 | inline | pending: rest batch, after T7a (`users`, `customers`, `consents`) | | +| T7e | S7 | inline | pending: docs 09/18 and openspec close-out | | ## Log @@ -35,3 +39,4 @@ Branch: one per unit (`feat/rls-unit-…`). Delivery: one PR per unit, stacke - 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. +- L10 (2026-11-05) Unit 6 closed in production: user merged #347. Unit 7 map (explorer): every runtime access to business tables is tenant-scoped except identity (login and refresh by email, signup email pre-check, POS token by terminal id: cross-tenant by design; customer phone token, consents and POS `last_seen_at`: tenant known but bare `db`) and the Meta WhatsApp webhook (`message_log` by provider id, `customers` by phone). User decision for the cross-tenant identity lookups: "Funciones SECURITY DEFINER (Recommended)". The WhatsApp webhook is out of scope (WhatsApp is not used) and does not block the communication batch; 0027 documents that it fails under the policy instead of reaching another tenant. Migration numbers: 0027 communication (T7b), 0028 identity lookups (T7a). diff --git a/packages/db/drizzle/0027_communication_rls.sql b/packages/db/drizzle/0027_communication_rls.sql new file mode 100644 index 0000000..3d9523a --- /dev/null +++ b/packages/db/drizzle/0027_communication_rls.sql @@ -0,0 +1,26 @@ +-- Enable row-level security on the communication batch (openspec tenant-isolation-rls 7.1). +-- +-- `message_log`, `whatsapp_templates` and `push_subscriptions` get RLS and the +-- `tenant_isolation` policy that `enableRls()` and `createRlsPolicies()` +-- generate for a `BUSINESS_ID_TABLES` table: a row is visible, and may be +-- written, only when its `business_id` equals `app.current_business_id`, which +-- `withTenantTransaction` sets on the transaction. It binds the workers' +-- `vyloop_app` role only; the owner keeps reading everything (no FORCE). +-- +-- Every runtime access to these tables runs inside `withTenantTransaction`, +-- with one exception: the Meta WhatsApp webhook (`workers/communication/src/routes.ts`, +-- `POST /webhook`) looks up `message_log` by `provider_message_id` and +-- `customers` by phone without a tenant. WhatsApp is not in use, so that route +-- receives no traffic; under this policy its status-callback update fails +-- instead of reaching another tenant's row. +-- +-- ## Rollback +-- +-- DROP POLICY tenant_isolation ON ""; +-- ALTER TABLE "
" DISABLE ROW LEVEL SECURITY; +ALTER TABLE "message_log" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +ALTER TABLE "whatsapp_templates" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +ALTER TABLE "push_subscriptions" ENABLE ROW LEVEL SECURITY; --> statement-breakpoint +CREATE POLICY tenant_isolation ON "message_log" USING (business_id = current_setting('app.current_business_id')::UUID); --> statement-breakpoint +CREATE POLICY tenant_isolation ON "whatsapp_templates" USING (business_id = current_setting('app.current_business_id')::UUID); --> statement-breakpoint +CREATE POLICY tenant_isolation ON "push_subscriptions" 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 f994168..4c2cfd9 100644 --- a/packages/db/drizzle/meta/_applied-outside-drizzle.json +++ b/packages/db/drizzle/meta/_applied-outside-drizzle.json @@ -290,6 +290,37 @@ "name": "push_campaigns.tenant_isolation" } ] + }, + { + "tag": "0027_communication_rls", + "when": 1793200000000, + "hash": "46b07fa8ba7e8bef70edae620d6edc84807f1dab008f81bda4330f4537dc0fbf", + "evidence": [ + { + "kind": "rls", + "name": "message_log" + }, + { + "kind": "rls", + "name": "whatsapp_templates" + }, + { + "kind": "rls", + "name": "push_subscriptions" + }, + { + "kind": "policy", + "name": "message_log.tenant_isolation" + }, + { + "kind": "policy", + "name": "whatsapp_templates.tenant_isolation" + }, + { + "kind": "policy", + "name": "push_subscriptions.tenant_isolation" + } + ] } ] } diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 2761624..7471e9b 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -190,6 +190,13 @@ "when": 1793100000000, "tag": "0026_wallet_rls", "breakpoints": true + }, + { + "idx": 27, + "version": "7", + "when": 1793200000000, + "tag": "0027_communication_rls", + "breakpoints": true } ] } diff --git a/packages/db/src/migration-sql.test.ts b/packages/db/src/migration-sql.test.ts index 74090b1..8bd3c09 100644 --- a/packages/db/src/migration-sql.test.ts +++ b/packages/db/src/migration-sql.test.ts @@ -337,10 +337,14 @@ describe(`${BACKLOG_MIGRATION} closes the schema backlog`, () => { * 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[] = ['0026_wallet_rls.sql']; +const RLS_MIGRATIONS: readonly string[] = ['0026_wallet_rls.sql', '0027_communication_rls.sql']; const WALLET_RLS_MIGRATION = '0026_wallet_rls.sql'; +/** The communication batch of the rollout (`RLS_BATCHES.communication` in `scripts/check-rls.mjs`). */ +const COMMUNICATION_RLS_MIGRATION = '0027_communication_rls.sql'; +const COMMUNICATION_TABLES = ['message_log', 'whatsapp_templates', 'push_subscriptions']; + describe('row-level security is confined to the explicit RLS migrations', () => { it('lists only migrations that exist', () => { for (const name of RLS_MIGRATIONS) { @@ -368,6 +372,25 @@ describe('row-level security is confined to the explicit RLS migrations', () => expect(actual).toEqual(expected); }); + it(`${COMMUNICATION_RLS_MIGRATION} runs exactly the statements rls.ts generates for the communication batch`, () => { + const dialect = new PgDialect(); + const render = (statements: ReturnType) => + statements.map((statement) => dialect.sqlToQuery(statement).sql.replace(/;$/, '')); + const batch = (statements: string[]) => + COMMUNICATION_TABLES.map((table) => { + const match = statements.filter((statement) => statement.includes(`"${table}"`)); + expect(match).toHaveLength(1); + return match[0]; + }); + + const expected = [...batch(render(enableRls())), ...batch(render(createRlsPolicies()))]; + const actual = codeStatements(readMigration(COMMUNICATION_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) => {