AISOCin‑a‑box

Multi-Tenancy & RLS

Tenant isolation in the reference stack is a database property, not an application convention: every business query runs as a NOBYPASSRLS role inside a transaction whose first statement scopes it to one tenant, and Postgres Row-Level Security is the load-bearing wall. Spec source: §1.3.1 ("shared database, shared schema, Row-Level Security as the load-bearing wall. Application roles are SET LOCAL-scoped per request; the ORM never sees a superuser," line 540). Implementation: db/rls/01-schema.sql (DDL + policies, applied on every boot) and apps/control-plane-api/src/soc_api/deps/{auth.py,db.py,rls.py} (request path).

1. The wall — 13 tables, 4 policies each

db/rls/01-schema.sql enables RLS on, and forces it for, 13 tenant-scoped tables:

tenants, users, edges, connectors, alerts, cases, timeline_events, hitl_approvals, containment_actions, audit_events, saved_queries, esql_runs, metrics_daily

Each gets the same four-policy shape (loop at schema line 292):

CREATE POLICY tenant_isolation_<table>_select
  ON <table> FOR SELECT
  USING (tenant_id = current_setting('app.tenant_id', true));

CREATE POLICY tenant_isolation_<table>_insert
  ON <table> FOR INSERT
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true));

CREATE POLICY tenant_isolation_<table>_update
  ON <table> FOR UPDATE
  USING (tenant_id = current_setting('app.tenant_id', true))
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true));

CREATE POLICY tenant_isolation_<table>_delete
  ON <table> FOR DELETE
  USING (tenant_id = current_setting('app.tenant_id', true));

Design details that matter:

  • FORCE ROW LEVEL SECURITY on all 13 — even the table owner is not exempt (§1.3.1). The wall holds regardless of which role a stray connection happens to be.

  • The GUC's second argument is true — current_setting returns NULL instead of erroring when the setting is absent, so an unscoped query evaluates tenant_id = NULL → no rows. ∅ is the failure mode, never an error and never "all rows".

  • INSERT/UPDATE carry WITH CHECK — without it, an INSERT could copy another tenant's row values into a new row (schema comment, line 259).

  • Uniform tenant_id scope column on every table — including tenants itself, where a trigger (tenants_tenant_id_sync) keeps tenant_id = id. This closes the escape hatch where a multi-statement query names the id column instead of tenant_id and the GUC stops matching (schema comment, lines 11–16).

  • The app role (soc_app, created at schema line 333): NOBYPASSRLS, search_path locked to public, statement_timeout = 5s. Grants are the narrow set the request path needs:

    Grant Tables Note
    SELECT, INSERT, UPDATE users, edges, connectors, alerts, cases, timeline_events, hitl_approvals, containment_actions, saved_queries, esql_runs, metrics_daily, tenants the business surface
    DELETE saved_queries only /api/esql/saved delete
    SELECT, INSERT (DELETE explicitly revoked) audit_events append-only mirror of the §3.4 hash chain — the projection cannot be edited from the request path
    DELETE revoked hitl_approvals approvals are update-decision-only
  • BYPASSRLS is stripped from the owner role too (schema line 355): the compose superuser gets BYPASSRLS from the postgres entrypoint, so the schema removes it — any stack built from this file is RLS-honest, not only the one booted the blessed way.

2. The request path — how the GUC gets set

X-Tenant-Id + X-Actor-Subject  (headers — the tenant is never a query
        │                          param; spec §4.4.3: serializer/view
        ▼                          choice is token-derived, never param-derived)
deps/auth.py resolve_caller     401 NO_TENANT | UNKNOWN_SUBJECT |
  regex ^tnt_[a-z0-9_]+$|^platform$   AUTH_STORE_UNAVAILABLE
  roles + mfa_enrolled from the       403 FORBIDDEN (perm not in role set)
  seeded users table (tenant-scoped
  read — the RLS wall guards the
  lookup too)
        ▼
deps/db.py app_conn(tenant)      regex re-check → refuse unscoped
  DSN rewrite soc_api → soc_app  transactions at the DB seam
  SELECT set_config('app.tenant_id', $1, FALSE)   -- SESSION scope:
  BEGIN                                     survives the transaction
  SELECT set_config('app.tenant_id', $1, TRUE)    -- LOCAL scope: the
        ▼                                     per-request wall
tenant_db(tenant) context        commit / rollback, then
  yield conn                      RESET app.tenant_id + close
  ...business queries...
  • Two levels of scoping, deliberately. The SESSION-level set_config(..., FALSE) makes the GUC readable at the transaction boundary the policies evaluate under; the LOCAL-level set_config(..., TRUE) is the per-request SET LOCAL of spec line 685 (BEGIN; SET LOCAL …; <queries>; COMMIT) and dies with the transaction. tenant_db's RESET is hygiene for the pooled-connection next user.
  • Fail closed, twice. Routers 401/403 before opening a transaction, so an unscoped read is structurally impossible; and even if one slipped through, NULL GUC ⇒ RLS ⇒ ∅ rows (schema comment + db.py module docstring).
  • The Phase-A seam is unit-tested. deps/rls.py::set_tenant_scope (the canonical single sanctioned place tenant scope is set) raises on missing/empty/non-tnt_ tenant ids — tests/unit/test_rls.py covers all three. db.py's app_conn applies the same rule with the fuller regex (which also admits the platform scope).

3. The role matrix (RBAC on top of the wall)

