Skip to content
MSO CloudDocumentation

ADR 0054 — attested RLS context and a separate auth identity

On this page
  • Status: Accepted (2026-10-03). Rolls out in two deploys (decision 4).
  • Date: 2026-10-03
  • Owners: Platform (tenancy & security).
  • Related: closes docs/SECURITY.md RISK-002 on deploy-2 evidence; extends ADR 0010 (runtime RLS, exact runtime roles); §66 (RLS context sticks only inside runWithRlsContext), §66c (exact non-bypass identities), §118–119 (a gate seeds with one identity and proves with another), §121 (a runtime writes only what its role is granted), §126 (privileged DATABASE_URL is local-only), §141 (this ADR's rule).

Context#

app.current_org_id and app.current_brand_id are custom GUCs any session may set. Every org policy reads them, so RLS stops a trusted code path that forgets its filter but not a holder of a runtime credential: set_config('app.current_org_id', <any org>) as yng_app reads every tenant. The same role also holds authentication material (password hashes, TOTP secrets, passkeys, WebAuthn challenges, magic-link digests) and the writes that escalate (INSERT users, UPDATE users.is_super_admin, INSERT org_memberships). A leaked yng_app URL is therefore a cross-tenant read and an account takeover.

Decisions#

Decision 1 — Tenant context is attested by a key no runtime role can read

A runtime pins org and brand only through app_set_rls_context(org, brand, key_id, exp, mac, scope), a SECURITY DEFINER function owned by the migrator with search_path pinned and EXECUTE revoked from PUBLIC. It verifies mac = HMAC-SHA256(key, 'yng-rls-v1|org|brand|exp') with exp inside [now, now + 120 s], comparing digests rather than raw bytes, and raises SQLSTATE 28000 rls context token rejected otherwise. On success it sets the two GUCs, app.rls_key_id, and app.rls_attest = HMAC(key, 'yng-rls-attest-v1|org|brand|pg_backend_pid').

The key lives in app_private.rls_context_keys (32 bytes, key_id smallint, N active keys for rotation). Schema app_private grants nothing to any runtime role. The migrator converges row 1 from RLS_CONTEXT_HMAC_KEY (64 hex) through the GUC yng.rls_context_hmac_key, the same pattern as the role passwords. A superuser session_user skips verification so operator scripts as yng keep working; superuser is already outside RLS.

app_rls_attested() recomputes the attestation for the current GUC values and backend pid and compares. Every org-cohort policy gains AND (SELECT app_rls_attested()). The scalar subquery makes it an InitPlan evaluated once per statement; the org_id = app_current_org() leg is unchanged, so index conditions and estimates are identical. A raw set_config, a copied app.rls_attest, or a re-set of org or brand after a valid pin all read zero rows.

Tokens live 60 s; transaction setup stays one statement (the setter plus the two existing timeout set_configs). Cube pins with scope = 'session'; the org-archive psql scripts emit the setter with a 120 s token.

Decision 2 — Authentication material belongs to a second identity, yng_auth

A new login role yng_auth (NOSUPERUSER NOBYPASSRLS, CONNECT only, password from YNG_AUTH_DB_PASSWORD) and a second web pool (AUTH_DATABASE_URL, AUTH_DB_POOL_MAX, default 5, identity asserted at boot as AUTH_RUNTIME_DB_ROLE=yng_auth) own user_auth_secrets, user_credentials, webauthn_challenges, magic_link_tokens, user INSERT/UPDATE/DELETE and org creation. Auth paths run inside runWithAuthContext, which pins a process attestation (org empty) through the same setter; the auth tables carry one FORCE-RLS policy TO yng_auth requiring app_rls_process_attested().

Secret columns move from users to user_auth_secrets (migration 0224_attested_rls_context.sql, backfilled). yng_app keeps the non-secret users columns, organizations and org_memberships metadata for session construction and member lists; it loses user INSERT/DELETE, updates to email, email_verified, is_super_admin and disabled_at, every auth table, and membership or org writes without an attested context of that org. yng_archive loses resource_shares password_hash/token_hash and restores them through a SECURITY DEFINER helper.

Decision 3 — One key for every runtime; the operator provisions it

Web, worker, archive-worker, Cube and the migrator receive the same RLS_CONTEXT_HMAC_KEY. start-prod.sh refuses a missing, placeholder or non-64-hex value for it and for YNG_AUTH_DB_PASSWORD, and refuses the public development key; verify-prod-compose.mjs, migrate.ts (production or RLS_REQUIRE_APP_RUNTIME=1) and rls-attest.sql refuse it too, so it can never become the stored key. start-prod.sh never generates either secret: a generated key would disagree with the stored one and every tenant read would be refused. verify-prod-compose.mjs asserts the key reaches all six services with one value, the ${VAR:?} form in both compose files, and the yng_auth URL on web only. Boot refuses the built-in development key under RLS_REQUIRE_APP_RUNTIME=1 and runs a self-check (app_set_rls_context(NULL…) then app_rls_process_attested()) that must return true, so an env/DB key mismatch stops the new replica before it serves.

Decision 4 — Two deploys: additive, then enforcement

Deploy 1 adds the extension, schema, key table, user_auth_secrets, the functions, yng_auth and its grants, the signing clients and the auth pool (dual-writing secrets to both places); policies stay unattested and yng_app keeps its grants. Deploy 2, after at least one day of soak with gates green, attests the cohort policies, adds the users/organizations/org_memberships/auth-table policies, narrows the manifests and stops the dual write. Dropping physical users secret columns is deferred until rollback no longer needs them. Migrate runs while the previous web still serves; in deploy 2 that web already signs, so no replica ever reads under policies it cannot satisfy.

The original deploy-2 rollback proposal, redeploying the deploy-1 commit to widen grants, is superseded for account-authentication enforcement by migration 0259. Retain the new migrator and bootstrap tools and the enforced database permissions. Roll back only to reviewed previous signed application images after testing those exact images against the enforced database. Never run the old migrator or bootstrap: the former widens permissions, while the latter reads retired legacy password fields. Keep the physical legacy columns until previous-image compatibility is no longer required; migration 0259 does not drop them.

Preserve the new migrator image and tag the reviewed previous web, worker and matching PDF images before rollout. A bounded application rollback restores those runtime image tags and uses the current scripts/start-prod.sh --no-build; the migrator tag and current source remain on the enforcing version. Rehearse the exact previous images against disposable enforced state before treating this rollback as verified.

Account-authentication enforcement does not close decision 2's archive share-secret requirement. The archive worker still needs a sealed export/restore design that preserves protected links; omitting their password hashes would make restored links unprotected. That requirement remains open, and this account cutover alone does not close RISK-002.

Rollback of deploy 1 is NOT a redeploy of the previous commit through start-prod.sh: that runs migrate, and the previous manifest fails closed on the unknown user_auth_secrets table, so the deploy aborts at migrate (the deploy-1 web keeps serving). Instead, start the previous web/worker images with docker compose … up -d --no-build and no migrate. The 0224 objects (pgcrypto, app_private, user_auth_secrets, the sync trigger, the functions, yng_auth) stay; the previous image neither reads nor depends on them, and the trigger keeps user_auth_secrets current while the old image writes users.

Key rotation: only key_id 1 exists and converges in place. After deploy 2, rotating the env key makes the retiring replica's tokens fail (28000) for the blue/green window. Before the first rotation, wire a key_id 2 path: insert the new key as row 2, sign with key_id 2, then retire row 1 with active = false after the swap.

Decision 5 — The raw GUC is banned outside the signer

No code sets app.current_org_id or app.current_brand_id with set_config/SET except the signer module, the schema SQL, and the probe gate that asserts the raw path is refused. Gates pin through one shared helper that signs. verify:rls gains a stolen-credential probe leg (raw GUC, forged attestation, wrong/expired/over-long tokens, re-set after a valid pin, app_private reads, yng_app on auth tables and escalating columns, cross-org membership writes, yng_auth without attestation and on tenant tables, Cube/archive raw versus attested); its deploy-1 assertions on policy behaviour are informational and become fatal in deploy 2.

Rejected#

  • Per-tenant Postgres roles with SET ROLE: one role per org, pool thrash, no brand leg.
  • Database per tenant: not this product's shape.
  • Verifying the HMAC inside app_current_org(): an HMAC per row on sequential scans, and only the InitPlan form keeps the selectivity estimates.
  • A context table keyed by pg_backend_pid: a write per request for the same InitPlan cost.
  • A separate super-admin signing key: the same process would hold both.
  • Keeping yng_app on auth tables behind SECURITY DEFINER lookups: a stolen credential still reads any hash by email.
  • TLS on the compose bridge as the fix: worth doing, orthogonal to credential theft.

Consequences#

  • A runtime credential alone selects no tenant context, reads or forges no authentication material, and grants itself no membership.
  • Residual, accepted: yng_app reads user names, emails and org/membership metadata; a web or worker process compromise holds the key and both pool URLs and reaches whatever that process can; a sniffer on the compose bridge sees replayable 60-second tokens alongside passwords and results.
  • Two new operator secrets, RLS_CONTEXT_HMAC_KEY and YNG_AUTH_DB_PASSWORD, in .env.prod, and their lines mirrored into the live docker-compose.prod.yml.
  • Cost per statement: one plpgsql call, a one-row key read and one HMAC (about 15 µs) per RLS table, no per-row cost; auth paths add one BEGIN/COMMIT.
  • Guards: rls-stolen-credential-probes.ts and runtime-acl-effective.ts in verify:rls; rls-raw-guc.py, rls-policy-attested.py and auth-secret-table-runtime.py in audit:all; verify-prod-compose.mjs.