On this page
- Status: Accepted — runtime posture/outbox/exact ACL implemented 2026-07-15; compromised-credential containment remains open
- Owner: Platform owner; schema/RLS changes require security review
- Related:
CLAUDE.md§66,docs/SECURITY.md, migrations 0094–0096 - Decision scope: web, worker, schema helpers, queue producers, operational scripts, production topology
Context#
The platform already used PostgreSQL ENABLE/FORCE ROW LEVEL SECURITY, but three failure modes made the deployed boundary weaker than the schema suggested:
- Production web and worker inherited the database owner credential. A superuser or
BYPASSRLSrole ignores even forced policies. set_config(..., is_local := true)was called outside an explicit transaction in legacy worker/script paths. With postgres.js autocommit, that value expires before the next query and may be set on a different pooled connection.- Web mutations published BullMQ work after commit through an in-process callback. This avoided pre-commit visibility races, but a Redis outage or process crash after PostgreSQL committed could strand a durable domain row forever.
Wrapping an entire request in one RLS transaction solved pinning but introduced another risk: provider, Redis, OAuth, object-storage, or AI calls could hold a scarce database connection while waiting on an external dependency.
Decision#
Exact service identities
- Web connects as
yng_app; worker connects asyng_worker. - Both roles are
NOSUPERUSER,NOBYPASSRLS, andNOINHERIT. - Migration/role provisioning uses a separate privileged identity and is never a runtime fallback.
- Production sets
RLS_REQUIRE_APP_RUNTIME=1and the exact expectedRUNTIME_DB_ROLE. Startup fails when the connected identity differs or has privilege-bypass flags. SECURITY DEFINERhelpers are capability APIs, not generic bypasses. Each helper has a fixed signature/result, bounded input/output, pinnedsearch_path, revokedPUBLICaccess, and an exact app-or-worker grant. Wrong-service invocation is tested live.- Non-superuser posture is necessary but not sufficient. Exact/default-deny table, sequence, function, and default-privilege grants now come from the reviewed runtime ACL manifest and are checked live. RISK-002 remains because a stolen runtime identity can still choose a tenant GUC and exercise that identity's legitimate capabilities; containment needs narrower control-plane/service identities, not another broad-grant cleanup.
Effective RLS scopes
- Tenant reads/writes execute through
runWithRlsContext(orgId, brandId, fn), which owns one transaction/connection and applies both GUCs withSET LOCAL. - Nested scopes reuse the same transaction, repin the inner IDs, and restore the outer IDs.
orgProcedure/brandProcedureare for DB-centered resolvers. An unsuccessful tRPC result is converted to a throw before the transaction boundary resolves, so partial writes and deferred effects roll back.- External work uses an orchestrated procedure: short scoped read/authorization phase → external I/O with no ambient transaction → short scoped write/audit/outbox phase.
- Bare
setOrgContext/setBrandContextoutside an active scope is compatibility behavior that fails closed under runtime roles and is forbidden in executable production/operational paths.
Durable async hand-off
job_outboxis an org-scoped, RLS-protected table. The domain row, audit row, and queue intent commit in one PostgreSQL transaction throughenqueueDurableJob(...).- Queue names, payloads, options, and colon-free stable job IDs are validated against a shared contract.
- A worker-only dispatcher claims bounded leases using a reviewed helper, publishes outside the database transaction, and records success or retry state. Stable BullMQ IDs make replay idempotent.
- Dispatcher retry uses bounded backoff, redacted error storage/logging, backlog/oldest-age metrics, and readiness degradation for stuck work.
- Production web code does not instantiate/publish BullMQ.
deferAfterCommitremains only for explicitly lossy effects whose loss is acceptable.
Alternatives considered#
- Keep the owner credential and rely on query predicates: rejected; one missing predicate becomes a cross-tenant incident and RLS supplies no defense.
- Session-level GUCs on pooled connections: rejected; context can leak across requests.
- One role for web and worker: rejected; it grants both services every helper capability and broadens compromise impact.
- Publish before commit: rejected; a fast worker can observe a missing row.
- Publish after commit in process: rejected for durable work; commit and publication are not atomic and failures cannot be replayed reliably.
- Distributed transaction across PostgreSQL and Redis: rejected; Redis/BullMQ do not participate in a useful two-phase commit and operational complexity exceeds the benefit.
- Hold the RLS transaction across external calls: rejected; it creates pool starvation, idle-transaction failures, and provider-billed work followed by DB rollback.
Threat and failure model#
The decision handles trusted application SQL that omits or mis-pins tenant context, pool reuse, duplicate delivery, Redis outages, dispatcher crashes between publish and acknowledgement, worker crashes, and malformed outbox rows. It does not contain a compromised runtime process/credential with arbitrary SQL: custom GUCs are caller-settable, so that actor can choose a tenant context and exercise every privilege its role owns. It also does not protect against compromise of the migration/owner credential, PostgreSQL host, or deployment secret manager.
Controls:
- exact role posture, table/sequence/function/default ACL, and helper-grant matrix are verified against live PostgreSQL;
- no-context and wrong-tenant reads fail closed;
- outbox publication is at-least-once, so consumers must be idempotent or use authoritative lifecycle rows;
- payload validation quarantines malformed intent rather than repeatedly publishing it;
- leases recover abandoned claims;
- external failures never extend a tenant DB transaction.
Compatibility and migration#
- Migrations are additive: runtime roles/helpers, then
job_outbox, then producer migrations. - Existing BullMQ processors and queue names remain; only publication ownership changes.
- Connector sync keeps the web-created
sync_jobsrow as the authoritative lifecycle record and passessyncJobIdto the worker, eliminating duplicate rows. - Local development may retain the owner URL for migrations/fixtures and emits a warning. CI/staging/production make that posture fatal.
Rollout#
- Apply schema and helper migrations with the migration identity.
- Verify both runtime roles and the complete helper catalog/grant matrix.
- Deploy dispatcher-capable workers before or with the first outbox producers.
- Flip web to
yng_app, then worker toyng_worker, with isolation/readiness probes. - Monitor outbox backlog, oldest age, publish failures, queue lag, and DLQ rate.
Rollback#
- Roll back application images while retaining additive schema objects.
- Do not revert runtimes to the owner credential as an operational shortcut. If a helper is missing, deploy a reviewed helper/grant migration or temporarily disable the affected feature.
- Outbox rows are replayable after restoring dispatcher health; they must not be deleted to make readiness green.
Evidence and metrics#
pnpm run verify:rls: complete policy inventory, exact role posture, 14-helper grant matrix, wrong-service denials, and live tenant isolation.scripts/audit/durable-job-outbox.py: ratchets every reviewed durable producer and rejects direct web publication.packages/schema/src/job-outbox-contract.test.tsandapps/worker/src/job-outbox-dispatcher.test.ts: contract, lease, retry, idempotency, redaction, and bounded-concurrency behavior.apps/web/src/__tests__/trpc-external-orchestration.test.ts: external phase has no ambient DB transaction and write phases restore scope.- Operational metrics: pending count, oldest pending age, publish success/failure, lease recovery, queue start lag, completion latency, and DLQ count.
Consequences#
Trusted application paths now depend on an executable role/scope contract rather than query predicates alone, and a committed domain row cannot lose its queue intent through ordinary Redis/process failure modes. This is not yet a runtime-compromise containment boundary until RISK-002 closes. The trade-off is more explicit orchestration and at-least-once processing; every durable job must define idempotency and join the shared contract/audit.