Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Give the services a database role the RLS policies actually apply to (#824)
Beenu Arora4ed5b31d2f37
diff --git a/.env.example b/.env.exampleindex 2d49826b2..b881e5d1d 100644--- a/.env.example+++ b/.env.example@@ -66,11 +66,33 @@ CONNECTORS_SERVICE_URL=http://connectors:8003CONNECTORS_SERVICE_TIMEOUT_SECONDS=15# ─── Database ─────────────────────────────────────────────────────────────────-# POSTGRES_PASSWORD is the dev password for the bundled Postgres container.-# `docker-compose.yml` and the API both interpolate this value, so changing it-# here is enough to rotate the dev password across the stack.+# Two roles, and the distinction is load-bearing rather than tidy.+#+# aisoc owner. Superuser (the postgres image makes POSTGRES_USER one),+# owns every table, applies the migration chain. No service+# connects as it.+# aisoc_app runtime. SELECT / INSERT / UPDATE / DELETE and nothing else, so+# that the schema's row-level-security policies apply to it. A+# superuser ignores those policies even under FORCE ROW LEVEL+# SECURITY, which is why running the services as `aisoc` left all+# 92 of them filtering nothing.+#+# POSTGRES_PASSWORD is the owner's; AISOC_APP_DB_PASSWORD is the runtime role's.+# Both are interpolated by docker-compose.yml, so changing them here rotates+# them across the stack. They are deliberately different values: they are+# different privilege levels.POSTGRES_PASSWORD=aisoc_dev_secret-DATABASE_URL=postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD}@localhost:5432/aisoc+AISOC_APP_DB_PASSWORD=aisoc_app_dev_secret++# What every service connects as.+DATABASE_URL=postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD}@localhost:5432/aisoc++# DDL only: `python -m app.scripts.run_migrations` uses this and nothing else+# does. Leave it unset and migrations fall back to DATABASE_URL, which is+# correct for a deployment that has not split the roles and fails loudly+# ("permission denied for schema public") on one that has.+# aisoc-db-role: owner — the migration chain applies DDL; the runtime role holds none+DATABASE_MIGRATION_URL=postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD}@localhost:5432/aisocREDIS_URL=redis://:redis_dev_secret@localhost:6379/0CLICKHOUSE_URL=http://aisoc:clickhouse_dev_secret@localhost:8123/aisocdiff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex edb83ef26..28657c0c1 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -277,7 +277,15 @@ jobs:--health-timeout 5s--health-retries 10env:- DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/aisoc+ # The two roles the default deployment ships, wired the same way here.+ # DATABASE_URL is what every service connects as: DML only, and the RLS+ # policies apply to it. DATABASE_MIGRATION_URL is the owner, used for DDL+ # and nothing else. Wiring this job as a single superuser is what let 92+ # RLS policies sit inert for months while the replay below went green+ # against a role invented by the test.+ DATABASE_URL: postgresql+asyncpg://aisoc_app:aisoc_app_ci_secret@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/aisoc+ AISOC_APP_DB_PASSWORD: aisoc_app_ci_secretSECRET_KEY: ci-dummy-secret-key-at-least-32bytes!ENVIRONMENT: developmentAISOC_MIGRATIONS_STRICT: '1'@@ -349,18 +357,26 @@ jobs:# replay runs here — the only job with a real database and the full# chain already applied.#- # It connects as a purpose-made role with neither SUPERUSER nor- # BYPASSRLS, because the role the services actually use is a superuser- # and would sail past every policy. That fact is itself asserted, so- # nobody can read a green tick here as "isolation is on in production".+ # It reads as `DATABASE_URL`, which is the role the default deployment+ # ships. It used to construct its own NOSUPERUSER NOBYPASSRLS role+ # because the shipped one was a superuser that sailed past every policy;+ # a green tick then proved a property of a role nothing ran as.+ # 061_runtime_app_role.sql made the shipped role the one the policies are+ # written for, so the replay now covers what ships.## POSTGRES_RLS_ISOLATION_REQUIRED turns an unreachable database into a# failure rather than a skip, for the same reason as the job above.- - name: Postgres row-level security isolation (live, two tenants)+ - name: Postgres row-level security isolation (live, two tenants, as the shipped role)env:POSTGRES_RLS_ISOLATION_REQUIRED: '1'run: python -m pytest tests/isolation/test_postgres_rls.py -v --tb=short+ # The static half of this gate runs on every PR in security.yml. This is+ # the half that can only be answered by a database: the role the+ # deployment actually connects as, inspected in pg_roles and pg_class.+ - name: Runtime DB role cannot bypass RLS (live)+ run: python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL" --owner-dsn "$DATABASE_MIGRATION_URL"+# The UEBA package layout (app/ dir) isn't wheel-buildable; alembic's# env.py only needs `app.models.ueba` importable, so run in-place with# PYTHONPATH instead of pip-installing the service.@@ -372,6 +388,7 @@ jobs:env:PYTHONPATH: .# Dedicated database so the SQL-runner schema above is untouched.+ # aisoc-db-role: owner — alembic applies DDL and reads DATABASE_URL by its own conventionDATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/ueba_cirun: |set -euo pipefail@@ -401,6 +418,7 @@ jobs:--health-timeout 5s--health-retries 10env:+ # aisoc-db-role: owner — pg_dump/pg_restore read and rewrite every table, including ones the runtime role cannotPOSTGRES_URL: postgresql://aisoc:aisoc_ci_secret@localhost:5432/aisocBACKUP_S3_BUCKET: s3://aisoc-dr-testBACKUP_S3_PREFIX: ci-dr@@ -635,6 +653,7 @@ jobs:--health-timeout 5s--health-retries 10env:+ # aisoc-db-role: owner — this job replays released migration chains, which is DDL from end to endDATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/aisocSECRET_KEY: ci-dummy-secret-key-at-least-32bytes!ENVIRONMENT: developmentdiff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex d2d80b5ef..6a5431680 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -24,6 +24,15 @@ on:- "scripts/check_route_auth.py"- "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"+ # The runtime-DB-role gate reads these, so a change to any of them has+ # to re-run it. A gate whose inputs are outside its own path filter is+ # a gate that stops running exactly when somebody edits what it checks.+ - "scripts/check_runtime_db_role.py"+ - "scripts/check_rls_policy_shape.py"+ - "docker-compose.yml"+ - "infra/**"+ - ".env.example"+ - "render.yaml"- ".github/workflows/isolation.yml"pull_request:paths:@@ -33,6 +42,15 @@ on:- "scripts/check_route_auth.py"- "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"+ # The runtime-DB-role gate reads these, so a change to any of them has+ # to re-run it. A gate whose inputs are outside its own path filter is+ # a gate that stops running exactly when somebody edits what it checks.+ - "scripts/check_runtime_db_role.py"+ - "scripts/check_rls_policy_shape.py"+ - "docker-compose.yml"+ - "infra/**"+ - ".env.example"+ - "render.yaml"- ".github/workflows/isolation.yml"# Matching isolation-live.yml, so a maintainer can run the isolation gate on# demand rather than only when a path filter happens to match.@@ -136,6 +154,26 @@ jobs:- name: Every query on a tenant-scoped table filters on a tenantrun: python scripts/check_tenant_query_predicates.py+ # The second layer, which was decoration until 061_runtime_app_role.sql:+ # every service connected as a superuser, and a superuser ignores RLS+ # policies even under FORCE ROW LEVEL SECURITY. This is the static half —+ # the deployment surfaces. integration.yml runs the live half against a+ # real database, where the role's attributes can be read directly.+ - name: Runtime-DB-role gate self-test (both directions)+ run: python scripts/check_runtime_db_role.py --self-test++ - name: No service connects as a role that can bypass RLS+ run: python scripts/check_runtime_db_role.py++ # The other way the second layer fails: a policy without the+ # `OR current_tenant_id() IS NULL` arm makes every cross-tenant worker+ # see zero rows and report success. Silent, and worse than the bypass.+ - name: Policy-shape gate self-test (both directions)+ run: python scripts/check_rls_policy_shape.py --self-test++ - name: Every RLS policy admits an unbound session and reads the GUC the tree sets+ run: python scripts/check_rls_policy_shape.py+- name: Start Redis for the two-tenant route replayrun: |docker run -d --name route-iso-redis -p 6379:6379 redis:7-alpinediff --git a/CHANGELOG.md b/CHANGELOG.mdindex bdeae1ab2..df34adb3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -920,6 +920,80 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **The services no longer connect to Postgres as a superuser, so the 92+ row-level-security policies added below now actually filter.** The previous+ entry closed the coverage gap and measured, in the same breath, that none of+ it did anything: `docker-compose.yml`, the CI service containers, the Helm+ chart and the Terraform environment all ran every service as+ `POSTGRES_USER=aisoc`, which the postgres image creates as a **superuser**,+ and a superuser ignores policies *even under* `FORCE ROW LEVEL SECURITY` —+ FORCE binds the table owner, not a superuser. Sixty-one new policies bought+ nothing operationally.++ `061_runtime_app_role.sql` splits the credential in two. `aisoc` owns the+ schema and applies migrations; `aisoc_app` is what every service connects+ as, holding `USAGE` on `public`, `SELECT / INSERT / UPDATE / DELETE` on+ tables and views, `USAGE, SELECT` on sequences and `EXECUTE` on functions —+ no `CREATE`, no `TRUNCATE` (`002_rls.sql` had granted `ALL`, which let one+ statement delete every tenant's rows without a policy seeing a `WHERE`+ clause), and ownership of nothing. Measured on `postgres:16` with two alerts+ seeded one per tenant and the session bound to tenant A, reading `alerts`+ with **no tenant predicate at all**: the old role saw 2, the new role sees+ 1, and an insert for tenant B is refused by the policy.++ Things this turned up along the way, each of which would have survived the+ role switch and quietly undone it:++ - **Two views read around every policy underneath them.** A view executes as+ its *owner* unless declared `security_invoker`, and both views here are+ owned by the role that ran the chain. Bound to tenant A,+ `mssp_tenant_latest_metrics` returned 2 rows before and 1 after.+ - **`SET LOCAL row_security = off` stops being a no-op and becomes a+ crash.** For a role the policies apply to, Postgres refuses the query+ rather than ignoring the policy. The retention purge, the hunt scheduler's+ sweep and tenant deletion all used it; all three now rely on the+ `OR current_tenant_id() IS NULL` arm and call `assert_cross_tenant_session()`+ first, which raises if a tenant *is* bound — a sweep that sees one tenant+ and reports success is worse than one that fails.+ - **`CREATE TABLE IF NOT EXISTS` still needs `CREATE` on the schema when the+ table already exists**, because Postgres checks the ACL before the+ existence test. Two stores in `services/agents` opened their pool that way+ and swallowed the failure into `logger.debug`, so the agents service would+ have silently recorded no cost telemetry and no institutional memory at+ all. Both tables are already in the migration chain; the bootstrap now+ probes first and reports at `error` if it genuinely has to create one.++ Deployment surfaces updated: `docker-compose.yml`, the demo compose stack,+ `integration.yml`, the Helm chart's `values.yaml`, the Terraform environment+ (which now generates the runtime role's password rather than reusing the RDS+ master user) and `.env.example`. `infra/postgres/initdb/zz_runtime_role_password.sh`+ sets the credential on a fresh volume before the container reports healthy;+ `app.scripts.run_migrations` applies it on every run, which covers an+ upgrade in place. **Operators on a managed Postgres must act**: apply the+ chain as the owner with `AISOC_APP_DB_PASSWORD` set, then point+ `DATABASE_URL` at `aisoc_app` and `DATABASE_MIGRATION_URL` at the owner.+ `002_rls.sql` created `aisoc_app` with the literal password `changeme`; 061+ does not clear it (that would break an operator who had already set a real+ one), so rotate it if none of the automatic paths applies to you.++ Two new gates, both with a self-test that runs before the scan and both+ failing over an empty or absent tree. `scripts/check_runtime_db_role.py`+ fails if a runtime DSN connects as the role that surface provisions as the+ database superuser — structurally, by reading `POSTGRES_USER` /+ `db_username` out of the tree rather than matching a name — and in+ `--dsn` mode reads `pg_roles` and `pg_class` directly, catching+ `rolsuper`, `rolbypassrls`, ownership, a view without `security_invoker`,+ and a role still accepting `changeme`. `scripts/check_rls_policy_shape.py`+ fails if a policy is written without the fail-open arm, replaying the chain+ in order so a definition a later migration repaired is not reported. Both+ run in `isolation.yml`; the live half runs in `integration.yml`.++ `tests/isolation/test_postgres_rls.py` now reads as `DATABASE_URL` — the+ role the deployment ships — instead of a `NOSUPERUSER NOBYPASSRLS` role it+ constructed for itself, so its 80-table two-tenant replay covers what ships.+ `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` is replaced+ by its inverse.+- **Row-level security covered 31 of 95 tenant-scoped tables; it now covers 92,and the seven policies that already existed but could never work arerepaired.** On the other 64 tables the query predicate was the only thingdiff --git a/ROADMAP.md b/ROADMAP.mdindex 830c027f7..4310bac5f 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **134 rows — 126 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **136 rows — 128 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex e4e845171..c6013eb0b 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 126 rows+The last row is the one worth reading first. It is the honest index: 128 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex b0bc983c8..7b711e695 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -111,9 +111,21 @@ Source: [`services/api/app/auth/saml.py`](https://github.com/beenuar/AiSOC/blob/### Database, cache, queue+**Two Postgres roles, and the distinction is a security control.** `DATABASE_URL`+is the role every service connects as: `aisoc_app`, which holds+`SELECT / INSERT / UPDATE / DELETE` and nothing else, so the schema's+row-level-security policies apply to it. `DATABASE_MIGRATION_URL` is the owner,+read by the migration runner and by nothing else. Running the services as the+owner — which every deployment surface did until `061_runtime_app_role.sql` —+leaves all 92 RLS policies filtering nothing, because a superuser ignores them+even under `FORCE ROW LEVEL SECURITY`. See+[Security → Multi-tenant isolation](../operations/security#the-role-the-services-connect-as).+| Variable | Default | Description ||----------|---------|-------------|-| `DATABASE_URL` | `postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc` | Async Postgres DSN |+| `DATABASE_URL` | `postgresql+asyncpg://aisoc_app:aisoc_app_dev_secret@localhost:5432/aisoc` | Async Postgres DSN for the **runtime** role. DML only. |+| `DATABASE_MIGRATION_URL` | unset → falls back to `DATABASE_URL` | Async Postgres DSN for the **owner**. Used only by `python -m app.scripts.run_migrations`, which needs DDL. |+| `AISOC_APP_DB_PASSWORD` | `aisoc_app_dev_secret` in compose; unset elsewhere | Password applied to the runtime role, by the postgres init hook on a fresh volume and by the migration runner on every run. Unset leaves the role's credential alone. || `DATABASE_POOL_SIZE` | `20` | SQLAlchemy pool size || `DATABASE_MAX_OVERFLOW` | `10` | SQLAlchemy max overflow || `REDIS_URL` | `redis://localhost:6379/0` | Redis DSN |@@ -383,7 +395,13 @@ These services read the same `AISOC_CORS_ORIGINS` / `CORS_ORIGINS` pair and fall# --- API ---SECRET_KEY=$(openssl rand -hex 32)ACCESS_TOKEN_EXPIRE_MINUTES=30-DATABASE_URL=postgresql+asyncpg://aisoc:changeme@localhost:5432/aisoc+# The runtime role: DML only, so row-level security applies to it.+DATABASE_URL=postgresql+asyncpg://aisoc_app:$(openssl rand -hex 16)@localhost:5432/aisoc+# The owner: DDL, read by the migration runner and nothing else.+DATABASE_MIGRATION_URL=postgresql+asyncpg://aisoc:changeme@localhost:5432/aisoc+# Applied to the runtime role when the chain is applied. Must match the+# password in DATABASE_URL above.+AISOC_APP_DB_PASSWORD=...REDIS_URL=redis://localhost:6379/0KAFKA_BOOTSTRAP_SERVERS=localhost:9092OPENSEARCH_URL=http://localhost:9200diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.mdindex 154be7f03..3da82d2c1 100644--- a/apps/docs/docs/operations/security.md+++ b/apps/docs/docs/operations/security.md@@ -116,31 +116,72 @@ The model:The three that remain are named rather than rounded away: `users` is excluded deliberately (below), and `case_tasks` / `case_timeline` are ORM models that no migration creates, so there is no table to protect.-### Two reasons RLS may not be protecting you right now+### The role the services connect as-**Your database role probably bypasses it.** A role with `SUPERUSER` or `BYPASSRLS` ignores policies *even under* `FORCE ROW LEVEL SECURITY` — FORCE binds the table owner, not a superuser. `docker-compose.yml` and the CI service containers both run every service as `POSTGRES_USER=aisoc`, and the `postgres` image creates that role as a superuser. In that configuration **no policy in this database is doing anything**, and it is measured rather than assumed: `tests/isolation/test_postgres_rls.py` seeds two tenants, binds the session to one, and asserts the shipped role still sees both.+A role with `SUPERUSER` or `BYPASSRLS` ignores policies *even under* `FORCE ROW LEVEL SECURITY` — FORCE binds the table owner, not a superuser. And an owner, though bound by FORCE, can simply issue `ALTER TABLE … NO FORCE ROW LEVEL SECURITY`. So there are three ways around a policy, and the default deployment used to hand a service all three at once: every service connected as `POSTGRES_USER=aisoc`, which the `postgres` image creates as a superuser and which owns every table the chain builds. **In that configuration no policy in this database did anything**, which was measured rather than assumed.-To make the policies live, connect the services as a role with neither attribute:+[`061_runtime_app_role.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/061_runtime_app_role.sql) splits the credential in two, and every deployment surface in this repository now ships the split:-```sql-CREATE ROLE aisoc_app LOGIN PASSWORD '<a real secret>' NOSUPERUSER NOBYPASSRLS;-GRANT USAGE ON SCHEMA public TO aisoc_app;-GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO aisoc_app;-GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO aisoc_app;-ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO aisoc_app;+| Role | What it is for | Grants |+| --- | --- | --- |+| `aisoc` (`POSTGRES_USER`) | Owns every table. Applies the migration chain. **No service connects as it.** | Everything, by ownership |+| `aisoc_app` | Every service's `DATABASE_URL`. Row-level security applies to it. | `USAGE` on schema `public`; `SELECT, INSERT, UPDATE, DELETE` on tables and views; `USAGE, SELECT` on sequences; `EXECUTE` on functions |++That grant list is the whole of it. No `CREATE` on the schema, so the role cannot create or alter a table. No `TRUNCATE`, which would otherwise let one statement delete every tenant's rows without a policy seeing a `WHERE` clause — `002_rls.sql` had granted `ALL`, and 061 revokes it. No `REFERENCES`, no `TRIGGER`. The role owns nothing.++`EXECUTE` on functions looks redundant because `PUBLIC` holds it by default, and on a stock database it is. It is spelled out because a deployment that hardens with `REVOKE ALL ON ALL FUNCTIONS FROM PUBLIC` would otherwise break RLS itself: `current_tenant_id()` is evaluated as the querying role inside every policy.++`DATABASE_MIGRATION_URL` carries the owner's DSN and is read by `python -m app.scripts.run_migrations` and nothing else. Leave it unset and migrations fall back to `DATABASE_URL`, which is right for a deployment that has not split the roles and fails loudly — `permission denied for schema public` — on one that has.++Verify any deployment with:++```bash+python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL" --owner-dsn "$DATABASE_MIGRATION_URL"```-Then point `DATABASE_URL` at `aisoc_app` and keep migrations running as the owner. Verify with:+It reads `pg_roles` and `pg_class` directly, so it answers for the database rather than for the config file, and it fails on all three bypasses plus a view that reads around the policies. `rolsuper` and `rolbypassrls` must both be false and the role must own nothing.++#### Two views were reading around the policies++A view executes its underlying reads as the **view's owner** unless it is declared `security_invoker`. Both views in this schema are owned by the role that ran the chain, so `mssp_tenant_latest_metrics` and `mssp_effective_tenant_rules` would have gone on returning every tenant's rows to `aisoc_app` after the role switch — a bypass that survives the fix meant to close it. Measured: bound to tenant A, the view returned 2 rows before and 1 after. 061 switches both to `security_invoker`, and the gate checks views as well as tables.++#### What an operator still has to do++The compose stacks and CI need nothing: `infra/postgres/initdb/zz_runtime_role_password.sh` runs inside the postgres image's first-boot init, after the migration chain and before the container reports healthy, and sets the runtime role's password from `AISOC_APP_DB_PASSWORD`. `depends_on: service_healthy` makes that ordering a guarantee rather than a race.++Three cases are **not** automatic:++* **An existing data volume.** `/docker-entrypoint-initdb.d` only runs when the data directory is empty, so `docker compose up` on a stack you already had never reaches that script. `app.scripts.run_migrations` applies `AISOC_APP_DB_PASSWORD` on every run, which covers it — but the API must have run migrations once with the variable set before the other services can authenticate. On a stack upgraded in place, expect the non-API services to fail their first connection attempts and recover on restart.+* **A managed Postgres** (RDS, Cloud SQL, a Helm-installed chart). There is no init hook. Apply the chain as the owner with `AISOC_APP_DB_PASSWORD` in the job's environment, then point the services' `DATABASE_URL` at `aisoc_app`. The Terraform environment generates the password for you (`terraform output -raw db_app_password`); the Helm chart ships no Secret template, so `values.yaml` spells the three steps out.+* **Rotating away from `changeme`.** `002_rls.sql` created `aisoc_app` with that literal. 061 does not clear it, because clearing it would break an operator who had already set a real password. Everything above overwrites it; if none of it applies to you, set one by hand. `check_runtime_db_role.py --dsn` tries that password and fails if it still works.++### A session that never bound a tenant still sees everything++If `app.current_tenant_id` is not set the policy permits the query. That is deliberate and load-bearing: ingest, fusion, the hunt scheduler's sweep, the retention purge and tenant deletion all operate across tenants and would otherwise process nothing, silently. Every policy in all five schema chains carries the arm```sql-SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user;+USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)```-Both flags must read `f`. `002_rls.sql` already creates an `aisoc_app` role with the literal password `changeme`; set a real one before using it.+and [`scripts/check_rls_policy_shape.py`](https://github.com/beenuar/AiSOC/blob/main/scripts/check_rls_policy_shape.py) fails if one is added without it. **A worker that silently stops seeing data is a worse failure than the bypass this change closes**, so that gate matters as much as the role does.++One construct did not survive the switch. `SET LOCAL row_security = off` appeared in the retention purge, the hunt scheduler and tenant deletion, and it only ever worked because the connecting role was a superuser: for a role the policies apply to, Postgres does not ignore them when row security is off — it raises `query would be affected by row-level security policy for table "…"`. All three now rely on the unbound-session arm and call `assert_cross_tenant_session()` first, which raises if a tenant *is* bound, because such a sweep would process one tenant's rows and report success.++The paths that deliberately **do** bind a tenant are `TenantDBSession` in the API, `_set_rls_context` in the agents ledger / hunt store / LLM resolver / Splunk evidence reader, and the per-hunt rebind in the hunt scheduler. Everywhere else the query predicate is the only control, which is why that gate is still the one that matters most.++### Which role each service runs as-**A session that never bound a tenant sees everything.** If `app.current_tenant_id` is not set the policy permits the query. That is deliberate — ingest, fusion, the hunt scheduler and the retention purge all operate across tenants and would otherwise process nothing, silently. The paths that *do* bind a tenant are `TenantDBSession` in the API, `_set_rls_context` in the agents ledger / hunt store / LLM resolver / Splunk evidence reader, and the per-hunt rebind in the hunt scheduler. Everywhere else the query predicate is the only control, which is why that gate is the one that matters.+Every service runs as the scoped runtime role. Nothing needs a cross-tenant credential, because the fail-open arm already gives an unbound session cross-tenant visibility — the distinction is per *session*, not per service, and that is strictly safer: a service that binds a tenant for one request cannot escape it by having been given a privileged role at startup.-Until 2026-09 the agents-service helpers set `app.tenant_id` — a variable no policy reads — so their scoping had never applied. Four policies had the mirror-image bug from the other side, reading `app.tenant_id` or `app.current_tenant`, and two called `current_setting` without `missing_ok` so an unbound session raised `unrecognized configuration parameter` instead of returning rows. All of it was invisible behind the superuser bypass. `test_no_policy_reads_a_session_variable_nothing_sets` keeps that class closed.+| Service | Role | Why |+| --- | --- | --- |+| `api` | runtime | Binds a tenant per request through `TenantDBSession`. Also holds `DATABASE_MIGRATION_URL` — the owner — used only by the migration runner at startup. |+| `ingest` (Go, `DATABASE_DSN`) | runtime | Writes inbox events for every tenant on an unbound session; the fail-open arm admits them. |+| `fusion` | runtime | Promotes alerts across tenants, unbound. |+| `agents` | runtime | Binds a tenant in the ledger, hunt store and LLM resolver; unbound elsewhere. |+| `actions`, `connectors`, `threatintel`, `honeytokens`, `purple-team`, `ueba`, `osquery-tls` | runtime | DML only. `osquery-tls` resolves a node's tenant *from* its enrolment key, so that lookup is unbound by necessity. |+| retention purge / hunt scheduler / tenant deletion (in-process in `api`) | runtime, unbound | Cross-tenant by design, and now assert that no tenant is bound before sweeping. |+| migration runner, `alembic`, `scripts/backup.sh` | owner | DDL, and a dump that has to read and rewrite tables the runtime role cannot. |The `users` table is excluded from RLS deliberately — it would create a chicken-and-egg problem during authentication, and platform-admin user administration is cross-tenant by design. Tenant filtering on `users` is enforced at the application layer through `get_current_user()`.@@ -235,10 +276,12 @@ table.Tenant isolation is enforced at read time, per store, and the predicate is thecontrol that matters. 92 of 95 tenant-scoped tables now carry an RLS policy (it-was 31), but RLS engages only on a session that has run-`SET LOCAL app.current_tenant_id` — and only for a database role that does not-bypass it, which the shipped role does. On an `aisoc_*` table read through a-plain session, a missing predicate is still a leak, not a defence-in-depth gap.+was 31), and since `061_runtime_app_role.sql` the shipped role is one those+policies apply to — so the second layer is real rather than nominal. It still+engages only on a session that has run `SET LOCAL app.current_tenant_id`, and+the workers deliberately do not: on an `aisoc_*` table read through a plain+unbound session, a missing predicate is still a leak, not a defence-in-depth+gap.The dangerous shape is a query that matches on an id and nothing else —`select(Honeytoken).where(Honeytoken.id == token_id)`. It takes no tenant, so@@ -467,6 +510,8 @@ When you move from `pnpm aisoc:demo` to a production deployment, walk through th- [ ] Configure SSO (OIDC or SAML) and disable local password login for human users — leave it on only for break-glass platform admins.- [ ] Require WebAuthn/passkeys for any role that triggers destructive playbook actions or credential changes.- [ ] Confirm `FORCE ROW LEVEL SECURITY` is set on every tenant-partitioned table (verify with `\d+ <tablename>` in `psql`).+- [ ] Confirm `DATABASE_URL` points at the DML-only runtime role and `DATABASE_MIGRATION_URL` at the owner: `python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL" --owner-dsn "$DATABASE_MIGRATION_URL"`. Without this, `FORCE` above is checking a box that the connecting role walks straight past.+- [ ] Set `AISOC_APP_DB_PASSWORD` to a fresh secret before applying the migration chain, so the runtime role is never left on the `changeme` literal `002_rls.sql` created it with.- [ ] Set up an external log sink for the audit log (Splunk, Elastic, Loki) — the in-DB log is the source of truth, but a copy in your SIEM is good practice.- [ ] Configure `AISOC_TRUSTED_PROXIES` to the CIDR(s) of your ingress / load balancer so `actor_ip` is sourced from `X-Forwarded-For` instead of the immediate TCP peer. Leave empty if the API is exposed directly to clients.- [ ] Schedule a periodic `verify_chain()` job against an offsite read replica or a CSV export of the `audit_log` table and alert on any verification failure.diff --git a/docker-compose.yml b/docker-compose.ymlindex 828096411..c68b41217 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -26,6 +26,24 @@# `ports: !reset []` to stop publishing a service on the host entirely.## Rotate the password while you're there.+#+# TWO DATABASE ROLES+# ------------------+# `aisoc` owner / migrations. Superuser, because POSTGRES_USER is what the+# postgres image makes it. Applies the migration chain. NO SERVICE+# CONNECTS AS THIS ROLE.+# `aisoc_app` runtime. SELECT / INSERT / UPDATE / DELETE and nothing else, and+# row-level security applies to it. Every service's DATABASE_URL.+#+# Until this split, every service ran as `aisoc`, and a superuser ignores RLS+# policies even under FORCE ROW LEVEL SECURITY — so all 92 policies in the+# schema filtered nothing. See services/api/migrations/061_runtime_app_role.sql.+#+# Every service below runs as the scoped role. Nothing needs a cross-tenant+# role: the policies are `tenant_id = current_tenant_id() OR current_tenant_id()+# IS NULL`, so ingest, fusion, the retention purge and the schedulers — none of+# which bind a tenant — keep seeing every tenant's rows. The per-service+# reasoning is tabulated in apps/docs/docs/operations/security.md.###############################################################################networks:@@ -51,14 +69,30 @@ services:image: postgres:16-alpinecontainer_name: aisoc-postgresenvironment:+ # The OWNER / migration role. Superuser, because that is what the+ # postgres image makes POSTGRES_USER, and it is what applies the chain.+ # No service connects as this role — see the DATABASE_URL entries below.POSTGRES_DB: aisocPOSTGRES_USER: aisocPOSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-aisoc_dev_secret}+ # The RUNTIME role's credential. `zz_runtime_role_password.sh` applies it+ # on first boot, after 061_runtime_app_role.sql has created the role with+ # DML-only grants. Rotate it the same way you rotate POSTGRES_PASSWORD;+ # the two are deliberately different values because they are different+ # privilege levels.+ AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}ports:- "127.0.0.1:5432:5432"volumes:- postgres_data:/var/lib/postgresql/data- - ./services/api/migrations:/docker-entrypoint-initdb.d:ro+ # The init hooks: 10_ applies the migration chain, 20_ gives the runtime+ # role its password. They live in one directory because Docker cannot+ # create a mountpoint inside a bind mount — binding a single file into a+ # bound `/docker-entrypoint-initdb.d` fails the container at startup.+ # Only runs when the data directory is empty; an upgrade in place is+ # covered by app.scripts.run_migrations instead.+ - ./infra/postgres/initdb:/docker-entrypoint-initdb.d:ro+ - ./services/api/migrations:/aisoc/migrations:ronetworks:- aisochealthcheck:@@ -253,7 +287,16 @@ services:ports:- "127.0.0.1:8000:8000"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ # Two roles, on purpose. DATABASE_URL is the runtime role: DML only, and+ # row-level security applies to it. DATABASE_MIGRATION_URL is the owner,+ # used by `app.scripts.run_migrations` for DDL and nothing else. Running+ # the service as the owner is what made all 92 RLS policies inert, since+ # a superuser ignores them even under FORCE ROW LEVEL SECURITY.+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ # Read by the migration runner to (re)apply the runtime role's password+ # on an existing data volume, where the postgres init hook never fires.+ AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}REDIS_URL: redis://:redis_dev_secret@redis:6379/0KAFKA_BOOTSTRAP_SERVERS: kafka:29092CLICKHOUSE_URL: http://aisoc:clickhouse_dev_secret@clickhouse:8123/aisoc@@ -321,7 +364,7 @@ services:# from your SIEM" path was unreachable on every local and CI stack.# This is a pgx DSN and is deliberately distinct from the SQLAlchemy# DATABASE_URL the Python services use.- DATABASE_DSN: postgres://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc?sslmode=disable+ DATABASE_DSN: postgres://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc?sslmode=disableLOG_LEVEL: infoJWT_SECRET: dev_secret_key_change_in_productionATTCK_DATA_PATH: /app/data/enterprise-attack.json@@ -386,7 +429,7 @@ services:environment:KAFKA_BOOTSTRAP_SERVERS: kafka:29092REDIS_URL: redis://:redis_dev_secret@redis:6379/3- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc# The ClickHouse event lake is a `full`-profile capability: it backs# /lake/sql and the hunt surface, not alerting. CORE runs without it and# the writer disables itself.@@ -423,7 +466,7 @@ services:ports:- "127.0.0.1:8001:8084"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/4CORE_API_URL: http://api:8000# Phase B1 — auto-triage every fused alert off the Kafka stream (copilot:@@ -512,7 +555,7 @@ services:profiles:- osqueryenvironment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocAISOC_OSQUERY_TLS_ENROLL_SECRET: ${AISOC_OSQUERY_TLS_ENROLL_SECRET:-change-me-in-production}# The ingest service is registered as `ingest-worker` in this compose# file; the previous `http://ingest:8080` would not resolve via DNS.@@ -543,7 +586,7 @@ services:environment:KAFKA_BOOTSTRAP_SERVERS: kafka:29092REDIS_URL: redis://:redis_dev_secret@redis:6379/5- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocCORE_API_URL: http://api:8000# Must match AISOC_ACTIONS_SERVICE_TOKEN on the api and slack-bot# services. Unset in dev, where AISOC_DEV_MODE relaxes the check;@@ -577,7 +620,7 @@ services:environment:KAFKA_BOOTSTRAP_SERVERS: kafka:29092REDIS_URL: redis://:redis_dev_secret@redis:6379/6- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocCORE_API_URL: http://api:8000CROWDSTRIKE_CLIENT_ID: ${CROWDSTRIKE_CLIENT_ID:-}CROWDSTRIKE_CLIENT_SECRET: ${CROWDSTRIKE_CLIENT_SECRET:-}@@ -652,7 +695,7 @@ services:ports:- "127.0.0.1:8007:8004"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/8KAFKA_BOOTSTRAP_SERVERS: kafka:29092CLICKHOUSE_URL: http://aisoc:clickhouse_dev_secret@clickhouse:8123/aisoc@@ -684,7 +727,7 @@ services:ports:- "127.0.0.1:8008:8005"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/9KAFKA_BOOTSTRAP_SERVERS: kafka:29092CORE_API_URL: http://api:8000@@ -713,7 +756,7 @@ services:ports:- "127.0.0.1:8006:8006"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/10CORE_API_URL: http://api:8000ATTCK_DATA_PATH: /app/data/enterprise-attack.jsondiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex fedcccccb..9d4e3becb 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -26,7 +26,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| MCP server exposes 13 tools | README L179 | `ci.yml :: mcp` | GATED | - || Plugin SDK Python/TS/Go | README L79, L193 | `ci.yml :: sdk-*` | PARTIAL (build/test gated; OpenAPI breaking-change now gated via `openapi-breaking.yml`, so a spec change that would break the generated SDKs is caught; per-language generated-client contract-drift is 11b) | Phase 11b || Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate |-| Cross-tenant isolation (Postgres) | (implied by multi-tenant) | `cross-tenant-rbac.yml` (nightly, 3 endpoints) + `ci.yml` + `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py` — the live-DB replay this row's gap named. Against the real chain on `postgres:16` it seeds an A row and a B row into **every** RLS-covered tenant table, asserts both are visible unscoped before asserting either absence, then binds the session to A and asserts B's row is unreachable on each one. Reads run as a role created with `NOSUPERUSER NOBYPASSRLS`, because the role the services ship with bypasses RLS outright — a fact the suite asserts rather than footnotes, so a green run here can never be read as "isolation is on in production". Also fails when a tenant-scoped table has no policy, when a policy exists without `FORCE`, when an exclusion no longer describes an unprotected table, and when any policy reads a session variable nothing sets) | GATED | reads as the probe role, not as the deployed role; the deployed role's bypass is itself asserted, and `apps/docs/docs/operations/security.md` carries the grant that turns the policies on |+| Cross-tenant isolation (Postgres) | (implied by multi-tenant) | `cross-tenant-rbac.yml` (nightly, 3 endpoints) + `ci.yml` + `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py` — the live-DB replay this row's gap named. Against the real chain on `postgres:16` it seeds an A row and a B row into **every** RLS-covered tenant table, asserts both are visible unscoped before asserting either absence, then binds the session to A and asserts B's row is unreachable on each one. Reads run as a role created with `NOSUPERUSER NOBYPASSRLS`, because the role the services ship with bypasses RLS outright — a fact the suite asserts rather than footnotes, so a green run here can never be read as "isolation is on in production". Also fails when a tenant-scoped table has no policy, when a policy exists without `FORCE`, when an exclusion no longer describes an unprotected table, and when any policy reads a session variable nothing sets) | GATED | reads as `DATABASE_URL`, which is the role the deployment ships: `061_runtime_app_role.sql` moved the services onto a DML-only `aisoc_app` and the suite's purpose-built probe role is gone, so the replay covers what runs. The gap this row carried — "reads as the probe role, not as the deployed role" — is closed. `test_the_owner_still_bypasses_which_is_why_they_are_two_roles` asserts the two roles have not silently merged back || Every authenticated route reads only the caller's own tenant | (implied by multi-tenant) | `ci.yml` api job (`test_tenant_scope_and_auth_holes.py` — the identity-timeline alert query binds the caller's tenant and keeps the caller-supplied search term a parameter; the case-timeline linked-alert hydration binds a tenant; and a directory-wide sweep over `app/api/v1/endpoints/*.py` fails if **any** raw `FROM aisoc_alerts` read omits `tenant_id`, so a new endpoint cannot reintroduce the shape) | GATED | the sweep covers raw SQL against the alerts tables; ORM reads rely on the existing per-endpoint isolation tests || Every playbook route requires an authenticated, permitted caller | (implied by RBAC) | `ci.yml` api job (`test_tenant_scope_and_auth_holes.py` — each of the eight route functions takes an authenticated principal, the decorated-route count is asserted against the expected permission map so a new ungated route fails, execute stays distinct from write, and every permission named is one a role actually grants) | GATED | - || An MSSP parent holds only tenants that invited it | operations/security.md (MSSP parent/child links) | `ci.yml` api job (`test_mssp_cross_tenant_authz.py` — the four child-scoped write routes refuse a tenant that is not the caller's child and persist nothing; unknown and unowned are indistinguishable so the routes cannot enumerate tenant UUIDs; onboarding refuses without an invite, refuses an invite addressed to another parent, consumes the invite on success, and refuses self-adoption) | GATED | the guard is unit-level against the route functions; the nightly live-DB `cross-tenant-rbac.yml` sweep does not yet cover the MSSP routes |@@ -129,7 +129,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No route lets its caller name the tenant it reads; a tenant parameter is intersected with the caller's scope | (implied by multi-tenant); `tests/isolation/README.md` | `isolation.yml :: route-scope` (`scripts/check_route_tenant_scope.py` — an AST pass over all routes under `services/`, failing in **both** directions: a route taking a tenant identifier with no auth dependency, and a route accepting one without passing it through a scope intersection. Request-body models are read too, since a `tenant_id` on a POST body is the same hole as a query parameter. `--self-test` injects a violation of each kind, asserts two clean controls pass, and strips the verifier the one conditional exemption names to prove a stale exemption is dropped; the root comes from `git rev-parse` and the scan prints how many routes across how many files it opened) + `tests/isolation/test_route_tenant_scope.py` (the vendored HS256 verifier rejects `alg: none`, a refresh token, a wrong key and an expired token; an empty scope refuses rather than widening; and a two-tenant replay seeds A and B through the real `EntityRiskEngine`, asserts both genuinely hold rows, then asserts an anonymous caller, an undeclared service token and a console session for B are each refused A's entity-risk queue) + `sync_vendored_tenant_scope.py --check` (six copies byte-identical but for `SERVICE_NAME`) | GATED | `services/mesh` is exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it) and three MSSP routes that *define* a scope rather than read within one are exempt with the constraint that stands in for the intersection named per row || Every route authenticates, or is public for a reason that is itself checked | (implied by multi-tenant + RBAC); `apps/docs/docs/operations/security.md` | `isolation.yml :: route-scope` (`scripts/check_route_auth.py` — default-deny over all 601 routes under `services/`, reusing the same AST collector as the tenant-scope gate so the two cannot drift. A route without an auth dependency must appear in one of three tables, each carrying its reason: a probe module, a named public route, or an **in-band credential** route whose entry names the verifier and lapses the moment the handler stops calling it. Fails in both directions — an unexplained route fails, and an exemption that no longer matches an unauthenticated route fails as stale, so the tables shrink as routes are secured. `--self-test` injects an unauthenticated mutating route, asserts router-level and module-local `Annotated[..., Depends(...)]` auth are both recognised, and strips a live in-band entry to prove a stale one is dropped) + `tests/isolation/test_route_auth_default_deny.py` (the real agents routers over ASGI: an anonymous caller is refused on all seven previously-open routes including playbook create/execute/delete, a valid console session still gets a non-empty response, a service token declaring no tenant is 403, and forged / expired / `alg: none` / refresh tokens are each refused) | GATED | `services/mesh` stays exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it), recorded as a service-level entry whose reason the inventory prints || Every query on a tenant-scoped table filters on a tenant, however the row was addressed | (implied by multi-tenant) | `isolation.yml :: route-scope` (`scripts/check_tenant_query_predicates.py` — the predicate question the parameter gate structurally cannot ask, since a route matching on an id takes no tenant. Both the tenant-scoped ORM models and the tenant-scoped tables are derived from the tree (the model's `tenant_id` column, the migrations' DDL) rather than listed, so a new migration cannot slip past. Scoping is recognised structurally through five shapes — inline `.where()`, a `filters` list, a variable binding, a later `q = q.where(...)`, a join, and a helper that takes the statement and returns it filtered — plus a predicate on the authenticated principal's own identity, a key an **enforcing** guard already validated against the caller's tenant, and an RLS context bound on the connection where the table carries a policy. "Enforcing" is decided structurally: a guard whose result is tested in a branch that only logs demonstrably continues on failure and earns no credit, a guard whose callee raises does, and a callee this module cannot resolve is refused rather than guessed — the previous rule guessed yes, so a fail-soft guard written inline was indistinguishable from one that 404s. The session is excluded from the validated set by what it is used as (the receiver of a call), since `db` reaches every raw statement's name set and was crediting queries keyed on something else entirely. Raw SQL is parsed too, with docstrings excluded so prose about a query is not read as one. Undecidable cases sit on a **shrink-only ratchet**: each entry carries a reason, an entry whose statement is now scoped fails as stale, and `MAX_RATCHET` is asserted against the table's length so growth needs a number raised in the diff) + `tests/isolation/test_route_auth_default_deny.py` (two tenants seeded against a real database, both asserted to hold rows before either absence is asserted, then tenant B naming tenant A's `query_id` gets nothing back) | GATED | 32 ratcheted exceptions remain, each with its reason — credential lookups that *establish* a tenant, deliberately cross-tenant MSSP portfolio reads, background workers that have no caller, and two SQL-fragment builders whose only caller appends the predicate. The two ledger writes that were ratcheted as "scoped by an RLS context" are gone: the rule now recognises that shape structurally, and re-checking it found the mechanism did not work — the agents service was setting `app.tenant_id`, which no policy reads |-| Every tenant-scoped table carries an RLS policy, and a policy that cannot engage says so rather than reading as protection | `apps/docs/docs/operations/security.md` (multi-tenant isolation) | `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py::test_every_tenant_table_is_protected_or_named` — both directions: a tenant-scoped table with no policy fails unless it is one of the named exclusions, and an exclusion that no longer describes an unprotected table fails as stale; `FORCE` is required on every one, since without it the table owner, which is the application, walks past the policy. `test_no_policy_reads_a_session_variable_nothing_sets` closes the bug class that made seven existing policies inert — four keyed on a GUC no code path sets, two raising `unrecognized configuration parameter` on an unbound session. `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` measures the shipped role's bypass so the coverage figure is never read as a live guarantee) + `check_tenant_query_predicates.py --inventory` (coverage derived from the migration text of all five schema chains, not one) | GATED | 92 of 95; the three left are named, not rounded away — `users` is excluded so authentication can resolve a principal before a tenant exists, and `case_tasks` / `case_timeline` are ORM models no migration creates, asserted still absent. The policies are inert until the deployment connects as a role without BYPASSRLS; the grant is documented and the bypass is asserted rather than assumed |+| Every tenant-scoped table carries an RLS policy, and a policy that cannot engage says so rather than reading as protection | `apps/docs/docs/operations/security.md` (multi-tenant isolation) | `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py::test_every_tenant_table_is_protected_or_named` — both directions: a tenant-scoped table with no policy fails unless it is one of the named exclusions, and an exclusion that no longer describes an unprotected table fails as stale; `FORCE` is required on every one, since without it the table owner, which is the application, walks past the policy. `test_no_policy_reads_a_session_variable_nothing_sets` closes the bug class that made seven existing policies inert — four keyed on a GUC no code path sets, two raising `unrecognized configuration parameter` on an unbound session. `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` measures the shipped role's bypass so the coverage figure is never read as a live guarantee) + `check_tenant_query_predicates.py --inventory` (coverage derived from the migration text of all five schema chains, not one) | GATED | 92 of 95; the three left are named, not rounded away — `users` is excluded so authentication can resolve a principal before a tenant exists, and `case_tasks` / `case_timeline` are ORM models no migration creates, asserted still absent (both re-confirmed against a live `postgres:16` with the full chain applied: `users` is the only tenant-scoped table without a policy, and neither ORM table has a `CREATE TABLE` anywhere in the chain). The policies are no longer inert: `061_runtime_app_role.sql` moved every deployment surface onto a role with neither attribute, and the row below gates it |+| The role the services connect as is subject to row-level security, and the cross-tenant workers still see every tenant | `apps/docs/docs/operations/security.md` (the role the services connect as) | `isolation.yml` (`scripts/check_runtime_db_role.py` — fails when a runtime DSN connects as the role that surface provisions as the database superuser. Structural: the privileged role is read out of `POSTGRES_USER` / `db_username` in the tree, not matched against a name, so renaming it changes nothing and a fourteenth service with a copied DSN still fails. Both directions — a *migration* DSN that is **not** the owner fails too, since the runtime role holds no DDL and that deploy dies on the first `CREATE TABLE`; a surface containing a Postgres URL that the parser could not read fails as a blind spot rather than passing; and an `aisoc-db-role: owner` exemption left behind after its DSN moved fails as stale. Thirteen classifier fixtures run *before* every scan, and a run that matched no surface exits non-zero) + `integration.yml :: migrations` (`--dsn`, which reads `pg_roles` and `pg_class` on a live database and catches `rolsuper`, `rolbypassrls`, ownership of a covered object, a view without `security_invoker`, and a role still accepting the password `002_rls.sql` shipped) | GATED | The parser's own blind spot was found by enumerating what it **credited**: `infra/terraform/main.tf` declares `db_username = var.db_username` and interpolates `${var.db_username}`, and the naive compare read those as two roles — so the one surface handing the RDS master user to every service was recorded as compliant. A managed Postgres still needs the operator to create the role's login; the compose stacks and CI do it themselves |+| A cross-tenant worker that stops seeing data says so instead of reporting success | `apps/docs/docs/operations/security.md` (a session that never bound a tenant) | `isolation.yml` (`scripts/check_rls_policy_shape.py` — every surviving policy in all five schema chains must carry the `OR current_tenant_id() IS NULL` arm, because ingest, fusion, the retention purge and the schedulers read on a session that binds no tenant and would otherwise see zero rows and report success. Replays the chain in order so a definition a later migration repaired is not reported, which is what lets the seven broken policies stay in the tree as history instead of being silenced by an ignore list. Both directions: a policy reading a GUC nothing sets, or omitting `missing_ok`, fails from the other side; a schema file that enables RLS but yields no policy fails as a blind spot; `ENABLE` without `FORCE`, and `ENABLE` with no policy, both fail) + `services/api/tests/test_retention_worker.py` (the sweep refuses, and issues no delete, on a session that has a tenant bound) | GATED | Two blind spots in this parser were found by counting what it credited rather than what it flagged: the four alembic chains build SQL by implicit string concatenation with no `;` so none of their twelve tables parsed, and the first fix then read each revision's `downgrade()` too, so create and drop cancelled and the policy count did not move. The static set is a deliberate **superset** of the live one — two policies in `002` sit behind an `IF EXISTS` a text replay cannot evaluate — which is the safe direction || Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list || The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | the `governed` execution class is compared against `engine.RESPONSE_STEP_TYPES` in both directions, and the published `StepType` union in `packages/types` against the engine's, because that file had drifted into a fourth 28-member vocabulary nothing imported. `approval` is the one remaining unimplemented type and the schema says so || A step a playbook engine cannot run never reports that it ran | concepts/playbooks.md (error handling) | `ci.yml` agents job (`test_playbook_engine_correctness.py::TestUnimplementedStepTypesFailClosed` — an `approval` gate the engine cannot honour halts the run instead of passing it, every handler-less `StepType` is asserted to fail rather than succeed, a missing handler is not retried, an explicit `on_failure: continue` is still honoured, and a dry run reports `would_fail` rather than a bare `dry_run: true`) | GATED | - |@@ -145,7 +147,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 126+- GATED: 128- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/infra/compose/docker-compose.demo.yml b/infra/compose/docker-compose.demo.ymlindex 46194c51f..211dbf3e4 100644--- a/infra/compose/docker-compose.demo.yml+++ b/infra/compose/docker-compose.demo.yml@@ -77,9 +77,13 @@ services:image: postgres:16-alpinecontainer_name: aisoc-demo-postgresenvironment:+ # Owner / migration role. No service connects as this one.POSTGRES_DB: aisocPOSTGRES_USER: aisocPOSTGRES_PASSWORD: aisoc_dev_secret+ # Runtime role credential, applied by the init hook below once+ # 061_runtime_app_role.sql has created the role and its grants.+ AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}# Host port is overridable so `pnpm aisoc:demo` can fall forward to the# next free port when a local Postgres is already bound to 5432. The# container port stays at 5432; only the publish side changes.@@ -87,6 +91,13 @@ services:- "127.0.0.1:${AISOC_POSTGRES_PORT:-5432}:5432"volumes:- postgres_demo_data:/var/lib/postgresql/data+ # The demo used to leave the whole schema to the API's startup migration+ # run. It now applies the chain at init for the same reason the root+ # stack does: the runtime role's grants come from 061, and they have to+ # exist before the first service authenticates. `depends_on:+ # service_healthy` then makes the ordering a guarantee rather than a race.+ - ../postgres/initdb:/docker-entrypoint-initdb.d:ro+ - ../../services/api/migrations:/aisoc/migrations:ronetworks:- aisoc-demohealthcheck:@@ -178,7 +189,10 @@ services:ports:- "127.0.0.1:${AISOC_API_PORT:-8000}:8000"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ # DDL runs as the owner; the service itself does not hold it.+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc+ AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}REDIS_URL: redis://:redis_dev_secret@redis:6379/0KAFKA_BOOTSTRAP_SERVERS: kafka:29092SECRET_KEY: dev_secret_key_change_in_production@@ -222,7 +236,7 @@ services:ports:- "127.0.0.1:${AISOC_AGENTS_PORT:-8001}:8084"environment:- DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/4CORE_API_URL: http://api:8000OPENAI_API_KEY: ${OPENAI_API_KEY:-}@@ -285,7 +299,7 @@ services:api:condition: service_healthyenvironment:- DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc+ DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/0SECRET_KEY: dev_secret_key_change_in_productionENV: developmentdiff --git a/infra/helm/aisoc/values.yaml b/infra/helm/aisoc/values.yamlindex b49ec40d8..8411ecec8 100644--- a/infra/helm/aisoc/values.yaml+++ b/infra/helm/aisoc/values.yaml@@ -412,9 +412,39 @@ backup:memory: 2Gi# ─── Bundled Infrastructure (disable in production; use managed services) ─────+#+# TWO DATABASE ROLES, AND THE CHART CANNOT CREATE THE SECOND ONE FOR YOU+# ----------------------------------------------------------------------+# `auth.username` below is the OWNER: it owns the schema and applies the+# migration chain. No service should connect as it. A superuser — which is+# what the bundled chart and most managed services make the master user —+# ignores every row-level-security policy in this schema, even under+# FORCE ROW LEVEL SECURITY, so running the services as the owner leaves all 92+# policies filtering nothing.+#+# Services connect as `aisoc_app`, a DML-only role that+# `services/api/migrations/061_runtime_app_role.sql` creates and constrains to+# NOSUPERUSER NOBYPASSRLS. The migration deliberately sets no password, so the+# deployment supplies one. This chart ships no Secret template — it reads an+# existing `<release>-secrets` — which means **this is an operator step**:+#+# 1. Apply the migration chain as the owner, with AISOC_APP_DB_PASSWORD set+# in the job's environment. That run gives `aisoc_app` its login.+# 2. Put the runtime DSN in `<release>-secrets` under `database-url`+# (and `honeytoken-database-url` / `purple-team-database-url`), pointing+# at `aisoc_app`.+# 3. Put the owner DSN under `database-migration-url`, used by the migration+# job and by nothing else.+#+# Verify with `python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL"`:+# rolsuper and rolbypassrls must both read false and the role must own nothing.+# Skip step 1 and the services cannot authenticate — a loud failure. Skip step 2+# and they authenticate as the owner, which is the silent one.postgresql:enabled: falseauth:+ # The owner / migration role. See the note above before pointing a+ # service's DATABASE_URL at this.database: aisocusername: aisocexistingSecret: aisoc-postgres-secretdiff --git a/infra/postgres/initdb/10_apply_migrations.sh b/infra/postgres/initdb/10_apply_migrations.shnew file mode 100755index 000000000..b17b19061--- /dev/null+++ b/infra/postgres/initdb/10_apply_migrations.sh@@ -0,0 +1,52 @@+#!/usr/bin/env bash+# Apply the API migration chain on a freshly initialised database.+#+# The compose stacks used to bind `services/api/migrations` straight onto+# `/docker-entrypoint-initdb.d`, letting the postgres entrypoint run the `.sql`+# files itself. That stopped being possible once a second file had to run in+# the same directory: Docker cannot create a mountpoint *inside* a bind mount,+# so `- ./a/b.sh:/docker-entrypoint-initdb.d/b.sh` fails the container at+# startup with+#+# create mountpoint for /docker-entrypoint-initdb.d/… : read-only file system+#+# — and it fails the same way whether or not the directory mount is `:ro`.+# Found by booting it, not by reading it.+#+# So the init directory is now `infra/postgres/initdb/`, holding this script+# and the one that sets the runtime role's password, and the migrations are+# mounted read-only alongside at AISOC_MIGRATIONS_DIR. Numbered filenames keep+# the order explicit rather than leaving it to a collation accident.+#+# Same semantics the entrypoint gave: files in filename order, `ON_ERROR_STOP`+# so a broken migration fails the boot instead of leaving a half-built schema+# that looks healthy.++set -euo pipefail++MIGRATIONS_DIR="${AISOC_MIGRATIONS_DIR:-/aisoc/migrations}"++if [ ! -d "${MIGRATIONS_DIR}" ]; then+ echo "[migrations] ${MIGRATIONS_DIR} is not mounted — no schema will be created." >&2+ echo "[migrations] Mount ./services/api/migrations there, or apply the chain from the API service." >&2+ exit 0+fi++shopt -s nullglob+files=("${MIGRATIONS_DIR}"/*.sql)+shopt -u nullglob++if [ ${#files[@]} -eq 0 ]; then+ echo "[migrations] ${MIGRATIONS_DIR} contains no .sql files — nothing applied." >&2+ exit 0+fi++echo "[migrations] applying ${#files[@]} files from ${MIGRATIONS_DIR}"+for f in "${files[@]}"; do+ echo "[migrations] $(basename "${f}")"+ psql -v ON_ERROR_STOP=1 --no-psqlrc \+ --username "${POSTGRES_USER}" \+ --dbname "${POSTGRES_DB}" \+ --quiet -f "${f}"+done+echo "[migrations] chain applied"diff --git a/infra/postgres/initdb/20_runtime_role_password.sh b/infra/postgres/initdb/20_runtime_role_password.shnew file mode 100755index 000000000..9def5ba34--- /dev/null+++ b/infra/postgres/initdb/20_runtime_role_password.sh@@ -0,0 +1,65 @@+#!/usr/bin/env bash+# Give the runtime role a login credential on a freshly initialised database.+#+# `services/api/migrations/061_runtime_app_role.sql` creates `aisoc_app` with+# DML-only grants and refuses to leave it able to bypass row-level security.+# What it deliberately does not do is set a password: a migration in a public+# repository must not carry one, and it must not clobber a credential an+# operator already configured.+#+# So the credential is applied here, from the environment, at the one moment+# where doing it is unambiguous — the postgres image's own first-boot init,+# which runs before the container reports healthy and therefore before any+# service's `depends_on: service_healthy` lets it try to connect.+#+# Numbered `20_` so it runs after `10_apply_migrations.sh`, which is what+# creates the role and its grants. Setting a password on a role that does not+# exist yet would create one with no privileges at all.+#+# Two things this cannot cover, both documented in+# apps/docs/docs/operations/security.md:+#+# * An *existing* data volume. `/docker-entrypoint-initdb.d` runs only when+# the data directory is empty, so an upgrade in place never reaches this+# script. `app.scripts.run_migrations` applies the same environment+# variable on every run, which is what closes that path.+# * A managed Postgres (RDS, Cloud SQL, a Helm-installed chart). There is no+# init hook to attach to; the deployment provisions the role itself.++set -euo pipefail++PASSWORD="${AISOC_APP_DB_PASSWORD:-}"++if [ -z "${PASSWORD}" ]; then+ echo "[runtime-role] AISOC_APP_DB_PASSWORD is empty — leaving aisoc_app without a login." >&2+ echo "[runtime-role] Services pointed at aisoc_app will fail to authenticate until one is set." >&2+ exit 0+fi++# The password never appears in the statement text. psql's `:'name'` quotes the+# variable for the `set_config` call — and only there, because psql does not+# substitute inside a dollar-quoted block — then `quote_literal` re-quotes it+# for the ALTER, which is a utility statement and takes no parameters. A+# password containing a quote therefore cannot terminate a literal.+psql -v ON_ERROR_STOP=1 \+ --username "${POSTGRES_USER}" \+ --dbname "${POSTGRES_DB}" \+ --set=app_password="${PASSWORD}" <<'SQL'+SELECT set_config('aisoc.app_password', :'app_password', false);++DO $$+DECLARE+ pw text := current_setting('aisoc.app_password');+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ EXECUTE 'CREATE ROLE aisoc_app LOGIN PASSWORD ' || quote_literal(pw);+ ELSE+ EXECUTE 'ALTER ROLE aisoc_app WITH LOGIN PASSWORD ' || quote_literal(pw);+ END IF;+END+$$;++SELECT set_config('aisoc.app_password', '', false);+SQL++echo "[runtime-role] aisoc_app can now log in; row-level security applies to it."diff --git a/infra/terraform/main.tf b/infra/terraform/main.tfindex 627890879..1e7b9ca4a 100644--- a/infra/terraform/main.tf+++ b/infra/terraform/main.tf@@ -121,6 +121,23 @@ module "rds" {allowed_security_groups = [module.eks.node_security_group_id]}+# ─── The runtime database role ────────────────────────────────────────────────+#+# RDS creates one master user, and handing it to every service is what left the+# schema's 92 row-level-security policies filtering nothing: a superuser+# ignores them even under FORCE ROW LEVEL SECURITY. Services connect as the+# DML-only role that `services/api/migrations/061_runtime_app_role.sql` creates;+# the master user is kept for migrations.+#+# The password is generated here rather than written down anywhere. Feed it to+# the job that applies the migration chain as AISOC_APP_DB_PASSWORD — that run+# is what gives the role a login — and read it back with+# `terraform output -raw db_app_password`.+resource "random_password" "db_app" {+ length = 32+ special = false+}+module "elasticache" {source = "./modules/elasticache"@@ -157,8 +174,9 @@ module "osquery_tls" {replicas = var.osquery_tls_replicas- enroll_secret = var.osquery_tls_enroll_secret- database_url = "postgresql+asyncpg://${var.db_username}:${module.rds.db_password}@${module.rds.endpoint}/aisoc"+ enroll_secret = var.osquery_tls_enroll_secret+ # The runtime role, not the RDS master user. See random_password.db_app above.+ database_url = "postgresql+asyncpg://${var.db_app_username}:${random_password.db_app.result}@${module.rds.endpoint}/aisoc"ingest_base_url = "http://aisoc-ingest.aisoc.svc.cluster.local:8080"autoscaling = {@@ -205,6 +223,19 @@ output "vpc_id" {value = module.vpc.vpc_id}+output "db_app_password" {+ description = "Password for the DML-only runtime role. Supply as AISOC_APP_DB_PASSWORD to the migration job."+ value = random_password.db_app.result+ sensitive = true+}++output "database_migration_url" {+ # aisoc-db-role: owner — the migration chain needs DDL; the runtime role has none+ description = "DSN for DATABASE_MIGRATION_URL. The RDS master user, used for DDL only."+ value = "postgresql+asyncpg://${var.db_username}:${module.rds.db_password}@${module.rds.endpoint}/aisoc"+ sensitive = true+}+output "osquery_tls_internal_url" {description = "In-cluster URL for the osquery-tls TLS endpoint"value = module.osquery_tls.internal_urldiff --git a/infra/terraform/variables.tf b/infra/terraform/variables.tfindex c4e7dab00..9b5f206d3 100644--- a/infra/terraform/variables.tf+++ b/infra/terraform/variables.tf@@ -55,12 +55,23 @@ variable "rds_instance_class" {}variable "db_username" {- description = "PostgreSQL master username"+ description = "PostgreSQL master username. Owns the schema and applies migrations; no service connects as it."type = stringdefault = "aisoc_admin"sensitive = true}+variable "db_app_username" {+ description = <<-EOT+ The DML-only role every service connects as. Created by+ services/api/migrations/061_runtime_app_role.sql, which also constrains it to+ NOSUPERUSER NOBYPASSRLS so the row-level-security policies actually apply.+ Change this only if you also change the migration.+ EOT+ type = string+ default = "aisoc_app"+}+variable "redis_node_type" {description = "ElastiCache Redis node type"type = stringdiff --git a/scripts/check_rls_policy_shape.py b/scripts/check_rls_policy_shape.pynew file mode 100644index 000000000..c18d73c3f--- /dev/null+++ b/scripts/check_rls_policy_shape.py@@ -0,0 +1,527 @@+#!/usr/bin/env python3+"""Fail if an RLS policy would make a cross-tenant worker silently see nothing.++The arm this is about+---------------------+Every policy in this schema is written::++ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)++The second clause is not decoration. Ingest, fusion, the retention purge, the+hunt scheduler's sweep and tenant deletion all read across every tenant on a+connection that never binds one, and the ``IS NULL`` arm is what lets them.+Drop it from one policy and that table quietly returns zero rows to those+workers — no error, no log line, just a purge that purges nothing and a+scheduler that fires nothing.++That mattered less while the services connected as a superuser, because a+superuser ignores policies entirely. ``061_runtime_app_role.sql`` moves them+onto a role the policies apply to, which makes the arm load-bearing in+production rather than in theory. **A worker that silently stops seeing data is+a worse failure than the bypass that change closes**, so the arm is now a gate.++The second bug class, kept closed+---------------------------------+``060_rls_coverage.sql`` repaired seven policies that could never engage: five+read ``app.tenant_id`` or ``app.current_tenant`` — GUCs no code path sets, so+they returned zero rows forever — and two called ``current_setting`` without+``missing_ok``, so an unbound session raised ``unrecognized configuration+parameter`` instead of returning anything. Both are invisible behind a+superuser. ``tests/isolation/test_postgres_rls.py`` catches them in a live+database; this catches them in the four schema chains that live database never+sees, because CI applies only the API chain.++Supersession is followed, not ignored+-------------------------------------+The broken definitions are still in the tree — 005, 007, 024 and 049 contain+them, and 060 drops and recreates each one. A scanner that read every+``CREATE POLICY`` in the repository would report seven findings that were+already fixed, and would then be silenced with an ignore list that outlives+its reason. So the chain is replayed in order: ``DROP POLICY`` removes an+entry, ``CREATE POLICY`` adds one, and only the surviving set is judged.++Both directions+---------------+* forward — a live policy with no fail-open arm fails.+* reverse — a live policy reading a GUC nothing sets, or omitting+ ``missing_ok``, fails. Same class from the other side: one returns nothing+ to a worker, the other returns nothing to a tenant.+* reverse — a schema file that enables row-level security but from which no+ policy could be parsed fails as a **blind spot**. The failure mode of a+ scanner is silence.+* reverse — a table with a policy but no ``FORCE`` fails: without it the owner+ walks past, and the owner is the role that runs migrations.++Empty input is a failure. A run that parsed no schema file has verified+nothing, and a probe recently found five wired gates reporting OK against an+empty repository.++Checked against a real database+-------------------------------+The surviving set this produces for the API chain was compared against+``pg_policies`` on a ``postgres:16`` with that chain applied: 84 here, 82+there, and the difference is fully accounted for. ``002_rls.sql`` guards two+policies behind ``IF EXISTS (SELECT 1 FROM information_schema.tables …)``, and+neither table existed when 002 ran — ``playbooks`` is never created by any+migration, and ``audit_log`` arrives in 004 and gets its policy there under a+different name. A text replay cannot evaluate a runtime condition, so the+static set is a **superset** of the live one. That is the safe direction: it+judges the shape of a policy that may not exist, rather than missing one that+does. ``tests/isolation/test_postgres_rls.py`` is what checks the live set.+"""++from __future__ import annotations++import argparse+import ast+import re+import sys+from dataclasses import dataclass, field+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_main # noqa: E402++#: Where the five schema chains live. Same three globs the predicate gate uses,+#: derived from the tree rather than listed, so a sixth chain is picked up by+#: existing somewhere conventional rather than by being added here.+SCHEMA_GLOBS: tuple[str, ...] = (+ "services/*/migrations/*.sql",+ "services/*/alembic/versions/*.py",+ "services/*/app/db/versions/*.py",+)++#: The only session variable any policy may read. ``002_rls.sql`` defines+#: ``current_tenant_id()`` over it and every binding path in the tree sets it.+CANONICAL_GUC = "app.current_tenant_id"++#: ``CREATE POLICY name ON table ... ;`` — the body runs to the statement+#: terminator. Quotes may be doubled because four of these are built inside an+#: ``EXECUTE format(...)``.+_CREATE_RE = re.compile(r"CREATE\s+POLICY\s+\"?(?P<name>\w+)\"?\s+ON\s+\"?(?P<table>[\w.]+)\"?(?P<body>.*?);", re.S | re.I)+_DROP_RE = re.compile(r"DROP\s+POLICY\s+(?:IF\s+EXISTS\s+)?\"?(?P<name>\w+)\"?\s+ON\s+\"?(?P<table>[\w.]+)\"?", re.I)+_ENABLE_RE = re.compile(r"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?\"?(?P<table>[\w.]+)\"?\s+ENABLE\s+ROW\s+LEVEL\s+SECURITY", re.I)+_FORCE_RE = re.compile(r"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?\"?(?P<table>[\w.]+)\"?\s+FORCE\s+ROW\s+LEVEL\s+SECURITY", re.I)+_NOFORCE_RE = re.compile(r"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?\"?(?P<table>[\w.]+)\"?\s+NO\s+FORCE\s+ROW\s+LEVEL\s+SECURITY", re.I)+_DISABLE_RE = re.compile(r"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?\"?(?P<table>[\w.]+)\"?\s+DISABLE\s+ROW\s+LEVEL\s+SECURITY", re.I)++#: ``current_setting('name'[, true])``, tolerating the doubled quotes that+#: appear inside a dollar-quoted ``EXECUTE format(...)``.+_SETTING_RE = re.compile(r"current_setting\(\s*'{1,2}(?P<name>[^']+)'{1,2}\s*(?P<rest>[^)]*)\)", re.I)++#: The helper 002_rls.sql defines. It reads the canonical GUC and returns NULL+#: when unset, so a policy calling it inherits both properties.+_HELPER = "current_tenant_id()"+++@dataclass+class Policy:+ table: str+ name: str+ body: str+ source: str+++@dataclass+class Schema:+ policies: dict[tuple[str, str], Policy] = field(default_factory=dict)+ forced: set[str] = field(default_factory=set)+ rls_tables: set[str] = field(default_factory=set)+ files: list[str] = field(default_factory=list)+ blind_spots: list[str] = field(default_factory=list)+++def _bare(table: str) -> str:+ return table.split(".")[-1].strip('"')+++def strip_comments(sql: str) -> str:+ """Drop ``--`` and ``/* */`` comments, leaving string literals alone.++ Every migration in this chain documents itself, and 060 in particular+ spells the canonical predicate out in prose and names the policies it+ replaces. Parsed as SQL, that prose becomes statements: a fixture with a+ commented-out ``CREATE POLICY`` produced a finding against a table that+ does not exist, and a commented-out ``DROP POLICY`` would have deleted a+ real policy from the replay — a comment silently switching the gate off+ for one table.++ Found by giving the parser a file whose comments disagreed with its SQL+ and reading what it *credited*, which was two policies where there is one.+ """+ out: list[str] = []+ i = 0+ n = len(sql)+ while i < n:+ ch = sql[i]+ if ch == "'":+ # A string literal, including the doubled-quote escape.+ out.append(ch)+ i += 1+ while i < n:+ out.append(sql[i])+ if sql[i] == "'":+ if i + 1 < n and sql[i + 1] == "'":+ out.append(sql[i + 1])+ i += 2+ continue+ i += 1+ break+ i += 1+ continue+ if ch == "-" and sql.startswith("--", i):+ while i < n and sql[i] != "\n":+ i += 1+ continue+ if ch == "/" and sql.startswith("/*", i):+ end = sql.find("*/", i + 2)+ i = n if end == -1 else end + 2+ continue+ out.append(ch)+ i += 1+ return "".join(out)+++def sql_view(name: str, text: str) -> str:+ """The SQL a schema file contains, whatever language wraps it.++ ``.sql`` files are SQL. The four alembic chains are Python that passes SQL+ to ``op.execute`` as implicitly-concatenated string literals across several+ source lines and with **no trailing semicolon** — so a statement regex+ anchored on ``;`` matched none of them and the four revisions covering+ twelve tenant-scoped tables were read as containing no policy at all.++ That was caught by this gate's own blind-spot clause rather than by review,+ which is the argument for having one. Python folds adjacent literals into a+ single constant at parse time, so walking the AST recovers each statement+ whole; they are re-emitted in source order with terminators so the replay+ below sees a normal chain.+ """+ if not name.endswith(".py"):+ return strip_comments(text)+ try:+ tree = ast.parse(text)+ except SyntaxError:+ return text+ # Only ``upgrade()``. An alembic revision's ``downgrade()`` is a mirror+ # image — every CREATE POLICY has a DROP POLICY facing it — so replaying+ # both in source order cancels the file out to nothing. The first version+ # of this function did exactly that, and the give-away was that removing a+ # blind spot over four files left the policy count unchanged: the gate+ # started reading them and immediately un-read them. Counting what a parser+ # *credits* is how that surfaced; the failure list looked fine.+ scope: ast.AST = tree+ for node in tree.body:+ if isinstance(node, ast.FunctionDef) and node.name == "upgrade":+ scope = node+ break++ # (line, column, text) rather than the nodes themselves: ``Constant.value``+ # is a union over every literal type, so joining the nodes' values needs a+ # narrowing the comprehension has already done but the type does not carry.+ literals: list[tuple[int, int, str]] = [+ (node.lineno, node.col_offset, node.value)+ for node in ast.walk(scope)+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value.strip()+ ]+ literals.sort()+ return strip_comments(";\n".join(text for _line, _col, text in literals) + ";")+++def replay(files: list[tuple[str, str]]) -> Schema:+ """Apply the chain in order and return the surviving policy set."""+ schema = Schema()+ for name, raw in files:+ schema.files.append(name)+ text = sql_view(name, raw)+ enabled = {_bare(m.group("table")) for m in _ENABLE_RE.finditer(text)}+ creates = list(_CREATE_RE.finditer(text))+ schema.rls_tables |= enabled++ # A file that switches RLS on but from which no policy parsed has not+ # been read, whatever it says. Enabling without a policy is also a+ # deny-all, so it is worth a human either way.+ if enabled and not creates and "CREATE POLICY" in text.upper():+ schema.blind_spots.append(name)++ for drop in _DROP_RE.finditer(text):+ schema.policies.pop((_bare(drop.group("table")), drop.group("name")), None)+ for create in creates:+ table = _bare(create.group("table"))+ schema.policies[(table, create.group("name"))] = Policy(+ table=table, name=create.group("name"), body=create.group("body"), source=name+ )+ for force in _FORCE_RE.finditer(text):+ schema.forced.add(_bare(force.group("table")))+ for unforce in _NOFORCE_RE.finditer(text):+ schema.forced.discard(_bare(unforce.group("table")))+ for disable in _DISABLE_RE.finditer(text):+ table = _bare(disable.group("table"))+ schema.rls_tables.discard(table)+ for key in [k for k in schema.policies if k[0] == table]:+ schema.policies.pop(key)+ return schema+++def judge(schema: Schema) -> list[str]:+ """Both directions over the surviving policies."""+ problems: list[str] = []++ for (table, name), policy in sorted(schema.policies.items()):+ body = policy.body+ where = f"{policy.source}: {table}.{name}"++ settings = list(_SETTING_RE.finditer(body))+ uses_helper = _HELPER.lower() in body.lower()++ for setting in settings:+ guc = setting.group("name")+ if guc != CANONICAL_GUC:+ problems.append(+ f"{where} reads {guc!r}; nothing in the tree sets that, so the policy returns zero rows forever"+ )+ elif "true" not in setting.group("rest").lower():+ problems.append(+ f"{where} calls current_setting({guc!r}) without missing_ok, so an unbound session raises "+ "'unrecognized configuration parameter' instead of returning rows"+ )++ if not settings and not uses_helper:+ problems.append(+ f"{where} references neither current_tenant_id() nor current_setting({CANONICAL_GUC!r}); "+ "the gate cannot tell what it is scoped by"+ )+ continue++ # The forward direction: the fail-open arm.+ if not re.search(r"\bIS\s+NULL\b", body, re.I):+ problems.append(+ f"{where} has no 'OR <tenant context> IS NULL' arm. Ingest, fusion, the retention purge and the "+ "schedulers read this table on a connection that binds no tenant; without the arm they see zero "+ "rows and report success."+ )++ for table in sorted(schema.rls_tables):+ if table not in schema.forced:+ problems.append(+ f"{table}: row-level security is enabled but not FORCEd, so the table owner — which is the role "+ "that runs migrations — walks straight past the policy"+ )+ if not any(t == table for t, _ in schema.policies):+ problems.append(f"{table}: row-level security is enabled with no surviving policy, which denies every row")++ return problems+++# ---------------------------------------------------------------------------+# Self-test — runs first, every time+# ---------------------------------------------------------------------------++_GOOD = (+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\n"+ "ALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);"+)++_FIXTURES: tuple[tuple[str, str, bool], ...] = (+ ("the canonical shape passes", _GOOD, True),+ (+ "a commented-out policy is prose, not a statement",+ "-- CREATE POLICY ghost_tenant ON ghost USING (tenant_id = current_tenant_id());\n"+ "/* DROP POLICY IF EXISTS t_tenant ON t; */\n" + _GOOD,+ True,+ ),+ (+ "no fail-open arm — cross-tenant workers would see nothing",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_tenant_id());",+ False,+ ),+ (+ "a GUC nothing sets",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_setting('app.tenant_id', true)::uuid "+ "OR current_setting('app.tenant_id', true) IS NULL);",+ False,+ ),+ (+ "current_setting without missing_ok raises on an unbound session",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_setting('app.current_tenant_id')::uuid "+ "OR current_setting('app.current_tenant_id')::uuid IS NULL);",+ False,+ ),+ (+ "ENABLE without FORCE lets the owner past",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);",+ False,+ ),+ (+ "ENABLE with no policy denies every row",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;",+ False,+ ),+ (+ "a later migration repairing an earlier one is not a finding",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_old ON t USING (tenant_id = current_setting('app.tenant_id', true)::uuid);\n"+ "DROP POLICY IF EXISTS t_old ON t;\n"+ "CREATE POLICY t_tenant ON t USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);",+ False, # still fails: the *fixture* is one file, and the repair is judged — see below+ ),+ (+ "doubled quotes inside EXECUTE format() are read, not skipped",+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "EXECUTE 'CREATE POLICY t_tenant ON t USING (tenant_id = current_setting(''app.tenant_id'', true)::uuid)';",+ False,+ ),+)+++#: The alembic shape, as a Python source fixture. Kept separate from _FIXTURES+#: because it exercises :func:`sql_view` rather than :func:`judge`, and because+#: the bug it pins had two halves: not reading the file at all, then reading it+#: and its ``downgrade()`` mirror so the two cancelled.+_ALEMBIC_GOOD = '''+"""A revision docstring, which is a string constant and must not be read as SQL."""++def upgrade():+ op.execute("ALTER TABLE t ENABLE ROW LEVEL SECURITY")+ op.execute("ALTER TABLE t FORCE ROW LEVEL SECURITY")+ op.execute(+ "CREATE POLICY t_tenant ON t "+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"+ )++def downgrade():+ op.execute("DROP POLICY IF EXISTS t_tenant ON t")+ op.execute("ALTER TABLE t DISABLE ROW LEVEL SECURITY")+'''++_ALEMBIC_BAD = _ALEMBIC_GOOD.replace(+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)", ")"+)+++def self_test() -> list[str]:+ failures: list[str] = []++ # An alembic revision must be read, must yield its policy, and must not be+ # cancelled out by its own downgrade().+ good = replay([("0002_tenant_rls.py", _ALEMBIC_GOOD)])+ if not good.policies:+ failures.append("an alembic revision yielded no policy — sql_view is not reading op.execute() literals")+ if judge(good):+ failures.append(f"a well-formed alembic revision was rejected: {judge(good)[0]}")+ if not judge(replay([("0002_tenant_rls.py", _ALEMBIC_BAD)])):+ failures.append("an alembic revision missing the fail-open arm was accepted")+ for label, sql, should_pass in _FIXTURES:+ if label.startswith("a later migration"):+ continue # handled by the two-file case below+ problems = judge(replay([(f"<self-test: {label}>", sql)]))+ passed = not problems+ if passed is not should_pass:+ failures.append(+ f"{label}: judge {'accepted' if passed else 'rejected (' + problems[0] + ')'}, "+ f"expected it to {'accept' if should_pass else 'reject'}"+ )++ # Supersession across two files, which is the real shape in this tree.+ broken = (+ "ALTER TABLE t ENABLE ROW LEVEL SECURITY;\nALTER TABLE t FORCE ROW LEVEL SECURITY;\n"+ "CREATE POLICY t_old ON t USING (tenant_id = current_setting('app.tenant_id', true)::uuid);"+ )+ repair = "DROP POLICY IF EXISTS t_old ON t;\n" + _GOOD+ if judge(replay([("007_broken.sql", broken)])) == []:+ failures.append("the pre-repair definition was accepted, so the chain replay proves nothing")+ if judge(replay([("007_broken.sql", broken), ("060_repair.sql", repair)])):+ failures.append("a repaired policy is still reported, so the chain replay does not follow DROP POLICY")++ # Empty input must not pass.+ if not _empty_findings(Schema()):+ failures.append("an empty schema produced no finding — the gate would pass over an empty tree")+ if _empty_findings(replay([("x.sql", _GOOD)])):+ failures.append("a populated schema was reported as empty — the empty-input rule is over-tight")+ return failures+++def _empty_findings(schema: Schema) -> list[str]:+ if not schema.files:+ return [f"no schema file matched any of the {len(SCHEMA_GLOBS)} globs — nothing was verified"]+ if not schema.policies:+ return [f"{len(schema.files)} schema files were read and not one policy parsed out of them — the parser is broken"]+ return []+++def collect(root: Path) -> list[tuple[str, str]]:+ """Schema files in chain order: per directory, sorted by filename."""+ paths: list[Path] = []+ for pattern in SCHEMA_GLOBS:+ paths.extend(sorted(root.glob(pattern)))+ seen: set[Path] = set()+ out: list[tuple[str, str]] = []+ for path in sorted(paths, key=lambda p: (str(p.parent), p.name)):+ if path in seen:+ continue+ seen.add(path)+ out.append((str(path.relative_to(root)), path.read_text(encoding="utf-8", errors="ignore")))+ return out+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--root", type=Path, default=None)+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="prove the judge still discriminates and that the gate refuses an empty tree, then stop",+ )+ args = parser.parse_args(argv)++ failures = self_test()+ if args.self_test:+ return self_test_main(+ Path(__file__).name,+ args=[],+ extra=[+ (+ f"{len(_FIXTURES) - 1} shape fixtures + alembic shape + supersession + 2 empty-input cases",+ not failures,+ )+ ]+ + [(f"self-test detail: {f}", False) for f in failures],+ )+ if failures:+ print("check_rls_policy_shape: SELF-TEST FAILED — the gate cannot be trusted this run")+ for failure in failures:+ print(f" [FAIL] {failure}")+ return 1+ print(f"check_rls_policy_shape: self-test OK ({len(_FIXTURES) - 1} shape fixtures + supersession + 2 empty-input cases)")++ root = (args.root or repo_root()).resolve()+ files = collect(root)+ schema = replay(files)+ problems = judge(schema) + _empty_findings(schema)+ problems += [f"{name}: enables row-level security but no policy could be parsed out of it" for name in schema.blind_spots]++ chains = sorted({str(Path(name).parent) for name in schema.files})+ print(f"check_rls_policy_shape: replayed {len(schema.files)} schema files under {root}")+ print(f" chains: {', '.join(chains)}")+ print(f" {len(schema.policies)} surviving policies over {len({t for t, _ in schema.policies})} tables; {len(schema.forced)} FORCEd")++ if problems:+ print(f"\nFAIL: {len(problems)} finding(s)")+ for problem in problems:+ print(f" [FAIL] {problem}")+ return 1+ print("OK: every surviving policy admits an unbound session and reads the one GUC the tree sets.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_runtime_db_role.py b/scripts/check_runtime_db_role.pynew file mode 100644index 000000000..134250ae6--- /dev/null+++ b/scripts/check_runtime_db_role.py@@ -0,0 +1,810 @@+#!/usr/bin/env python3+"""Fail if the role a service connects as can reach around row-level security.++Why this exists+---------------+``060_rls_coverage.sql`` took RLS from 31 of 95 tenant-scoped tables to 92, and+established by measurement that not one of those policies filtered anything:+every deployment surface ran the services as the role the postgres image+creates from ``POSTGRES_USER``, which is a **superuser**, and a superuser+ignores policies even under ``FORCE ROW LEVEL SECURITY``. Sixty-one new+policies bought nothing operationally.++``061_runtime_app_role.sql`` and the surfaces around it fix that. This gate is+what stops it coming back — because the way it comes back is not somebody+deleting a policy, it is somebody adding a service to ``docker-compose.yml`` by+copying the block above it.++Three ways a role gets around a policy, all checked+---------------------------------------------------+``SUPERUSER`` ignores RLS outright.+``BYPASSRLS`` ignores RLS outright.+**ownership** ``FORCE`` binds the owner, but an owner can simply issue+ ``ALTER TABLE … NO FORCE ROW LEVEL SECURITY``. A role that+ can turn the control off is not subject to it.++Structural, not a list of names+-------------------------------+The gate never asks "is this role called ``aisoc``". It asks which role *this+surface provisions as the database superuser* — ``POSTGRES_USER`` for the+postgres image, ``username`` for the RDS / Cloud SQL / chart credential — and+then checks whether any runtime DSN in the same surface connects as that role.+Rename every role tomorrow and the gate still works; add a fourteenth service+with a copied DSN and it fails.++Both directions+---------------+The dominant failure shape in this repository is the one-directional gate: it+compares A against B, never B against A, and prints OK while drift accumulates+in the direction things actually change. So:++* forward — a **runtime** DSN connecting as the provisioned superuser fails.+ That is the bypass.+* reverse — a **migration** DSN connecting as anything else fails. The runtime+ role holds no DDL, so this is a deploy that will die on the first+ ``CREATE TABLE``; it is worth catching in review rather than at 2am.+* reverse — a surface that provisions a database but from which no DSN could+ be parsed fails as a **blind spot**, not as a pass. This is the check that+ would have caught this gate being wrong about its own inputs: the failure+ mode of a scanner is silence, and silence here is indistinguishable from+ compliance.++Every one of those is printed with the file, the variable and the role, so the+output says what was inspected rather than only what was wrong.++A self-test runs first, every time+-----------------------------------+:func:`self_test` pushes hand-built surfaces through the same classifier the+real scan uses — a compose file with the bypass, one with the split, one with+the roles the wrong way round, one that mentions a DSN the parser cannot read+— and asserts each verdict. It is not behind a flag, because a gate whose+parser silently stopped matching reports OK, and OK is what a broken gate and a+clean tree look like from outside.++Empty input is a failure+------------------------+A probe recently ran every wired gate against an empty repository and five+reported OK, including the validator behind a number the front page quotes. A+scan that finds no deployment surface has not verified anything, so it exits+non-zero and says so.++Live mode+---------+``--dsn`` asks the database instead of the tree: connect, read ``pg_roles`` and+``pg_class``, and report the three bypasses directly. That is the only way to+catch a role whose attributes were changed outside this repository, and it also+tries the credential ``002_rls.sql`` shipped (``changeme``) so a deployment+still on it is told. Runs in ``integration.yml`` where a database exists.++Usage+-----+ python scripts/check_runtime_db_role.py # static scan+ python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL" \\+ --owner-dsn "$DATABASE_MIGRATION_URL" # + live+ python scripts/check_runtime_db_role.py --self-test-only+"""++from __future__ import annotations++import argparse+import asyncio+import re+import sys+from dataclasses import dataclass, field+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_main # noqa: E402++# ---------------------------------------------------------------------------+# What counts as a deployment surface+# ---------------------------------------------------------------------------++#: Globs relative to the repository root. Every surface that either provisions+#: a Postgres credential or hands one to a service. Docs are excluded on+#: purpose: prose is checked by review, and a code fence in a tutorial is not a+#: deployment.+SURFACE_GLOBS: tuple[str, ...] = (+ "docker-compose.yml",+ "docker-compose.*.yml",+ "infra/compose/*.yml",+ "infra/helm/**/values.yaml",+ "infra/helm/**/templates/*.yaml",+ "infra/terraform/**/*.tf",+ "infra/terraform/**/*.tfvars",+ "infra/fly/**/*.toml",+ ".github/workflows/*.yml",+ ".env.example",+ "render.yaml",+)++#: Environment variable names whose value is a DSN the *migration/DDL* path+#: uses. These are the ones that are *supposed* to be the owner.+MIGRATION_VARS = frozenset({"DATABASE_MIGRATION_URL", "AISOC_DATABASE_MIGRATION_URL"})++#: Some DSNs must be the owner and cannot say so in their variable name, because+#: the tool reading them chose the name: alembic and the SQL runner both read+#: ``DATABASE_URL``, and ``scripts/backup.sh`` needs a credential that can dump+#: and restore every table it does not own.+#:+#: Rather than keep a list of those in this file — which would drift the moment+#: a workflow moved — the surface declares it inline, on or immediately above+#: the line, with a reason:+#:+#: # aisoc-db-role: owner — alembic applies DDL; the runtime role has none+#: DATABASE_URL: postgresql+asyncpg://aisoc:...@localhost:5432/ueba_ci+#:+#: The reason is required and is printed in the scan output, so the exemption+#: is visible at the point of use rather than in a table somebody has to go+#: and find. A marker with no DSN under it fails as stale — same shrink-only+#: discipline as the predicate gate's ratchet, minus the second file.+_OWNER_MARKER_RE = re.compile(r"aisoc-db-role:\s*owner\b[ \t]*[—:-]?[ \t]*(?P<reason>.*)", re.I)++#: Variables that name a database superuser being provisioned. The postgres+#: image creates ``POSTGRES_USER`` as a superuser; the managed-database modules+#: create their master user as the owner of everything the chain builds.+SUPERUSER_DECL_KEYS = ("POSTGRES_USER", "DB_USERNAME", "DB_USER", "MASTER_USERNAME")++#: A Postgres URL in any of the spellings this tree uses. The role is group 2;+#: it is optional so a DSN with no credentials still parses (and is ignored+#: rather than silently treated as compliant).+_DSN_RE = re.compile(+ r"(?P<scheme>postgres(?:ql)?(?:\+\w+)?)://(?:(?P<role>[^:/@\s\"']+)(?::(?P<password>[^@\s\"']*))?@)?"+ r"(?P<host>[^/\s\"']+)",+)++#: `KEY: value` / `KEY=value` / `KEY = "value"`, which covers YAML, dotenv,+#: HCL and TOML closely enough for the keys above. Deliberately loose: a key+#: this misses shows up as a blind spot rather than as a pass.+_ASSIGN_RE = re.compile(r"^\s*(?:-\s*name:\s*)?[\"']?(?P<key>[A-Za-z_][\w.\-]*)[\"']?\s*[:=]\s*(?P<value>.+?)\s*$")++#: Anything that looks like a Postgres URL scheme. Used only to decide whether+#: a surface the parser found nothing in *should* have yielded something.+_SCHEME_HINT_RE = re.compile(r"postgres(?:ql)?(?:\+\w+)?://")++#: Placeholder DSNs used by unit-test jobs that never open a socket+#: (``postgresql+asyncpg://x:x@localhost/x``). Recognised by shape — a role+#: equal to its own password and a host with no real name — not by a list.+_PLACEHOLDER_HOSTS = frozenset({"localhost/x", "localhost", "127.0.0.1"})+++@dataclass+class Dsn:+ var: str+ role: str+ password: str | None+ host: str+ #: Set when the surface declared this DSN as deliberately the owner's,+ #: with the stated reason. ``None`` means it is a runtime DSN.+ owner_reason: str | None = None+++@dataclass+class Finding:+ surface: str+ detail: str+++@dataclass+class Inspected:+ """Everything the scan looked at, so the output can name it."""++ surfaces: list[str] = field(default_factory=list)+ superusers: dict[str, set[str]] = field(default_factory=dict)+ runtime_dsns: list[tuple[str, str, str]] = field(default_factory=list) # surface, var, role+ migration_dsns: list[tuple[str, str, str]] = field(default_factory=list)+ ignored_dsns: list[tuple[str, str, str]] = field(default_factory=list)+ #: DSNs the surface declared as the owner's on purpose, with the reason.+ exempted: list[tuple[str, str, str, str]] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Parsing+# ---------------------------------------------------------------------------+++def _strip_quotes(value: str) -> str:+ value = value.split("#", 1)[0].strip() if not value.startswith(("'", '"')) else value.strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":+ return value[1:-1]+ return value+++def _expand_default(value: str) -> str:+ """``${VAR:-fallback}`` → ``fallback``.++ Deployment surfaces parameterise both the role and the password. The role+ is what this gate reasons about, so an unresolved ``${...}`` would make+ every DSN unclassifiable — which is the same as not checking.+ """+ return re.sub(r"\$\{[A-Za-z_][\w]*:-([^}]*)\}", r"\1", value)+++def _canonical_role(role: str) -> str:+ """``${var.db_username}`` and ``var.db_username`` are the same role.++ Found by enumerating what the gate *credited* rather than what it flagged:+ ``infra/terraform/main.tf`` declares ``db_username = var.db_username`` and+ interpolates ``${var.db_username}`` into every service DSN, and the naive+ string compare read those as two different roles — so the one surface that+ hands the RDS master user to thirteen services was being recorded as+ compliant. A gate's blind spots do not announce themselves in its failures.+ """+ role = role.strip()+ if role.startswith("${") and role.endswith("}"):+ role = role[2:-1]+ return role.strip()+++def _is_placeholder(role: str | None, password: str | None, host: str) -> bool:+ """A DSN that exists to satisfy a settings import, not to reach a database."""+ if role is None:+ return True+ return bool(role == password and host.rstrip("/").split("/")[0] in _PLACEHOLDER_HOSTS)+++def parse_surface(text: str, name: str) -> tuple[set[str], list[Dsn], bool, list[int]]:+ """Pull the provisioned superusers and every DSN out of one file.++ Returns ``(superuser_roles, dsns, saw_scheme, unused_marker_lines)``.+ ``saw_scheme`` records whether the text contains a Postgres URL at all,+ which is how the caller tells "no database here" apart from "the parser+ could not read this one".+ """+ superusers: set[str] = set()+ dsns: list[Dsn] = []+ marker_lines: dict[int, str] = {}+ consumed_markers: set[int] = set()++ pending_name: str | None = None+ for lineno, raw in enumerate(text.splitlines()):+ line = _expand_default(raw)+ match = _ASSIGN_RE.match(line)++ marker = _OWNER_MARKER_RE.search(raw)+ if marker:+ marker_lines[lineno] = marker.group("reason").strip()++ # Kubernetes-style `- name: FOO` / ` value: bar` pairs.+ stripped = line.strip()+ if stripped.startswith("- name:"):+ pending_name = _strip_quotes(stripped.split(":", 1)[1])+ key = None+ value = ""+ if match:+ key = match.group("key")+ value = _strip_quotes(match.group("value"))+ if key == "value" and pending_name:+ key = pending_name+ pending_name = None++ if key and any(key.upper().endswith(decl) for decl in SUPERUSER_DECL_KEYS):+ role = _canonical_role(value)+ if role:+ superusers.add(role)++ for dsn in _DSN_RE.finditer(line):+ owner_reason: str | None = None+ for candidate in (lineno, lineno - 1, lineno - 2):+ if candidate in marker_lines:+ owner_reason = marker_lines[candidate]+ consumed_markers.add(candidate)+ break+ dsns.append(+ Dsn(+ var=key or "<inline>",+ role=dsn.group("role") or "",+ password=dsn.group("password"),+ host=dsn.group("host"),+ owner_reason=owner_reason,+ )+ )++ stale = sorted(set(marker_lines) - consumed_markers)+ return superusers, dsns, bool(_SCHEME_HINT_RE.search(text)), stale+++def classify(surface: str, text: str, inspected: Inspected, known_superusers: set[str] | None = None) -> list[Finding]:+ """Both directions, over one surface. Records what it credited as it goes.++ ``known_superusers`` carries the roles every *other* surface provisions.+ Database roles are properties of the deployment, not of the file that+ mentions them, and scoping the comparison per-file left a hole exactly+ where it mattered: ``.env.example`` hands out a DSN and declares no+ ``POSTGRES_USER``, so it landed in "nothing to compare against" and was+ never checked. Found by reading what the gate credited, not what it+ flagged.+ """+ findings: list[Finding] = []+ declared, dsns, saw_scheme, stale_markers = parse_surface(text, surface)+ superusers = declared | (known_superusers or set())+ inspected.surfaces.append(surface)+ if declared:+ inspected.superusers[surface] = declared++ usable = [d for d in dsns if not _is_placeholder(d.role or None, d.password, d.host)]++ # Reverse direction #2: the parser's own blind spot. A surface that plainly+ # contains a Postgres URL but yielded nothing readable has not been+ # checked, and reporting OK for it is the failure this clause exists to+ # prevent.+ if saw_scheme and not dsns:+ findings.append(+ Finding(surface, "contains a Postgres URL but no DSN could be parsed out of it — the gate cannot vouch for this file")+ )+ return findings++ # Reverse direction #3: an exemption that no longer excuses anything. A+ # marker left behind after its DSN moved reads as a considered decision+ # and is not one.+ for lineno in stale_markers:+ findings.append(+ Finding(surface, f"line {lineno + 1} carries an `aisoc-db-role: owner` marker with no DSN under it — remove it")+ )++ for dsn in usable:+ var, role = dsn.var, _canonical_role(dsn.role)+ is_migration = var.upper() in MIGRATION_VARS or dsn.owner_reason is not None+ bucket = inspected.migration_dsns if is_migration else inspected.runtime_dsns+ bucket.append((surface, var, role))+ if dsn.owner_reason is not None:+ inspected.exempted.append((surface, var, role, dsn.owner_reason))+ if not dsn.owner_reason:+ findings.append(+ Finding(surface, f"{var} is marked `aisoc-db-role: owner` with no reason given; state why it needs DDL")+ )++ if not superusers:+ # Nothing in this surface says which role is privileged, so there+ # is nothing to compare against. Recorded, not credited.+ inspected.ignored_dsns.append((surface, var, role))+ continue++ if is_migration and role not in superusers:+ findings.append(+ Finding(+ surface,+ f"{var} connects as {role!r}, which this surface does not provision as the "+ f"database superuser ({', '.join(sorted(superusers))}). Migrations need DDL; "+ "the runtime role deliberately has none, so this deploy dies on the first CREATE TABLE.",+ )+ )+ elif not is_migration and role in superusers:+ findings.append(+ Finding(+ surface,+ f"{var} connects as {role!r}, which this surface provisions as the database "+ "superuser. A superuser ignores every RLS policy in the schema, even under "+ "FORCE ROW LEVEL SECURITY. Point it at the runtime role and put the owner in "+ "DATABASE_MIGRATION_URL.",+ )+ )++ return findings+++# ---------------------------------------------------------------------------+# Self-test — runs before the scan, not behind a flag+# ---------------------------------------------------------------------------++_FIXTURES: tuple[tuple[str, str, bool], ...] = (+ (+ "bypass: a service connecting as the provisioned superuser",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ DATABASE_URL: postgresql+asyncpg://owner_role:pw@postgres:5432/aisoc+ """,+ False,+ ),+ (+ "split: runtime role for the service, owner for migrations",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ DATABASE_URL: postgresql+asyncpg://runtime_role:pw@postgres:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://owner_role:pw@postgres:5432/aisoc+ """,+ True,+ ),+ (+ "reverse: migrations pointed at the runtime role, which holds no DDL",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ DATABASE_URL: postgresql+asyncpg://runtime_role:pw@postgres:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://runtime_role:pw@postgres:5432/aisoc+ """,+ False,+ ),+ (+ "blind spot: a Postgres URL the DSN pattern cannot read",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ DATABASE_URL: postgresql:// {{ tpl .Values.dsn }}+ """,+ False,+ ),+ (+ "renaming the roles changes nothing — the rule is structural",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: postgres+ api:+ environment:+ DATABASE_URL: postgresql+asyncpg://postgres:pw@postgres:5432/app+ """,+ False,+ ),+ (+ "${VAR:-default} is resolved, so a parameterised bypass is still caught",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ DATABASE_URL: postgresql+asyncpg://owner_role:${PW:-x}@postgres:5432/aisoc+ """,+ False,+ ),+ (+ "a unit-test placeholder DSN is not a deployment and must not fail",+ """+ env:+ POSTGRES_USER: owner_role+ DATABASE_URL: postgresql+asyncpg://x:x@localhost/x+ """,+ True,+ ),+ (+ "an interpolated role matches its own declaration",+ """+ db_username = var.db_username+ database_url = "postgresql+asyncpg://${var.db_username}:pw@rds/aisoc"+ """,+ False,+ ),+ (+ "an owner marker with a reason excuses the DSN under it",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ env:+ # aisoc-db-role: owner — alembic applies DDL+ DATABASE_URL: postgresql+asyncpg://owner_role:pw@localhost:5432/ueba_ci+ """,+ True,+ ),+ (+ "an owner marker with no reason is not an exemption",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ env:+ # aisoc-db-role: owner+ DATABASE_URL: postgresql+asyncpg://owner_role:pw@localhost:5432/ueba_ci+ """,+ False,+ ),+ (+ "an owner marker left behind after its DSN moved fails as stale",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ api:+ environment:+ # aisoc-db-role: owner — this DSN is long gone+ SOME_OTHER_SETTING: 3+ DATABASE_URL: postgresql+asyncpg://runtime_role:pw@postgres:5432/aisoc+ """,+ False,+ ),+ (+ "an owner marker cannot excuse a DSN that is not the owner's",+ """+ services:+ postgres:+ environment:+ POSTGRES_USER: owner_role+ env:+ # aisoc-db-role: owner — claims DDL but names the wrong role+ DATABASE_URL: postgresql+asyncpg://runtime_role:pw@localhost:5432/aisoc+ """,+ False,+ ),+ (+ "a surface with no database at all is simply not a finding",+ """+ services:+ web:+ environment:+ NEXT_PUBLIC_API_URL: http://api:8000+ """,+ True,+ ),+)+++def self_test() -> list[str]:+ """Push known-good and known-bad surfaces through :func:`classify`.++ Returns a list of failure descriptions; empty means the classifier still+ distinguishes the cases it is supposed to.+ """+ failures: list[str] = []+ for label, text, should_pass in _FIXTURES:+ findings = classify(f"<self-test: {label}>", text, Inspected())+ passed = not findings+ if passed is not should_pass:+ verdict = "accepted" if passed else f"rejected ({findings[0].detail})"+ expected = "accept" if should_pass else "reject"+ failures.append(f"{label}: classifier {verdict}, expected it to {expected}")++ # The empty-input rule, asserted rather than assumed: a run that inspected+ # nothing must not be able to report OK.+ if not _empty_input_findings(Inspected()):+ failures.append("an Inspected with no surfaces produced no finding — the gate would pass over an empty tree")+ populated = Inspected(surfaces=["x"], runtime_dsns=[("x", "DATABASE_URL", "r")])+ if _empty_input_findings(populated):+ failures.append("a populated scan was reported as empty — the empty-input rule is over-tight")+ return failures+++def _empty_input_findings(inspected: Inspected) -> list[Finding]:+ """Nothing scanned is a failure, not a pass."""+ out: list[Finding] = []+ if not inspected.surfaces:+ out.append(+ Finding(+ "<root>",+ f"no deployment surface matched any of the {len(SURFACE_GLOBS)} configured globs — "+ "nothing was verified. An absent, empty or wrongly-rooted tree fails here rather "+ "than reporting OK.",+ )+ )+ elif not (inspected.runtime_dsns or inspected.migration_dsns):+ out.append(+ Finding(+ "<root>",+ f"{len(inspected.surfaces)} surfaces were read and not one yielded a database DSN. "+ "Either the tree stopped configuring a database or the parser stopped matching; "+ "both need a human.",+ )+ )+ return out+++# ---------------------------------------------------------------------------+# Live mode+# ---------------------------------------------------------------------------++_WELL_KNOWN_PASSWORD = "changeme" # noqa: S105 — the literal 002_rls.sql shipped; tested against, never used+++def _bare_dsn(url: str) -> str:+ for prefix in ("postgresql+asyncpg://", "postgresql+psycopg://", "postgres+asyncpg://"):+ if url.startswith(prefix):+ return "postgresql://" + url[len(prefix) :]+ return url+++def _redact(dsn: str) -> str:+ return re.sub(r"//([^:/@]*)(:[^@]*)?@", r"//\1:***@", dsn)+++async def _live_findings(dsn: str, owner_dsn: str | None) -> list[Finding]:+ try:+ import asyncpg # noqa: PLC0415 — optional; live mode only+ except ImportError:+ return [Finding("<live>", "asyncpg is not installed, so --dsn could not be checked")]++ findings: list[Finding] = []+ conn = await asyncpg.connect(_bare_dsn(dsn), timeout=15)+ try:+ row = await conn.fetchrow("SELECT current_user AS role, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user")+ owned = await conn.fetch(+ """+ SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r','v','m','p')+ AND c.relowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)+ ORDER BY 1 LIMIT 5+ """+ )+ # A view without security_invoker executes its reads as the view's+ # owner, so it walks past every policy underneath it regardless of who+ # is querying. Checked here because it is exactly the shape this whole+ # change is about, one level of indirection further out.+ leaky_views = await conn.fetch(+ """+ SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind = 'v'+ AND c.relowner <> (SELECT oid FROM pg_roles WHERE rolname = current_user)+ AND coalesce((SELECT option_value FROM pg_options_to_table(c.reloptions)+ WHERE option_name = 'security_invoker'), 'false') <> 'true'+ ORDER BY 1+ """+ )+ finally:+ await conn.close()++ role = row["role"]+ print(f" live: connected as {role!r} (rolsuper={row['rolsuper']}, rolbypassrls={row['rolbypassrls']})")+ if row["rolsuper"]:+ findings.append(Finding("<live>", f"{role!r} is a SUPERUSER and ignores every RLS policy in this database"))+ if row["rolbypassrls"]:+ findings.append(Finding("<live>", f"{role!r} holds BYPASSRLS and ignores every RLS policy in this database"))+ if owned:+ names = ", ".join(r["relname"] for r in owned)+ findings.append(+ Finding("<live>", f"{role!r} owns objects in public ({names}…) and can ALTER TABLE … NO FORCE ROW LEVEL SECURITY")+ )+ if leaky_views:+ names = ", ".join(r["relname"] for r in leaky_views)+ findings.append(+ Finding("<live>", f"views without security_invoker execute as their owner and read past the policies: {names}")+ )++ # The credential 002_rls.sql shipped. Not detectable from a password hash,+ # but perfectly detectable by trying it.+ if not row["rolsuper"]:+ try:+ probe = await asyncpg.connect(+ re.sub(r"//([^:/@]+)(:[^@]*)?@", rf"//\1:{_WELL_KNOWN_PASSWORD}@", _bare_dsn(dsn), count=1),+ timeout=10,+ )+ except Exception: # noqa: BLE001 — a refused login is the good outcome+ pass+ else:+ await probe.close()+ findings.append(+ Finding("<live>", f"{role!r} still accepts the password 002_rls.sql shipped; set AISOC_APP_DB_PASSWORD")+ )++ if owner_dsn:+ owner = await asyncpg.connect(_bare_dsn(owner_dsn), timeout=15)+ try:+ orow = await owner.fetchrow("SELECT current_user AS role, rolsuper FROM pg_roles WHERE rolname = current_user")+ can_ddl = await owner.fetchval("SELECT has_schema_privilege(current_user, 'public', 'CREATE')")+ finally:+ await owner.close()+ print(f" live: migration role {orow['role']!r} (rolsuper={orow['rolsuper']}, CREATE on public={can_ddl})")+ # Reverse direction: the owner must still be able to do what it is for.+ if not can_ddl:+ findings.append(+ Finding("<live>", f"the migration role {orow['role']!r} cannot CREATE in schema public, so the chain cannot apply")+ )+ if orow["role"] == role:+ findings.append(+ Finding("<live>", "DATABASE_URL and DATABASE_MIGRATION_URL are the same role, so the split is nominal only")+ )+ return findings+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def collect(root: Path) -> list[Path]:+ seen: dict[Path, None] = {}+ for pattern in SURFACE_GLOBS:+ for path in sorted(root.glob(pattern)):+ if path.is_file():+ seen.setdefault(path, None)+ return list(seen)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--root", type=Path, default=None, help="tree to scan (default: git toplevel)")+ parser.add_argument("--dsn", default=None, help="also inspect a live database as the runtime role")+ parser.add_argument("--owner-dsn", default=None, help="the migration role, checked in the reverse direction")+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="prove the classifier still discriminates and that the gate refuses an empty tree, then stop",+ )+ args = parser.parse_args(argv)++ # Always first, whether or not --self-test was asked for: a classifier+ # that stopped distinguishing its cases would otherwise report a clean+ # tree, and that is indistinguishable from a working gate.+ st_failures = self_test()+ if args.self_test:+ # The shared body adds the one property this file cannot check about+ # itself — that running the gate inside a repository holding no+ # content exits non-zero rather than printing OK.+ return self_test_main(+ Path(__file__).name,+ args=[],+ extra=[(f"{len(_FIXTURES)} classifier fixtures + 2 empty-input cases", not st_failures)]+ + [(f"self-test detail: {f}", False) for f in st_failures],+ )+ if st_failures:+ print("check_runtime_db_role: SELF-TEST FAILED — the gate cannot be trusted this run")+ for failure in st_failures:+ print(f" [FAIL] {failure}")+ return 1+ print(f"check_runtime_db_role: self-test OK ({len(_FIXTURES)} classifier fixtures + 2 empty-input cases)")++ root = (args.root or repo_root()).resolve()+ surfaces = [(str(p.relative_to(root)), p.read_text(encoding="utf-8", errors="ignore")) for p in collect(root)]++ # Pass one: which roles does this deployment provision as privileged? A+ # role is a property of the database, so a surface that hands out a DSN+ # without declaring one is still checked against what the rest declared.+ known: set[str] = set()+ for _rel, text in surfaces:+ known |= parse_surface(text, _rel)[0]++ inspected = Inspected()+ findings: list[Finding] = []+ for rel, text in surfaces:+ findings.extend(classify(rel, text, inspected, known))++ findings.extend(_empty_input_findings(inspected))++ print(f"check_runtime_db_role: scanned {len(inspected.surfaces)} deployment surfaces under {root}")+ print(f" roles this deployment provisions as privileged: {sorted(known) or '<none found>'}")+ print(+ f" {len(inspected.runtime_dsns)} runtime DSN(s), {len(inspected.migration_dsns)} migration DSN(s), "+ f"{len(inspected.superusers)} surface(s) declaring a provisioned superuser"+ )+ for surface, roles in sorted(inspected.superusers.items()):+ credited = [f"{var}={role}" for s, var, role in inspected.runtime_dsns if s == surface]+ print(f" {surface}: superuser={sorted(roles)} runtime={credited or ['<none>']}")+ if inspected.exempted:+ print(f" {len(inspected.exempted)} DSN(s) declared `aisoc-db-role: owner` on purpose:")+ for surface, var, role, reason in inspected.exempted:+ print(f" {surface}: {var} as {role!r} — {reason}")+ if inspected.ignored_dsns:+ print(f" {len(inspected.ignored_dsns)} DSN(s) in surfaces that declare no superuser, so nothing to compare against:")+ for surface, var, role in inspected.ignored_dsns:+ print(f" {surface}: {var} as {role!r}")++ if args.dsn:+ findings.extend(asyncio.run(_live_findings(args.dsn, args.owner_dsn)))+ print(f" live target: {_redact(args.dsn)}")++ if findings:+ print(f"\nFAIL: {len(findings)} finding(s)")+ for finding in findings:+ print(f" [FAIL] {finding.surface}: {finding.detail}")+ return 1++ print("OK: no service connects as a role that can reach around row-level security.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex ed7a643ba..b3264102d 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -27,11 +27,13 @@ somebody reading this file will see them:ledger / hunt store / LLM resolver, and the per-hunt rebind in the huntscheduler. Every other connection — ingest, fusion, the workers — leaves itunset, and the policies then fail open by design.-* The role the services connect as (``POSTGRES_USER=aisoc`` in compose and CI)- is a superuser, and a superuser bypasses RLS even under FORCE ROW LEVEL- SECURITY. Measured in ``tests/isolation/test_postgres_rls.py``: with two- alerts seeded one per tenant and the context bound to tenant A, that role- sees both.+* The role the services connect as used to be a superuser, and a superuser+ bypasses RLS even under FORCE ROW LEVEL SECURITY, so the second layer was+ not there at all. ``061_runtime_app_role.sql`` moved every deployment+ surface onto a DML-only role and ``scripts/check_runtime_db_role.py`` keeps+ it there, so that caveat is retired — but it applies again the moment an+ operator points ``DATABASE_URL`` at the owner, which is why the credit below+ is still counted separately rather than folded into the total.So on most reads a missing predicate is still a leak rather than adefence-in-depth gap, and this gate is still the control that matters.@@ -56,8 +58,11 @@ Structural signals only, because a naming convention is exactly what drifts:a policy. Four ratchet entries described this mechanism instead of a defect.Re-checking them found the mechanism did not work: the agents service set``app.tenant_id`` while every policy reads ``app.current_tenant_id``. The- rule credits the fixed form and counts it separately in the output, because- the credit lapses on a deployment whose role bypasses RLS.+ rule credits the fixed form and counts it separately in the output. Until+ 061_runtime_app_role.sql that credit lapsed on every shipped deployment,+ because the connecting role bypassed RLS outright; it now holds by default+ and lapses only on a deployment that has pointed DATABASE_URL back at the+ owner — which ``scripts/check_runtime_db_role.py`` fails on.Anything else is a finding, and must be on the ratchet with a reason.@@ -986,7 +991,10 @@ class ScanResult:#: Statements credited because the connection carries an RLS context.#: Reported on every run rather than folded silently into "scoped": the#: credit holds only where the deployment connects as a role that does not- #: bypass RLS, and today's default role does.+ #: bypass RLS. That was false of every shipped surface until+ #: 061_runtime_app_role.sql and is true of all of them now, which is a+ #: property of the deployment rather than of this tree — so it stays a+ #: separate number instead of being folded into "scoped".rls_scoped: intdef __iter__(self):@@ -1046,7 +1054,7 @@ def _print_inventory(findings: list[Finding], inv: Inventory, files: int, statemprint(f" tenant-scoped tables : {len(inv.tables)}")print(f" of those, RLS-covered : {len(inv.tables & inv.rls_tables)} (the rest have query-layer scoping only)")print(f" statements examined : {statements}")- print(f" scoped by RLS context : {rls_scoped} (conditional: the default connection role bypasses RLS)")+ print(f" scoped by RLS context : {rls_scoped} (holds where DATABASE_URL is the DML-only runtime role, which is now the default)")print()services = sorted({f.service for f in findings})print(f"{'service':<16}{'findings':>10}{'ratcheted':>11}{'open':>7}{'no-RLS':>8}")@@ -1408,7 +1416,8 @@ def main(argv: list[str] | None = None) -> int:if result.rls_scoped:print(f" {result.rls_scoped} statement(s) are scoped by an RLS context on the connection rather than by a "- "predicate; that credit holds only where the deployment connects as a role without BYPASSRLS."+ "predicate; that credit holds where DATABASE_URL is a role without SUPERUSER or BYPASSRLS, which "+ "every deployment surface now ships and scripts/check_runtime_db_role.py keeps true.")if len(RATCHET) > MAX_RATCHET:diff --git a/services/agents/app/core/cost_telemetry.py b/services/agents/app/core/cost_telemetry.pyindex 7fac6a3f6..4788d6d36 100644--- a/services/agents/app/core/cost_telemetry.py+++ b/services/agents/app/core/cost_telemetry.py@@ -29,6 +29,8 @@ from typing import Anyimport structlog+from app.core.schema_bootstrap import ensure_table+logger = structlog.get_logger()# ---------------------------------------------------------------------------@@ -99,6 +101,26 @@ class CallRecord:_POOL: Any = None+#: Only used when the table is genuinely absent — normally it arrives with+#: ``services/api/migrations/020_soc_metrics_h2.sql``, which also gives it the+#: RLS policy this copy cannot.+_RUN_COSTS_DDL = """+CREATE TABLE IF NOT EXISTS aisoc_run_costs (+ run_id TEXT NOT NULL,+ tenant_id TEXT NOT NULL,+ model TEXT,+ total_prompt_tokens INTEGER NOT NULL DEFAULT 0,+ total_completion_tokens INTEGER NOT NULL DEFAULT 0,+ total_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ total_latency_ms DOUBLE PRECISION NOT NULL DEFAULT 0,+ call_count INTEGER NOT NULL DEFAULT 0,+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (run_id, tenant_id, model)+);+CREATE INDEX IF NOT EXISTS aisoc_run_costs_tenant_run+ ON aisoc_run_costs (tenant_id, run_id);+"""+async def _get_pool() -> Any | None:global _POOL@@ -116,24 +138,13 @@ async def _get_pool() -> Any | None:max_size=2,)async with pool.acquire() as conn:- await conn.execute(- """- CREATE TABLE IF NOT EXISTS aisoc_run_costs (- run_id TEXT NOT NULL,- tenant_id TEXT NOT NULL,- model TEXT,- total_prompt_tokens INTEGER NOT NULL DEFAULT 0,- total_completion_tokens INTEGER NOT NULL DEFAULT 0,- total_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,- total_latency_ms DOUBLE PRECISION NOT NULL DEFAULT 0,- call_count INTEGER NOT NULL DEFAULT 0,- recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (run_id, tenant_id, model)- );- CREATE INDEX IF NOT EXISTS aisoc_run_costs_tenant_run- ON aisoc_run_costs (tenant_id, run_id);- """- )+ # Probe before creating: the runtime role holds DML only, and+ # `CREATE TABLE IF NOT EXISTS` checks the schema ACL before the+ # existence test, so it raises even when the table is there. See+ # app/core/schema_bootstrap.py.+ if not await ensure_table(conn, "aisoc_run_costs", _RUN_COSTS_DDL):+ await pool.close()+ return None_POOL = poolreturn _POOLexcept Exception as exc:diff --git a/services/agents/app/core/schema_bootstrap.py b/services/agents/app/core/schema_bootstrap.pynew file mode 100644index 000000000..a58915d5a--- /dev/null+++ b/services/agents/app/core/schema_bootstrap.py@@ -0,0 +1,68 @@+"""Converge a table this service needs, without needing DDL rights to do it.++Two stores in this service — the per-run cost ledger and institutional memory —+opened their pool with ``CREATE TABLE IF NOT EXISTS`` and swallowed any failure+into ``logger.debug``. Both tables are already in the API migration chain+(``020_soc_metrics_h2.sql`` and ``022_institutional_memory.sql``), so the DDL+was belt-and-braces on every real deployment.++It stopped being harmless when the services moved onto a non-superuser runtime+role (``services/api/migrations/061_runtime_app_role.sql``). Postgres checks+schema ACL *before* the existence test, so ``CREATE TABLE IF NOT EXISTS`` on a+table that already exists still raises::++ ERROR: permission denied for schema public++Measured against ``postgres:16``, not inferred. With the failure landing in a+``debug`` log and the caller returning ``None``, the observable result would+have been the agents service quietly recording no cost telemetry and no+institutional memory at all — a worker that silently stops, which is the+failure this whole change is meant not to trade the bypass for.++So: look before leaping. If the table is there, nothing is attempted and no+privilege is required. If it is genuinely absent the DDL still runs, and a+failure is reported at ``error`` with the reason spelled out, because at that+point the deployment really is missing a migration.+"""++from __future__ import annotations++from typing import Any++import structlog++logger = structlog.get_logger(__name__)+++async def ensure_table(conn: Any, table: str, ddl: str) -> bool:+ """Make sure ``table`` exists, creating it only if it does not.++ Returns ``True`` when the table is usable afterwards. Never raises: the+ callers treat an unusable store as "fall back to in-memory", and turning+ that into a crash would take the agent down over telemetry. The difference+ from the previous behaviour is that an unusable store is now *loud*.+ """+ try:+ present = await conn.fetchval("SELECT to_regclass($1)", f"public.{table}")+ except Exception as exc: # noqa: BLE001 — a dead connection is the caller's problem+ logger.error("schema_bootstrap.probe_failed", table=table, error=str(exc))+ return False++ if present is not None:+ return True++ try:+ await conn.execute(ddl)+ except Exception as exc: # noqa: BLE001 — reported, not swallowed+ logger.error(+ "schema_bootstrap.create_failed",+ table=table,+ error=str(exc),+ hint=(+ f"{table} is absent and this role cannot create it. The runtime role holds DML only "+ "by design; apply the API migration chain as the owner role (DATABASE_MIGRATION_URL) "+ "instead of relying on this bootstrap."+ ),+ )+ return False+ return Truediff --git a/services/agents/app/memory/institutional.py b/services/agents/app/memory/institutional.pyindex 158e1cb52..062dbd45d 100644--- a/services/agents/app/memory/institutional.py+++ b/services/agents/app/memory/institutional.py@@ -25,12 +25,33 @@ from typing import Anyimport structlog+from app.core.schema_bootstrap import ensure_table+logger = structlog.get_logger()_FALLBACK: dict[str, Any] = {}_POOL: Any = None # asyncpg.Pool | None+#: Only used when the table is genuinely absent — normally it arrives with+#: ``services/api/migrations/022_institutional_memory.sql``, which also gives+#: it the RLS policy this copy cannot.+_MEMORY_DDL = """+CREATE TABLE IF NOT EXISTS aisoc_institutional_memory (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id TEXT NOT NULL,+ key TEXT NOT NULL,+ value JSONB NOT NULL,+ tags TEXT[] NOT NULL DEFAULT '{}',+ analyst_override BOOLEAN NOT NULL DEFAULT FALSE,+ override_reason TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, key)+);+CREATE INDEX IF NOT EXISTS aisoc_institutional_memory_tenant_key+ ON aisoc_institutional_memory (tenant_id, key);+"""+def _normalise_dsn(url: str) -> str:return url.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")@@ -47,25 +68,14 @@ async def _get_pool() -> Any | None:import asyncpg # type: ignore[import]pool = await asyncpg.create_pool(_normalise_dsn(dsn), min_size=1, max_size=3)- # Ensure table exists+ # Probe before creating: the runtime role holds DML only, and+ # `CREATE TABLE IF NOT EXISTS` checks the schema ACL before the+ # existence test, so it raises even when the table is there. See+ # app/core/schema_bootstrap.py.async with pool.acquire() as conn:- await conn.execute(- """- CREATE TABLE IF NOT EXISTS aisoc_institutional_memory (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- tenant_id TEXT NOT NULL,- key TEXT NOT NULL,- value JSONB NOT NULL,- tags TEXT[] NOT NULL DEFAULT '{}',- analyst_override BOOLEAN NOT NULL DEFAULT FALSE,- override_reason TEXT,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- UNIQUE (tenant_id, key)- );- CREATE INDEX IF NOT EXISTS aisoc_institutional_memory_tenant_key- ON aisoc_institutional_memory (tenant_id, key);- """- )+ if not await ensure_table(conn, "aisoc_institutional_memory", _MEMORY_DDL):+ await pool.close()+ return None_POOL = poolreturn _POOLexcept Exception as exc:diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 9a239b4b2..7949f0561 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -320,6 +320,20 @@ class Settings(BaseSettings):# this default mirrors the compose default so ``aisoc serve`` works on a# fresh clone with zero configuration.DATABASE_URL: PostgresDsn = "postgresql+asyncpg://aisoc:aisoc_dev_secret@localhost:5432/aisoc" # type: ignore[assignment]++ # The role that applies the migration chain, which is *not* the role that+ # serves requests. ``DATABASE_URL`` points at `aisoc_app`, which holds DML+ # only and is subject to row-level security; DDL needs the table owner.+ #+ # Falls back to ``DATABASE_URL`` when unset, so a deployment that has not+ # split the roles yet behaves exactly as it did before. Where they are+ # split and this is left unset, the migration run fails on the first+ # ``CREATE TABLE`` with "permission denied for schema public" — a loud+ # failure at deploy time, which is the right place for it.+ DATABASE_MIGRATION_URL: str | None = Field(+ default=None,+ validation_alias=AliasChoices("DATABASE_MIGRATION_URL", "AISOC_DATABASE_MIGRATION_URL"),+ )DATABASE_POOL_SIZE: int = 20DATABASE_MAX_OVERFLOW: int = 10# Recycle pooled connections before managed Postgres idle-closes them.diff --git a/services/api/app/db/cross_tenant.py b/services/api/app/db/cross_tenant.pynew file mode 100644index 000000000..734e824c8--- /dev/null+++ b/services/api/app/db/cross_tenant.py@@ -0,0 +1,71 @@+"""The precondition a cross-tenant sweep depends on, asserted instead of assumed.++Three paths in this service read or write across every tenant: the retention+purge, the hunt scheduler's due-hunt sweep, and tenant deletion. All three used+to open with ``SET LOCAL row_security = off``.++That statement only ever worked because the deployment connected as a+superuser. ``migrations/061_runtime_app_role.sql`` moves the services onto a+role with neither ``SUPERUSER`` nor ``BYPASSRLS``, and for such a role Postgres+does not ignore policies when row security is off — it refuses the query::++ ERROR: query would be affected by row-level security policy for table "alerts"++So the construct flips from "no-op dressed as a control" to "hard failure", and+the cross-tenant reads rest instead on the arm every policy in this schema+already carries::++ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)++A session that never bound a tenant sees everything. That is deliberate and+documented; ``scripts/check_rls_policy_shape.py`` fails if a policy is added+without the arm, so the schema side cannot drift.++Which leaves exactly one way for a sweep to go quiet: running on a session that+*did* bind a tenant. It would then enumerate one tenant, purge or reschedule+that tenant's rows under whatever configuration it loaded, and report success.+A worker that silently stops seeing data is a worse failure than the bypass+this change closes, so that condition raises here.++This module deliberately imports nothing from ``app.api`` — it is called from+background workers, and ``app.db.rls`` pulls in the FastAPI dependency graph.+"""++from __future__ import annotations++import logging++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++logger = logging.getLogger("aisoc.cross_tenant")++_BOUND_TENANT_SQL = "SELECT NULLIF(current_setting('app.current_tenant_id', true), '')"+++class CrossTenantPreconditionError(RuntimeError):+ """A cross-tenant sweep was asked to run on a session bound to one tenant."""+++def _safe(value: object, limit: int = 64) -> str:+ """One-line, length-capped rendering for a log record."""+ return str(value).replace("\r", "").replace("\n", " ")[:limit]+++async def assert_cross_tenant_session(session: AsyncSession, what: str) -> None:+ """Raise unless ``session`` will see every tenant's rows.++ ``what`` names the sweep so the log record identifies the caller without a+ traceback.+ """+ bound = await session.scalar(text(_BOUND_TENANT_SQL))+ if not bound:+ return+ logger.error(+ "cross-tenant scan %r refused: the session is bound to tenant %s, so it would " "process one tenant's rows and report success",+ _safe(what),+ _safe(bound),+ )+ raise CrossTenantPreconditionError(+ f"{_safe(what)} must run on a session with no tenant bound; app.current_tenant_id is {_safe(bound)!r}"+ )diff --git a/services/api/app/scripts/run_migrations.py b/services/api/app/scripts/run_migrations.pyindex 07a37918c..0f258e9c3 100644--- a/services/api/app/scripts/run_migrations.py+++ b/services/api/app/scripts/run_migrations.py@@ -29,6 +29,7 @@ Run standalone via:from __future__ import annotationsimport asyncio+import contextlibimport loggingimport osfrom pathlib import Path@@ -93,6 +94,21 @@ def _asyncpg_dsn(url: str) -> tuple[str, dict]:return new_url, kwargs+def migration_url() -> str:+ """The DSN migrations run against — the owner's, not the runtime role's.++ ``DATABASE_URL`` points at ``aisoc_app``, which holds SELECT / INSERT /+ UPDATE / DELETE and nothing else, so that row-level security applies to it+ (see ``migrations/061_runtime_app_role.sql``). DDL needs the role that owns+ the tables, which is a separate credential.++ Unset falls back to ``DATABASE_URL``, which is the pre-split behaviour and+ what a single-role deployment still wants.+ """+ configured = (settings.DATABASE_MIGRATION_URL or "").strip()+ return configured or str(settings.DATABASE_URL)++async def _connect() -> asyncpg.Connection:"""Open a fresh asyncpg connection, retrying on transient connect errors.@@ -112,7 +128,7 @@ async def _connect() -> asyncpg.Connection:intentionally **not** retried — those need human attention, notmore attempts."""- dsn, kwargs = _asyncpg_dsn(str(settings.DATABASE_URL))+ dsn, kwargs = _asyncpg_dsn(migration_url())last_exc: Exception | None = None# ~3 min total window (see the back-off below). On the Fly demo, the# release_command machine is often the *first* thing to touch the Postgres@@ -174,6 +190,65 @@ async def _apply_one(conn: asyncpg.Connection, name: str, sql: str) -> tuple[strreturn name, False, str(exc)+async def _provision_runtime_role(conn: asyncpg.Connection) -> None:+ """Apply ``AISOC_APP_DB_PASSWORD`` to the runtime role, if one is configured.++ ``061_runtime_app_role.sql`` creates ``aisoc_app`` with DML-only grants and+ no password, because a migration in a public repository must not carry a+ credential and must not overwrite one an operator already set deliberately.+ The credential therefore arrives from the environment.++ The compose stack also applies it from ``infra/postgres/initdb``, which is+ the cleaner place — it runs before the container reports healthy, so no+ service can race it. That hook fires only on an *empty* data directory+ though, so an upgrade in place never reaches it, and a CI service container+ has no hook at all. This covers both, running on the owner connection that+ just applied the chain.++ Unset is a normal state (a deployment managing the role itself, or one that+ has not split the roles yet) and is logged rather than treated as an error.+ """+ password = os.environ.get("AISOC_APP_DB_PASSWORD", "")+ if not password:+ logger.info(+ "AISOC_APP_DB_PASSWORD unset — leaving the runtime role's credential alone. "+ "If DATABASE_URL points at aisoc_app, that role needs a password from somewhere."+ )+ return+ try:+ # The password is bound as a parameter into a session GUC, then+ # re-quoted by the server for the ALTER (a utility statement takes no+ # parameters). It is never concatenated into SQL in this process.+ await conn.execute("SELECT set_config('aisoc.app_password', $1, false)", password)+ await conn.execute(+ """+ DO $$+ DECLARE pw text := current_setting('aisoc.app_password');+ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ EXECUTE 'CREATE ROLE aisoc_app LOGIN PASSWORD ' || quote_literal(pw);+ ELSE+ EXECUTE 'ALTER ROLE aisoc_app WITH LOGIN PASSWORD ' || quote_literal(pw);+ END IF;+ END $$;+ """+ )+ logger.info("runtime role aisoc_app: login credential applied from AISOC_APP_DB_PASSWORD")+ except Exception as exc: # noqa: BLE001 — reported, never fatal to the chain+ # Loud, because the services connect as this role: getting here means+ # they are about to fail authentication and the reason should already+ # be in the log when that happens.+ logger.error(+ "could not set the runtime role's password (%s: %s). Services pointed at aisoc_app "+ "will fail to authenticate until it is provisioned.",+ type(exc).__name__,+ str(exc).replace("\r", "").replace("\n", " ")[:200],+ )+ finally:+ with contextlib.suppress(Exception):+ await conn.execute("SELECT set_config('aisoc.app_password', '', false)")++def _migrations_required() -> bool:"""Whether a migration *connect* failure should crash the process.@@ -200,7 +275,14 @@ async def main() -> None:returnfiles = sorted(p for p in MIGRATIONS_DIR.iterdir() if p.suffix == ".sql")- logger.info("Found %d migration files", len(files))+ parts = urlsplit(migration_url())+ role = (parts.username or "?").replace("\r", "").replace("\n", " ")[:64]+ logger.info(+ "Found %d migration files; connecting as %r (%s)",+ len(files),+ role,+ "DATABASE_MIGRATION_URL" if (settings.DATABASE_MIGRATION_URL or "").strip() else "DATABASE_URL",+ )try:conn = await _connect()@@ -248,6 +330,8 @@ async def main() -> None:logger.error("✗ failed %s: %s", name, err)failures.append((name, err or ""))+ await _provision_runtime_role(conn)+if failures:logger.warning("%d migrations failed; see logs above", len(failures))# CI strict mode (Phase 3 migrations gate): any failed migrationdiff --git a/services/api/app/services/tenant_deletion.py b/services/api/app/services/tenant_deletion.pyindex 630ddf331..a531a1de0 100644--- a/services/api/app/services/tenant_deletion.py+++ b/services/api/app/services/tenant_deletion.py@@ -41,6 +41,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import settingsfrom app.db.clickhouse import execute_lake_query+from app.db.cross_tenant import assert_cross_tenant_sessionfrom app.db.neo4j import get_session as neo4j_sessionlogger = logging.getLogger("aisoc.tenant_deletion")@@ -154,9 +155,16 @@ async def _count_dependent_organizations(db: AsyncSession, tenant_id: uuid.UUID)async def purge_postgres(db: AsyncSession, tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:result = StoreResult(store="postgres")try:- # Cross-tenant by design, and the predicate below is explicit, so RLS- # would only be able to hide rows we are required to delete.- await db.execute(text("SET LOCAL row_security = off"))+ # Cross-tenant by design, and the predicate below is explicit, so a+ # policy could only hide rows we are required to delete. An unbound+ # session sees all of them through the ``OR current_tenant_id() IS+ # NULL`` arm; a bound one would delete a fraction of the tenant's rows+ # and report the deletion complete, which for this operation is a+ # compliance claim rather than a log line.+ #+ # ``SET LOCAL row_security = off`` used to stand here and raises under+ # the runtime role (``migrations/061_runtime_app_role.sql``).+ await assert_cross_tenant_session(db, "tenant deletion purge")tables = await discover_tenant_tables(db)for table in tables:diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.pyindex 214a07bbb..cda88601a 100644--- a/services/api/app/workers/hunt_scheduler.py+++ b/services/api/app/workers/hunt_scheduler.py@@ -67,6 +67,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.airgap import AirgapViolationfrom app.core.config import settings+from app.db.cross_tenant import assert_cross_tenant_sessionfrom app.db.database import AsyncSessionLocalfrom app.models.case import Casefrom app.models.saved_hunt import SavedHunt@@ -409,13 +410,20 @@ async def run_once(runner = executor or _execute_huntfired = 0try:- # The DB session bound here doesn't carry an ``app.current_tenant_id``- # GUC, so RLS would block reads. Disable the row filter for the- # scheduler's sweep — we *want* cross-tenant visibility because the- # worker iterates every tenant's scheduled hunts. We re-bind the- # tenant before each per-hunt write to keep RLS enforcement intact- # for the case insert.- await db.execute(text("SET LOCAL row_security = off"))+ # The sweep is cross-tenant on purpose: the worker iterates every+ # tenant's scheduled hunts, then re-binds the tenant before each+ # per-hunt write so the case insert is RLS-enforced.+ #+ # It used to open with ``SET LOCAL row_security = off``. That was only+ # ever a no-op dressed as a control — it worked because the deployment+ # connected as a superuser, and under the runtime role+ # (``migrations/061_runtime_app_role.sql``) it raises "query would be+ # affected by row-level security policy" on the first read *and* on+ # every per-hunt write after the rebind. The unbound session already+ # sees every tenant through the ``OR current_tenant_id() IS NULL`` arm;+ # what matters is that nothing bound a tenant before we got here, which+ # would quietly reduce the sweep to one tenant.+ await assert_cross_tenant_session(db, "hunt scheduler sweep")rows = (await db.execute(select(SavedHunt).where(SavedHunt.schedule.is_not(None)))).scalars().all()for hunt in rows:if not _is_due(hunt, now):diff --git a/services/api/app/workers/retention_purge.py b/services/api/app/workers/retention_purge.pyindex dc6f5aebd..ffd39097f 100644--- a/services/api/app/workers/retention_purge.py+++ b/services/api/app/workers/retention_purge.py@@ -46,6 +46,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import settingsfrom app.db.clickhouse import execute_lake_query+from app.db.cross_tenant import assert_cross_tenant_sessionfrom app.db.database import AsyncSessionLocalfrom app.services.retention import _clamp, build_lake_purge_sql, resolve_policy@@ -113,13 +114,19 @@ def build_alert_count_sql(days: int) -> tuple[str, dict[str, int]]:async def _load_policies(db: AsyncSession) -> list[tuple[uuid.UUID, dict[str, int]]]:"""Tenants with an explicit retention policy row.- Read with row security off: the worker is cross-tenant by nature, and the- per-tenant predicate is applied explicitly in each statement below rather- than being inherited from a session GUC. Relying on RLS here would mean the- purge silently no-ops when the GUC is unset, which is precisely the failure- class this worker exists to remove.+ The worker is cross-tenant by nature, and the per-tenant predicate is+ applied explicitly in each statement below rather than being inherited+ from a session GUC.++ This used to open with ``SET LOCAL row_security = off``. Under the runtime+ role (``migrations/061_runtime_app_role.sql``) that raises rather than+ relaxing anything, because Postgres refuses the query instead of ignoring+ the policy for a role the policy applies to. The cross-tenant read now+ rests on the ``OR current_tenant_id() IS NULL`` arm every policy carries,+ and the precondition that makes that arm apply is asserted instead of+ assumed."""- await db.execute(text("SET LOCAL row_security = off"))+ await assert_cross_tenant_session(db, "retention purge policy load")rows = await db.execute(text("SELECT tenant_id, raw_events_days, alerts_days, audit_days " "FROM retention_policies ORDER BY tenant_id"))diff --git a/services/api/migrations/061_runtime_app_role.sql b/services/api/migrations/061_runtime_app_role.sqlnew file mode 100644index 000000000..73beb373f--- /dev/null+++ b/services/api/migrations/061_runtime_app_role.sql@@ -0,0 +1,201 @@+-- The role the services connect as, so that the row-level security policies+-- 060_rls_coverage.sql added are something other than decoration.+--+-- What 060 left undone+-- --------------------+-- 060 took RLS from 31 of 95 tenant-scoped tables to 92, and measured that+-- not one of those policies filtered anything in the default deployment:+-- docker-compose.yml and the CI service containers run every service as+-- POSTGRES_USER=aisoc, which the postgres image creates as a SUPERUSER, and a+-- superuser ignores policies *even under* FORCE ROW LEVEL SECURITY — FORCE+-- binds the table owner, not a superuser. Seeded one alert per tenant and+-- bound the session to tenant A: `aisoc` saw 2 rows, a NOSUPERUSER+-- NOBYPASSRLS role saw 1.+--+-- 060 deliberately stopped there, because switching the connection role needs+-- a password and a grant review that belong to a deployment rather than to a+-- schema change. This migration does the grant review. The password is still+-- the deployment's (see "No credential is set here").+--+-- The role model+-- --------------+-- owner / migration role `aisoc` (POSTGRES_USER). Owns every table, runs+-- DDL, applies this chain. Superuser in the+-- bundled Postgres; needs only table ownership and+-- CREATE on the schema in a managed one.+-- runtime role `aisoc_app`. Every service's DATABASE_URL. DML+-- only: it can read and write rows and it cannot+-- reach around a policy.+--+-- Separating them is the whole mechanism. Migrations legitimately need DDL;+-- the services do not, and a role that can ALTER a table can also+-- `ALTER TABLE … NO FORCE ROW LEVEL SECURITY`, which is a bypass with extra+-- steps. So `aisoc_app` owns nothing, and the gate+-- `scripts/check_runtime_db_role.py` fails if it ever does.+--+-- The minimum grants, worked out by measurement rather than by copying a+-- template+-- ------------------------------------------------------------------------+-- USAGE on schema public — without it every object reference fails.+-- NOT CREATE: see the note on runtime DDL.+-- SELECT, INSERT, UPDATE, DELETE on tables and views. No TRUNCATE (nothing+-- outside migrations and tests issues+-- one), no REFERENCES, no TRIGGER.+-- USAGE, SELECT on sequences — this chain currently defines none, every+-- key being a uuid. Granted anyway so the+-- first `BIGSERIAL` somebody adds does not+-- fail at 3am; `USAGE` is what `nextval`+-- needs and `SELECT` what `currval` does.+-- EXECUTE on functions — PUBLIC already holds this by default, so+-- it changes nothing on a stock database.+-- It is spelled out because a hardened+-- deployment that runs+-- `REVOKE ALL ON ALL FUNCTIONS FROM PUBLIC`+-- would otherwise break RLS itself:+-- `current_tenant_id()` is evaluated as the+-- querying role inside every policy.+--+-- 002_rls.sql granted `ALL` on all tables and sequences. That included+-- TRUNCATE, which lets a role delete every tenant's rows in one statement+-- without a policy ever seeing a WHERE clause. It is revoked below.+--+-- Two views were reading around the policies+-- ------------------------------------------+-- A view executes its underlying reads as the *view's owner* unless it is+-- declared `security_invoker`. Both views in this schema are owned by the+-- superuser that ran the chain, so `mssp_tenant_latest_metrics` and+-- `mssp_effective_tenant_rules` would have kept returning every tenant's rows+-- to `aisoc_app` after the role switch — a bypass that survives the fix that+-- is supposed to close it. Neither view has a caller in the tree today, which+-- is why nobody noticed. Both are switched to `security_invoker` here, and the+-- gate checks views as well as tables so the next one cannot repeat it.+--+-- Cross-tenant work still works, and that is deliberate+-- -----------------------------------------------------+-- Every policy in this schema is `tenant_id = current_tenant_id() OR+-- current_tenant_id() IS NULL` — fail-open on a session that never bound a+-- tenant. Ingest, fusion, the retention purge, the hunt scheduler's sweep and+-- tenant deletion all run on such a session and keep seeing every tenant.+-- That arm is load-bearing rather than incidental: without it those workers+-- would silently process nothing, which is a worse failure than the bypass+-- this migration closes. `scripts/check_rls_policy_shape.py` fails if a policy+-- is added without it.+--+-- One construct does *not* survive the switch: `SET LOCAL row_security = off`.+-- For a role that is neither superuser nor exempt, Postgres does not ignore+-- policies when row security is off — it raises `query would be affected by+-- row-level security policy for table "…"`. Three call sites used it to+-- enumerate tenants and now rely on the unbound-session arm instead, with an+-- explicit precondition check so a bound tenant on a cross-tenant sweep is+-- reported rather than acted on.+--+-- No credential is set here+-- -------------------------+-- A migration in a public repository must not carry a password, and this one+-- does not set or clear one: an operator who has already configured+-- `aisoc_app` keeps their credential. 002_rls.sql did create the role with the+-- literal `changeme`; the compose stack now overwrites that on first boot from+-- `AISOC_APP_DB_PASSWORD`, CI provisions its own, and+-- `scripts/check_runtime_db_role.py --dsn` proves a live deployment is not+-- still on it by trying to log in with it.++-- ─── 1. The runtime role exists and cannot reach around a policy ─────────────+-- Created NOLOGIN with no password when absent, so a half-configured+-- deployment fails at connect time instead of coming up on a credential that+-- is public knowledge. Attributes are re-asserted on every apply: this is the+-- security property, and re-applying must converge on it however the role got+-- into its current state.++DO $$+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ CREATE ROLE aisoc_app NOLOGIN;+ RAISE NOTICE 'created role aisoc_app (NOLOGIN). Set a password and LOGIN before pointing DATABASE_URL at it.';+ END IF;+END+$$;++ALTER ROLE aisoc_app+ WITH NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE NOREPLICATION;++COMMENT ON ROLE aisoc_app IS+ 'AiSOC runtime role: DML only, subject to row-level security. Migrations run as the table owner, not as this role.';++-- ─── 2. Minimum grants ───────────────────────────────────────────────────────+-- REVOKE first so re-applying this migration narrows a widened grant rather+-- than layering a second one on top of it. Written against ALL TABLES /+-- ALL SEQUENCES rather than a list, because a list is a naming convention with+-- extra steps and the next migration would not be on it.++REVOKE ALL ON ALL TABLES IN SCHEMA public FROM aisoc_app;+REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM aisoc_app;+REVOKE ALL ON SCHEMA public FROM aisoc_app;++GRANT USAGE ON SCHEMA public TO aisoc_app;+GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO aisoc_app;+GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO aisoc_app;+GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO aisoc_app;++-- Objects a later migration creates. These are recorded against the role that+-- runs this statement, which is the role that runs the chain — the same role+-- that will create those objects. A deployment that changes its migration role+-- must re-run this migration as the new one, and the gate's live mode reports+-- the resulting gap as a missing grant rather than leaving it to be discovered+-- by a 500.+ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM aisoc_app;+ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON SEQUENCES FROM aisoc_app;+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO aisoc_app;+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO aisoc_app;+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT EXECUTE ON FUNCTIONS TO aisoc_app;++-- ─── 3. Close the two views that read as their owner ─────────────────────────+-- `security_invoker` is Postgres 15+. Every deployment surface in this repo+-- provisions 16 (compose `postgres:16-alpine`, CI `postgres:16`, the RDS and+-- Cloud SQL modules `16.x`), so this is a floor the tree already had rather+-- than one this migration introduces. Guarded by `to_regclass` so the+-- statement is skipped rather than fatal on a database that predates the two+-- MSSP views.++DO $$+BEGIN+ IF to_regclass('public.mssp_tenant_latest_metrics') IS NOT NULL THEN+ EXECUTE 'ALTER VIEW public.mssp_tenant_latest_metrics SET (security_invoker = true)';+ END IF;+ IF to_regclass('public.mssp_effective_tenant_rules') IS NOT NULL THEN+ EXECUTE 'ALTER VIEW public.mssp_effective_tenant_rules SET (security_invoker = true)';+ END IF;+END+$$;++-- ─── 4. Refuse to report success on a role that can still bypass ─────────────+-- The failure this migration exists to prevent is a policy that reads as+-- protection and filters nothing. Asserting the outcome here means a chain+-- that applied "successfully" cannot have left that state behind — including+-- on a managed Postgres where `aisoc_app` was pre-created by someone else with+-- attributes this migration would otherwise have quietly left alone.++DO $$+DECLARE+ bad text;+ owns text;+BEGIN+ SELECT string_agg(flag, ', ') INTO bad FROM (+ SELECT 'SUPERUSER' AS flag FROM pg_roles WHERE rolname = 'aisoc_app' AND rolsuper+ UNION ALL+ SELECT 'BYPASSRLS' FROM pg_roles WHERE rolname = 'aisoc_app' AND rolbypassrls+ ) f;+ IF bad IS NOT NULL THEN+ RAISE EXCEPTION 'aisoc_app still holds % — every RLS policy in this database would be bypassed', bad;+ END IF;++ SELECT string_agg(c.relname, ', ') INTO owns+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public'+ AND c.relkind IN ('r', 'v', 'm', 'p')+ AND c.relowner = (SELECT oid FROM pg_roles WHERE rolname = 'aisoc_app');+ IF owns IS NOT NULL THEN+ RAISE EXCEPTION 'aisoc_app owns %, and an owner can ALTER TABLE … NO FORCE ROW LEVEL SECURITY', owns;+ END IF;+END+$$;diff --git a/services/api/tests/test_retention_worker.py b/services/api/tests/test_retention_worker.pyindex 4c88025bf..dd3636bd7 100644--- a/services/api/tests/test_retention_worker.py+++ b/services/api/tests/test_retention_worker.py@@ -16,6 +16,7 @@ import uuidfrom typing import Anyimport pytest+from app.db.cross_tenant import CrossTenantPreconditionErrorfrom app.services.retention import build_alert_purge_sql, build_lake_purge_sqlfrom app.workers import retention_purgefrom app.workers.retention_purge import (@@ -47,12 +48,27 @@ class FakeScalarResult:class FakeSession:"""Records every statement so tenant scoping can be asserted, not assumed."""- def __init__(self, policies: list[dict[str, Any]], alert_counts: dict[str, int]) -> None:+ def __init__(+ self,+ policies: list[dict[str, Any]],+ alert_counts: dict[str, int],+ bound_tenant: str | None = None,+ ) -> None:self._policies = policiesself._alert_counts = alert_counts+ #: What ``current_setting('app.current_tenant_id', true)`` answers.+ #: ``None`` is the cross-tenant case the worker requires.+ self._bound_tenant = bound_tenantself.statements: list[tuple[str, dict[str, Any]]] = []self.committed = False+ async def scalar(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:+ sql = str(stmt)+ self.statements.append((sql, dict(params or {})))+ if "app.current_tenant_id" in sql:+ return self._bound_tenant+ return None+async def execute(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:sql = str(stmt)self.statements.append((sql, dict(params or {})))@@ -234,13 +250,38 @@ class TestResilience:assert run.tenants[1].lake_rows == 2-async def test_row_security_is_disabled_before_enumerating_tenants(+async def test_cross_tenant_precondition_is_checked_before_enumerating_tenants(lake_calls: list[Any],) -> None:- """Without this the worker reads zero policies and purges nothing, quietly."""+ """Without this the worker reads zero policies and purges nothing, quietly.++ The check used to be ``SET LOCAL row_security = off``, which only worked+ because the deployment connected as a superuser — and which *raises* for+ the runtime role introduced in ``migrations/061_runtime_app_role.sql``.+ The cross-tenant read now rests on the ``OR current_tenant_id() IS NULL``+ arm, so what has to be asserted is that no tenant was bound.+ """db = FakeSession([_policy(TENANT_A)], {})await run_once(db=db, dry_run=True)- assert "SET LOCAL row_security = off" in db.statements[0][0]+ assert "app.current_tenant_id" in db.statements[0][0]+ assert not any("row_security" in sql for sql, _ in db.statements), (+ "SET LOCAL row_security = off raises for a role the policies apply to; " "the worker must not reintroduce it"+ )+++async def test_a_sweep_on_a_tenant_bound_session_refuses_rather_than_purging_one_tenant(+ lake_calls: list[Any],+) -> None:+ """The one way this worker can go quiet, made loud.++ A bound session sees a single tenant, so the sweep would purge that+ tenant's rows under whatever policy it happened to load and report+ success. That is worse than not running.+ """+ db = FakeSession([_policy(TENANT_A)], {}, bound_tenant=str(TENANT_A))+ with pytest.raises(CrossTenantPreconditionError):+ await run_once(db=db, dry_run=True)+ assert not db.deletes(), "the sweep must refuse before issuing any delete"async def test_audit_is_not_purged(lake_calls: list[Any]) -> None:diff --git a/services/api/tests/test_tenant_deletion.py b/services/api/tests/test_tenant_deletion.pyindex b2bcb32f9..ff9f9cb96 100644--- a/services/api/tests/test_tenant_deletion.py+++ b/services/api/tests/test_tenant_deletion.py@@ -38,12 +38,22 @@ class FakeScalar:class FakeSession:- def __init__(self, counts: dict[str, int] | None = None) -> None:+ def __init__(self, counts: dict[str, int] | None = None, bound_tenant: str | None = None) -> None:self.counts = counts if counts is not None else dict.fromkeys(DISCOVERED, 2)+ #: What ``current_setting('app.current_tenant_id', true)`` answers.+ #: ``None`` is the cross-tenant case the purge requires.+ self._bound_tenant = bound_tenantself.statements: list[str] = []self.committed = Falseself.rolled_back = False+ async def scalar(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:+ sql = " ".join(str(stmt).split())+ self.statements.append(sql)+ if "app.current_tenant_id" in sql:+ return self._bound_tenant+ return None+async def execute(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:sql = " ".join(str(stmt).split())self.statements.append(sql)@@ -238,3 +248,21 @@ def test_report_serialises_every_store() -> None:assert payload["complete"] is Falseassert payload["total_rows"] == 10assert {s["store"] for s in payload["stores"]} == {"postgres", "neo4j"}+++async def test_a_purge_on_a_tenant_bound_session_refuses_rather_than_deleting_a_fraction() -> None:+ """The one way this can go quiet, made loud.++ The purge is cross-tenant by construction and used to open with+ ``SET LOCAL row_security = off``, which only worked because the deployment+ connected as a superuser. Under the runtime role+ (``migrations/061_runtime_app_role.sql``) that statement raises, so the+ read now rests on the ``OR current_tenant_id() IS NULL`` arm — and a+ session that *did* bind a tenant would delete some of that tenant's rows+ and report the deletion complete. For an operation whose output is a+ compliance claim, that is the worst available outcome.+ """+ db = FakeSession(bound_tenant=str(TENANT))+ result = await tenant_deletion.purge_postgres(db, TENANT, dry_run=False)+ assert result.error and "CrossTenantPreconditionError" in result.error+ assert not db.deletes(), "the purge must refuse before issuing any delete"diff --git a/tests/isolation/test_postgres_rls.py b/tests/isolation/test_postgres_rls.pyindex 180b9c7ba..33225f54b 100644--- a/tests/isolation/test_postgres_rls.py+++ b/tests/isolation/test_postgres_rls.py@@ -18,20 +18,21 @@ makes such a test mean anything:step exists to prevent.3. Assert the tenant-A-scoped read returns A's row and never B's.-Read as the *non-superuser the policies are written for*---------------------------------------------------------+Read as the role the deployment actually ships+----------------------------------------------A superuser, or any role with BYPASSRLS, ignores policies even under FORCE ROW-LEVEL SECURITY. ``docker-compose.yml`` and the CI service containers both run-every service as ``POSTGRES_USER=aisoc``, which the postgres image creates as a-superuser — so in the shipped configuration **every policy in this database is-bypassed**. ``test_superuser_bypasses_rls_which_is_why_the_probe_role_exists``-pins that as a measured fact rather than a caveat in a comment, so nobody reads-the green ticks below as "tenant isolation is on in production".--The rest of this suite therefore connects as a purpose-made role with neither-SUPERUSER nor BYPASSRLS. That is the configuration the policies are written-for, and the one ``apps/docs/docs/operations/security.md`` tells operators to-deploy.+LEVEL SECURITY. Until ``061_runtime_app_role.sql`` every service ran as+``POSTGRES_USER=aisoc``, which the postgres image creates as a superuser, so+every policy in this database was bypassed — and this suite compensated by+building its own ``NOSUPERUSER NOBYPASSRLS`` role to read as. That made the+green ticks below a statement about a role nothing ran as.++So the role under test is now ``DATABASE_URL``: whatever the deployment+connects as. ``DATABASE_MIGRATION_URL`` (the owner) is used only for seeding,+which needs DDL-adjacent privileges the runtime role deliberately lacks.+``test_the_shipped_role_does_not_bypass_rls`` asserts the distinction is real+before anything else is measured, so a deployment that collapses the two roles+fails here rather than passing vacuously.Skips when no database answers, so a local ``pytest tests/isolation`` staysgreen — but **cannot** skip where it is supposed to run. ``integration.yml``@@ -55,7 +56,17 @@ import pytestREPO_ROOT = Path(__file__).resolve().parents[2]MIGRATIONS = REPO_ROOT / "services" / "api" / "migrations"+#: The role the deployment connects as — the one whose behaviour this file is+#: about. Not a role the test invents.DSN = os.environ.get("DATABASE_URL", "")++#: The owner. Seeding needs ``SET session_replication_role = replica`` so a+#: foreign key does not force a full object graph per table, and that is+#: superuser-only; the runtime role must not have it. Falls back to ``DSN`` so+#: a single-role deployment still runs — and then fails loudly on+#: :func:`test_the_shipped_role_does_not_bypass_rls`, which is the point.+ADMIN_DSN = os.environ.get("DATABASE_MIGRATION_URL", "").strip() or DSN+REQUIRED = os.environ.get("POSTGRES_RLS_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")#: Applied to every test. ``pytest.mark.asyncio`` is attached per-test instead@@ -70,12 +81,6 @@ pytestmark = pytest.mark.skipif(TENANT_A = uuid.UUID("0c000000-0000-0000-0000-00000000000a")TENANT_B = uuid.UUID("0c000000-0000-0000-0000-00000000000b")-#: A role with neither SUPERUSER nor BYPASSRLS. Created by the fixture rather-#: than reusing ``aisoc_app`` from 002_rls.sql, whose password is a literal-#: ``changeme`` that no deployment should keep and no test should depend on.-PROBE_ROLE = "aisoc_rls_probe"-PROBE_PASSWORD = "rls-probe-not-a-deployment-credential"-#: Excluded from RLS on purpose; see the header of 060_rls_coverage.sql.#: ``users`` must resolve a principal before any tenant exists, and#: platform-admin user administration is deliberately cross-tenant.@@ -95,6 +100,16 @@ def _asyncpg_dsn(url: str) -> str:return url+def _redact(dsn: str) -> str:+ """A DSN safe to put in a failure message: role and host, never the password."""+ return re.sub(r"//([^:/@]*)(:[^@]*)?@", r"//\1:***@", dsn)+++def _role_of(dsn: str) -> str:+ match = re.search(r"//([^:/@]+)", dsn)+ return match.group(1) if match else "?"++#: Quoted literals inside a CHECK constraint, e.g.#: ``CHECK (node_type = ANY (ARRAY['user'::text, 'host'::text]))``._CHECK_LITERAL = re.compile(r"'([^']+)'")@@ -252,37 +267,47 @@ async def _seed_row(conn, table: str, tenant: uuid.UUID, enum_labels: dict[str,await conn.execute(f'INSERT INTO public."{table}" ({", ".join(names)}) VALUES ({", ".join(values)})') # noqa: S608-async def _make_probe_role() -> str:- """A DSN for a role with neither SUPERUSER nor BYPASSRLS."""+async def _connect_admin():+ """Owner connection, used for seeding only."""+ asyncpg = pytest.importorskip("asyncpg")+ if not ADMIN_DSN:+ pytest.skip("neither DATABASE_MIGRATION_URL nor DATABASE_URL is set")+ dsn = _asyncpg_dsn(ADMIN_DSN)+ try:+ return await asyncpg.connect(dsn)+ except Exception as exc: # noqa: BLE001+ # Both branches raise, but `pytest.fail`/`skip` are not annotated+ # NoReturn, so without the explicit raise the function reads as one+ # that sometimes returns None (`py/mixed-returns`).+ if REQUIRED:+ pytest.fail(f"POSTGRES_RLS_ISOLATION_REQUIRED is set but no database answered at {_redact(dsn)}: {exc}")+ pytest.skip(f"no Postgres at {_redact(dsn)}: {exc}")+ raise+++async def _runtime_dsn() -> str:+ """The deployment's own DSN, checked to be usable before anything is read.++ A connect failure here is the finding, not a reason to skip: the point of+ this suite is that the shipped credential works *and* is constrained, and+ "the role could not log in" is how a half-applied role split presents.+ """asyncpg = pytest.importorskip("asyncpg")if not DSN:pytest.skip("DATABASE_URL not set")- admin_dsn = _asyncpg_dsn(DSN)+ dsn = _asyncpg_dsn(DSN)try:- admin = await asyncpg.connect(admin_dsn)+ conn = await asyncpg.connect(dsn)except Exception as exc: # noqa: BLE001if REQUIRED:- pytest.fail(f"POSTGRES_RLS_ISOLATION_REQUIRED is set but no database answered at {admin_dsn!r}: {exc}")- pytest.skip(f"no Postgres at {admin_dsn!r}: {exc}")- try:- await admin.execute(- f"""- DO $$ BEGIN- IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{PROBE_ROLE}') THEN- CREATE ROLE {PROBE_ROLE} LOGIN PASSWORD '{PROBE_PASSWORD}';- END IF;- END $$;- """- )- # NOSUPERUSER / NOBYPASSRLS are the whole point of this role.- await admin.execute(f"ALTER ROLE {PROBE_ROLE} WITH LOGIN NOSUPERUSER NOBYPASSRLS PASSWORD '{PROBE_PASSWORD}'")- await admin.execute(f"GRANT USAGE ON SCHEMA public TO {PROBE_ROLE}")- await admin.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {PROBE_ROLE}")- await admin.execute(f"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {PROBE_ROLE}")- finally:- await admin.close()-- return re.sub(r"//[^@]*@", f"//{PROBE_ROLE}:{PROBE_PASSWORD}@", _asyncpg_dsn(DSN), count=1)+ pytest.fail(+ f"the deployment's own DATABASE_URL ({_redact(dsn)}) could not connect: {exc}. "+ "061_runtime_app_role.sql creates aisoc_app without a password; the deployment "+ "supplies one through AISOC_APP_DB_PASSWORD."+ )+ pytest.skip(f"DATABASE_URL unusable ({_redact(dsn)}): {exc}")+ await conn.close()+ return dsn#: Populated once by :func:`_seeded`. A module-scoped *async* fixture binds@@ -296,13 +321,12 @@ async def _seeded() -> dict:Seeding runs as the owner with replication-role ``replica`` so foreign keysdo not force a full object graph per table. The *reads* under test all run- as the probe role, which is what the policies are written for.+ as the deployment's own role, which is what the policies are written for."""if _STATE:return dict(_STATE)- probe_dsn = await _make_probe_role()- asyncpg = pytest.importorskip("asyncpg")- admin = await asyncpg.connect(_asyncpg_dsn(DSN))+ runtime_dsn = await _runtime_dsn()+ admin = await _connect_admin()enum_labels: dict[str, list[str]] = {}seeded_tables: list[str] = []unseedable: dict[str, str] = {}@@ -336,7 +360,7 @@ async def _seeded() -> dict:finally:await admin.close()- _STATE.update({"tables": tables, "seeded": seeded_tables, "unseedable": unseedable, "probe_dsn": probe_dsn})+ _STATE.update({"tables": tables, "seeded": seeded_tables, "unseedable": unseedable, "runtime_dsn": runtime_dsn})return dict(_STATE)@@ -346,32 +370,89 @@ async def _seeded() -> dict:@pytest.mark.asyncio-async def test_superuser_bypasses_rls_which_is_why_the_probe_role_exists() -> None:- """The role the services actually connect as ignores every policy here.-- Not a caveat in a docstring — a measurement. ``docker-compose.yml`` runs- every service as ``POSTGRES_USER=aisoc``, and the postgres image creates- that role as a superuser. If this test ever *fails* because the connecting- role stopped bypassing RLS, that is good news and the deployment docs- should say so.+async def test_the_shipped_role_does_not_bypass_rls() -> None:+ """Every other result in this file is conditional on this one.++ A superuser, or any role with BYPASSRLS, ignores policies even under FORCE+ ROW LEVEL SECURITY, and an owner can simply turn FORCE off. So before any+ isolation is measured, establish that the role the deployment connects as+ holds none of the three.++ This assertion is the inverse of the one it replaces. That one measured+ the shipped role *bypassing* RLS and pinned it as a fact, because it did;+ 061_runtime_app_role.sql is what made the inverse true.+ """+ seeded = await _seeded()+ asyncpg = pytest.importorskip("asyncpg")+ conn = await asyncpg.connect(seeded["runtime_dsn"])+ try:+ row = await conn.fetchrow(+ "SELECT current_user AS role, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user"+ )+ owned = await conn.fetchval(+ """+ SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r','v','m','p')+ AND c.relowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)+ """+ )+ finally:+ await conn.close()++ problems = []+ if row["rolsuper"]:+ problems.append("SUPERUSER")+ if row["rolbypassrls"]:+ problems.append("BYPASSRLS")+ if owned:+ problems.append(f"owns {owned} object(s) in public, so it can ALTER TABLE … NO FORCE ROW LEVEL SECURITY")+ assert not problems, (+ f"DATABASE_URL connects as {row['role']!r}, which holds {', '.join(problems)}. "+ "Every policy in this database is then decoration and the assertions below prove nothing. "+ "Point DATABASE_URL at the runtime role and DATABASE_MIGRATION_URL at the owner — see "+ "services/api/migrations/061_runtime_app_role.sql."+ )+++async def test_the_owner_still_bypasses_which_is_why_they_are_two_roles() -> None:+ """The other half of the split, asserted so it cannot silently merge.++ If ``DATABASE_MIGRATION_URL`` ever ends up pointing at the runtime role,+ migrations fail at the first ``CREATE TABLE`` — loudly, and at deploy+ time. The reverse, both variables pointing at the owner, is the state this+ whole change exists to end and is *silent*. So measure the contrast+ directly: the same read, as each role, must differ."""- await _seeded()+ seeded = await _seeded()asyncpg = pytest.importorskip("asyncpg")- admin = await asyncpg.connect(_asyncpg_dsn(DSN))+ admin = await _connect_admin()try:- is_super = await admin.fetchval("SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user")- if not is_super:- pytest.skip(f"connected as {DSN.split('//')[-1].split(':')[0]!r}, which does not bypass RLS — policies are live")async with admin.transaction():await admin.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(TENANT_A))- both = await admin.fetchval("SELECT count(*) FROM alerts WHERE tenant_id IN ($1, $2)", TENANT_A, TENANT_B)- assert both == 2, (- f"expected the bypassing role to see both tenants' alerts, saw {both} — "- "if this dropped to 1 the connection role changed and the docs are now understating the guarantee"- )+ owner_sees = await admin.fetchval(+ "SELECT count(*) FROM alerts WHERE tenant_id IN ($1, $2)", TENANT_A, TENANT_B+ )finally:await admin.close()+ runtime = await asyncpg.connect(seeded["runtime_dsn"])+ try:+ async with runtime.transaction():+ await runtime.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(TENANT_A))+ runtime_sees = await runtime.fetchval(+ "SELECT count(*) FROM alerts WHERE tenant_id IN ($1, $2)", TENANT_A, TENANT_B+ )+ finally:+ await runtime.close()++ assert runtime_sees == 1, f"the runtime role bound to tenant A saw {runtime_sees} of the 2 seeded alerts, not 1"+ assert owner_sees == 2, (+ f"the owner bound to tenant A saw {owner_sees}, not both. That is not a leak — it means "+ f"DATABASE_MIGRATION_URL ({_role_of(ADMIN_DSN)}) is not the owner, and the migration chain "+ "will fail the next time it needs DDL."+ )+# ---------------------------------------------------------------------------# The two-tenant replay, once per protected table@@ -399,14 +480,14 @@ async def test_scoped_read_as_A_never_returns_B() -> None:"""The property, table by table, as a non-bypassing role."""seeded = await _seeded()asyncpg = pytest.importorskip("asyncpg")- probe = await asyncpg.connect(seeded["probe_dsn"])+ runtime = await asyncpg.connect(seeded["runtime_dsn"])leaked: list[str] = []vacuous: list[str] = []checked = 0try:for table in seeded["seeded"]:# (2) Unscoped: both tenants' rows are really there.- unscoped = await probe.fetchval(+ unscoped = await runtime.fetchval(f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = ANY($1::text[])', # noqa: S608[str(TENANT_A), str(TENANT_B)],)@@ -415,13 +496,13 @@ async def test_scoped_read_as_A_never_returns_B() -> None:continue# (3) Scoped to A: A's row, never B's.- async with probe.transaction():- await probe.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(TENANT_A))- seen_a = await probe.fetchval(+ async with runtime.transaction():+ await runtime.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(TENANT_A))+ seen_a = await runtime.fetchval(f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = $1', # noqa: S608str(TENANT_A),)- seen_b = await probe.fetchval(+ seen_b = await runtime.fetchval(f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = $1', # noqa: S608str(TENANT_B),)@@ -431,7 +512,7 @@ async def test_scoped_read_as_A_never_returns_B() -> None:leaked.append(f"{table}: tenant A could not see its own row ({seen_a}), so the policy is over-tight")checked += 1finally:- await probe.close()+ await runtime.close()assert not vacuous, "seeded rows were not visible even unscoped, so the scoped assertions prove nothing: " + "; ".join(vacuous)assert not leaked, "; ".join(leaked)@@ -449,16 +530,16 @@ async def test_a_session_with_no_tenant_context_still_sees_everything() -> None:"""seeded = await _seeded()asyncpg = pytest.importorskip("asyncpg")- probe = await asyncpg.connect(seeded["probe_dsn"])+ runtime = await asyncpg.connect(seeded["runtime_dsn"])try:for table in seeded["seeded"][:20]:- both = await probe.fetchval(+ both = await runtime.fetchval(f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = ANY($1::text[])', # noqa: S608[str(TENANT_A), str(TENANT_B)],)assert both == 2, f"{table}: a worker connection with no tenant context saw {both} of 2 rows, not both"finally:- await probe.close()+ await runtime.close()@pytest.mark.asyncio@@ -471,8 +552,7 @@ async def test_no_policy_reads_a_session_variable_nothing_sets() -> None:``unrecognized configuration parameter``. Both are invisible while asuperuser bypasses them."""- asyncpg = pytest.importorskip("asyncpg")- admin = await asyncpg.connect(_asyncpg_dsn(DSN))+ admin = await _connect_admin()try:rows = await admin.fetch("SELECT tablename, policyname, qual FROM pg_policies WHERE schemaname = 'public'")finally:@@ -503,8 +583,7 @@ async def test_every_tenant_table_is_protected_or_named() -> None:two documented exclusions. Reverse: an exclusion that no longer describesan unprotected table fails too, so the list cannot outlive its reason."""- asyncpg = pytest.importorskip("asyncpg")- admin = await asyncpg.connect(_asyncpg_dsn(DSN))+ admin = await _connect_admin()try:unprotected = {r["t"]@@ -582,7 +661,11 @@ async def test_attack_path_relational_fallback_refuses_another_tenants_case() ->sys.path.insert(0, str(api_root))from app.api.v1.endpoints.graph import _attack_path_from_relational # noqa: PLC0415- sa_url = DSN if DSN.startswith("postgresql+") else "postgresql+asyncpg://" + _asyncpg_dsn(DSN).split("://", 1)[1]+ # Owner connection: this replay needs `SET session_replication_role = replica`,+ # which is superuser-only and which the runtime role must not have.+ sa_url = (+ ADMIN_DSN if ADMIN_DSN.startswith("postgresql+") else "postgresql+asyncpg://" + _asyncpg_dsn(ADMIN_DSN).split("://", 1)[1]+ )engine = sqlalchemy_asyncio.create_async_engine(sa_url)case_a = uuid.uuid4()case_b = uuid.uuid4()