RLS answers "which tenant's rows"; RBAC answers "which actions". deps/auth.py::ROLE_PERMS condenses the spec §1.3.2 matrix to the permissions this API gates on (roles come from the seeded users table, per tenant — not from env):

Role Surface
client_exec read cases / metrics / reports
viewer read-only customer surface (cases, metrics, reports, timeline, edges, connectors)
client_it + update cases, request actions, run ES|QL, manage users
analyst + ingest alerts, approve actions, read audit
manager approve-only (the §4 A4 approvals role)
concierge_lead analyst + read tenants, manage users
admin tenant-local administration (+ manage connectors)
platform_admin tenants:manage + fleet/metrics/connectors read — no telemetry read path: platform_admin is not a tenant and no RLS policy grants it one (separation of duties, schema comment line 262). Platform identity resolution (platform_caller) scans the platform GUC scope, deliberately crossing tenants.

PUBLIC_PERMS = {alerts:ingest, tenants:bootstrap}: the edge tunnel presents a tenant credential, not a user session (§1.2.4), so ingest is gated to the tenant, with analyst-or-above additionally required when a user acts. MFA gate (D-V1): approvals submitted by users without mfa_enrolled = true never count — hitl_approvals.mfa_verified is checked server-side per decision.

4. Tenancy beyond Postgres

Substrate Production design (spec §1.3.1) Reference stack (what runs)
Elasticsearch Per-tenant index patterns; one ES role per tenant + one API service user per tenant; the control plane selects the ES client by tenant. DLS row filtering is [LIC?] Platinum/Enterprise — not load-bearing; the Basic-baseline fence is index-pattern-scoped roles (free-tier RBAC) + API-injected tenant_id filter + a CI cross-tenant probe (query as A, assert zero B docs) One shared loopback-only ES (security disabled by design — the box keeps raw logs on the customer's appliance). Tenancy = per-tenant index stamping by the Vector sink (soc-box-ecs-{SOC_TENANT}-%Y.%m.%d) + the tenant registry: esql.py validates every query against tenants.index_allow_list and routes to tenants.es_url (per-tenant endpoint). No DLS roles exist in the reference (spec-only; see §6).
Audit chain §3.4: one hash chain per tenant, audit-before-execute Per-tenant ChainWriter in the orchestrator (TenantChains — one sqlite chain-{tenant_id}.db per tenant, tenant id regex-validated before a writer is created) + a per-tenant PG mirror (audit_events PK (tenant_id, seq), UNIQUE (tenant_id, event_hash), append-only). GET /v1/audit/{tenant}/chain verifies its own tenant's chain only.
Orchestrator state PostgresSaver checkpoint under the tenant scope (§3.2.4) In-memory MemorySaver keyed per case run; tenancy lives in the durable projections (case/approval/timeline rows) and the per-tenant chain, not in the graph memory.

5. The tests that actually run

apps/control-plane-api/tests/integration/test_cross_tenant.py — real HTTP against a live stack + real SQL as the RLS role. Opt-in via env (skips cleanly otherwise so plain unittest runs stay green):

SOC_IT_PG_DSN='postgresql://soc_app:[email protected]:54330/soc_control' \
SOC_IT_API=http://127.0.0.1:8117 \
PYTHONPATH=apps/control-plane-api/src python3 -m unittest tests.integration.test_cross_tenant
Test Asserts
test_db_empty_read_as_b A scoped connection as tnt_globex_02 reads 0 rows of tnt_acme_01 in 9 tables (cases, alerts, timeline_events, hitl_approvals, containment_actions, audit_events, esql_runs, metrics_daily, saved_queries)
test_no_guc_empty_read An unscoped connection (GUC unset) reads ∅ — the fail-closed property, §2
test_api_404_identical A's case id under B's headers → 404 with a body byte-identical to a random missing id on the case + timeline + evidence + actions + approvals sub-routes — the "no 403 that confirms existence" rule
test_lists_do_not_leak A's case id is absent from B's /api/cases?limit=500 listing

Plus tests/unit/test_rls.py (the set_tenant_scope fail-closed seam, §2) and the rest of the control-plane unit suite (unittest discover). Repo convention (AGENTS.md tenancy rules): every new table ships its RLS policy and its ∅-read test in the same PR — the db/rls loop + this test file are the standing pattern.

6. What is not true yet (honesty)

Per deliverables/audit-2026-11-23.md:

  • G1 suite 1.A1–1.A14: NOT-STARTED — "zero of 14 exist" (audit line 122). The in-repo tests above are the proxy; the spec's Phase-1 gate items (1.A8 cross-tenant query 403, 1.A9 RLS SET ROLE bypass attempt, 1.A10 nightly pen-test of every endpoint + the tunnel) have not been written. The audit's own recommendation (line 216): start with 1.A8/1.A9/1.A10 against the reference stack — they are the G1 hard items with the longest lead time.
  • D4 — "tenancy in the datastore": Partial. PG RLS follows §1.3.1 for the reference tables (true and tested); the ES per-tenant index + DLS role template is spec-only, no DLS roles exist (audit line 168).
  • D2 — "sovereignty is physical": Partially — convention, not gate. Compose hard-binds every host port to 127.0.0.1 and tailnet exposure goes only through tailscale serve; but there is no outbound-only WireGuard agent and no 1.A3 (ss -ltn / nmap) acceptance test (audit line 166).
  • Spec request path is JWT + per-tenant ES client selection (line 685); the reference uses X-Tenant-Id / X-Actor-Subject headers with a seeded users table. The wall (RLS + fail-closed ∅ + 404-identical) is the same shape in both; the credential plumbing is the Phase-1 delta.