Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions docs/09-Database-Design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 <fase>` 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 <fase>` 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 <fase>` 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 '<generada>';
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.

---

Expand Down
3 changes: 2 additions & 1 deletion odd/tasks/tenant-isolation-rls.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Branch: one per unit (`feat/rls-unit<N>-…`). 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
Expand All @@ -34,3 +34,4 @@ Branch: one per unit (`feat/rls-unit<N>-…`). 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.
4 changes: 2 additions & 2 deletions openspec/changes/tenant-isolation-rls/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<next>_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
Expand Down
48 changes: 48 additions & 0 deletions packages/db/drizzle/0026_wallet_rls.sql
Original file line number Diff line number Diff line change
@@ -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 "<table>";
-- ALTER TABLE "<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);
39 changes: 39 additions & 0 deletions packages/db/drizzle/meta/_applied-outside-drizzle.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}
]
}
9 changes: 8 additions & 1 deletion packages/db/drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@
"when": 1793000000000,
"tag": "0025_card_credential",
"breakpoints": true
},
{
"idx": 26,
"version": "7",
"when": 1793100000000,
"tag": "0026_wallet_rls",
"breakpoints": true
}
]
}
}
Loading
Loading