Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

Sixty-four tables the second layer did not cover, and seven policies that could never work

Beenu Arorabeb34771ace8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3879791cf..9585e4eab 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -575,11 +575,17 @@ jobs:
# the 0.3.x line has no patch there, so the pin had to move before
# the alert could close. The deterministic eval suites are the
# re-grade — MITRE accuracy is unchanged at 97.0%.
+ # markdown is a declared dependency of this service (pyproject:
+ # markdown = "^3.5") and the report renderer's HTML branch needs it.
+ # test_router_report.py was in neither the install list nor the file
+ # list below, so two of its assertions failed on every developer
+ # machine and CI never ran them either way.
pip install --quiet pytest pytest-asyncio respx \
'langchain-core>=1.2.22,<2' 'langchain-openai>=1,<2' 'langgraph>=1,<2' \
- jsonschema
+ jsonschema 'markdown>=3.5,<4'
cd services/agents
python3 -m pytest \
+ tests/test_router_report.py \
tests/test_mitre_accuracy.py \
tests/test_alert_reduction.py \
tests/test_investigation_completeness.py \
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 895212728..4fa9a1ec0 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -343,6 +343,24 @@ jobs:
MSSP_ISOLATION_REQUIRED: '1'
run: pip install --quiet pytest pytest-asyncio && python -m pytest tests/test_mssp_portfolio_isolation.py -v --tb=short
+ # 060_rls_coverage.sql takes RLS from 31 of 95 tenant-scoped tables to
+ # every one of them bar a documented exclusion. A migration that adds 49
+ # policies is worth what the evidence that they filter is worth, so the
+ # 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".
+ #
+ # 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)
+ env:
+ POSTGRES_RLS_ISOLATION_REQUIRED: '1'
+ run: python -m pytest tests/isolation/test_postgres_rls.py -v --tb=short
+
# 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.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce7a8f1d7..a7b5e6000 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -760,6 +760,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- **The tenant-predicate gate can now tell a guard from a log line, and the
+ ratchet shrank from 34 to 32.** It credited any query addressed by a key
+ passed to a call that also received the caller's tenant — which
+ `investigations.py` does correctly fourteen times — but a guard that logs
+ and continues was indistinguishable from one that raises. The only real
+ instance of the fail-soft shape was caught solely because its unscoped query
+ lived in a different function; written inline it would have been credited.
+ The distinction is now made structurally, and the undecidable remainder is
+ refused rather than guessed: a guard whose result is tested in a branch that
+ only logs demonstrably continues on failure and earns nothing; a guard whose
+ callee raises is enforcing; a callee the module cannot resolve is not
+ credited, so the statement becomes a finding that needs a reason.
+
+ The gate also recognises an RLS context bound on the connection, on a table
+ that carries a policy — the mechanism four ratchet entries described instead
+ of a defect. Re-checking all four rather than trusting them found that none
+ of the four reasons was accurate: two named a `_set_rls_context` that wrote
+ the wrong session variable (fixed, and those two entries are now retired by
+ the rule), and two named "a per-tenant RLS session" that their only caller
+ deliberately does not use — `_purge_alerts` runs with row security *off* and
+ appends the tenant predicate itself. Those two keep their exemption with a
+ corrected reason. Credit granted this way is counted and printed on every
+ run, because it lapses on a deployment whose role bypasses RLS.
+
+ Two further blind spots, found by checking what the gate *credits* rather
+ than what it flags: its RLS inventory globbed only
+ `services/*/migrations/*.sql`, so twelve tenant-scoped tables in four
+ alembic-managed services read as unprotected however many policies they
+ carried; and a policy created inside a PL/pgSQL `EXECUTE` is invisible to
+ it, which is why `060_rls_coverage.sql` spells out 56 literal `ALTER TABLE` /
+ `CREATE POLICY` statements instead of looping over an array. `--self-test`
+ grew from 8 cases to 14, covering both new rules in both directions.
+
- **`check_gate_coverage.py` decides what a check is from what a script does,
not what it is called.** It classified by filename — `check_*`,
`validate_*`, `_conformance.py`, plus a hand-kept list of five exceptions
@@ -818,6 +851,62 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
+- **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 are
+ repaired.** On the other 64 tables the query predicate was the only thing
+ between two customers, so one missing `WHERE tenant_id` was a leak rather
+ than something a second layer caught — which is not the design the
+ repository documents. `060_rls_coverage.sql` adds a policy to every
+ remaining table in the API chain, and the four services that manage their
+ own schema (honeytokens, osquery-tls, purple-team, ueba) each carry a
+ matching alembic revision. The three that remain are named rather than
+ rounded away: `users` is excluded so authentication can resolve a principal
+ before a tenant exists, and `case_tasks` / `case_timeline` are ORM models
+ that no migration creates.
+
+ Four things found along the way, each invisible for the same reason:
+
+ - **The application bypasses RLS entirely.** `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`. Measured, not inferred: with two
+ alerts seeded one per tenant and the session bound to tenant A, that role
+ sees both and a `NOSUPERUSER NOBYPASSRLS` role sees one. The security doc
+ claimed the opposite — "there is no superuser escape hatch via the
+ application's DB role" — and now carries the grant that makes it true.
+ - **Seven policies were keyed on a session variable nothing sets.**
+ `alert_sla_events` and `tenant_sla_config` read `app.tenant_id`;
+ `custom_parsers` and `retention_policies` read `app.current_tenant`;
+ `compliance_evidence` had no unset-context arm. All five returned zero
+ rows once RLS engaged. `external_assets` and `external_asset_drift` called
+ `current_setting` without `missing_ok`, so an unbound session raised
+ `unrecognized configuration parameter` instead. All seven are normalised
+ to the canonical predicate.
+ - **The agents service had the mirror-image bug.** Its four
+ `_set_rls_context` helpers wrote `app.tenant_id` while every policy reads
+ `app.current_tenant_id`, so the scoping they exist to provide had never
+ been applied — the policies fell through their fail-open arm every time.
+ - **Five tables had RLS enabled without `FORCE`**, so the table owner —
+ which is the application — walked past the policy regardless.
+
+ `tests/isolation/test_postgres_rls.py` is the evidence, wired into
+ `integration.yml`'s migrations job where a real database with the full chain
+ already exists. It seeds an A row and a B row into every RLS-covered tenant
+ table (80 of 80 in the API chain), asserts both are visible unscoped before
+ asserting either absence, then binds the session to A and asserts B's row is
+ unreachable. It also asserts the shipped role's bypass, so a green run here
+ can never be read as "tenant isolation is on in production".
+
+- **The attack-path relational fallback is verified against a real Postgres.**
+ `GET /graph/attack-path/{case_id}` reads `aisoc_cases` by id whenever the
+ Neo4j traversal fails — which for a deployment shipping no graph database is
+ always. It gained a tenant predicate in the previous release, but that fix
+ was covered by a gate and by review only: the statement uses
+ `CAST(:cid AS UUID)`, which SQLite mangles, so no offline suite could execute
+ it. Tenant B naming tenant A's case UUID is now demonstrated to be refused
+ against the database the query is written for, with tenant A's row asserted
+ present first.
+
- **Fifty-eight routes across four services carried no authentication at all,
and the previous gate could not see them.** `check_route_tenant_scope.py`
asks a conditional question — *if* a route takes a tenant, where did the
@@ -1132,6 +1221,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Four tests failed on a clean checkout and belonged to nobody.** A suite
+ with known-failing tests teaches everyone to skim past red, so each is now
+ either fixed or skipped with a reason that says what to do about it.
+
+ - `test_hunt_scheduler_cron.py::TestNextFireAt::test_basic_hourly` asserted
+ croniter's answer (the top of the next hour) from a class that, unlike its
+ neighbour, carried no `_CRONITER_AVAILABLE` guard — so without the
+ dependency it failed rather than skipped. Not environmental: the fallback
+ is an interval stepper with defined behaviour that nothing was checking.
+ It now asserts the right answer on each path, so both are tested.
+ - `test_router_report.py::test_findings_with_html_tags_are_escaped` required
+ the literal `&lt;script&gt;`, which only the `markdown` branch produces —
+ the `<pre>` fallback escapes the already-escaped body again and emits
+ `&amp;lt;script&amp;gt;`. That is more escaped, not less, so a correct
+ branch was reporting a security failure. It now asserts the property that
+ matters (nothing reaches the document as an executable tag, and the
+ payload is still present rather than dropped) on either branch.
+ - `test_router_report.py::test_html_wraps_markdown_with_document_chrome`
+ genuinely needs `markdown` — a declared dependency of the service — and
+ now skips with that stated, while CI installs it and runs the file, which
+ it had never done.
+ - `test_graph_freshness.py::test_graph_writer_does_not_block_fusion_on_failure`
+ treated "something answered on port 8080" as "the ingest service
+ answered". Its only escape hatch was a connection error, so an unrelated
+ local service returning 401 became a failure reading "fusion should never
+ block on graph". It now checks `GET /health` reports `service: ingest`
+ before asserting anything, and the skip names what did answer.
+
+- **Two alembic chains could never run.** `services/honeytokens/alembic/` and
+ `services/purple-team/alembic/` each contained an empty `__init__.py`, which
+ shadows the installed `alembic` package whenever the working directory is on
+ `sys.path` — so `alembic upgrade head` failed with
+ `No module named 'alembic.config'` from inside the service directory, and
+ `env.py`'s own `from alembic import context` would have failed the same way.
+ Removed, matching `services/ueba/alembic/`, which never had one. All four
+ service chains are now verified upgrade → downgrade → upgrade against a live
+ Postgres.
+
- **Every live Okta password reset raised `TypeError` and came back FAILED.**
`ResetPasswordExecutor` documents `parameters.send_email` as "used only for
the Okta path", reads it, and passed `send_email=` to
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index f09e5b4df..154be7f03 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -103,18 +103,46 @@ When a user hits an endpoint they don't have permission for, AiSOC returns `403
## Multi-tenant isolation (RLS)
-AiSOC is multi-tenant by design. Every tenant-partitioned table has Postgres Row-Level Security enforced. The migration that sets this up is [`002_rls.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/002_rls.sql).
+AiSOC is multi-tenant by design, and Postgres Row-Level Security is the **second** layer under that. The primary control is the `tenant_id` predicate in the query, gated by [`scripts/check_tenant_query_predicates.py`](https://github.com/beenuar/AiSOC/blob/main/scripts/check_tenant_query_predicates.py). This section describes the layer beneath it, including where it does not currently engage.
The model:
1. The application layer authenticates the user and resolves their `tenant_id`.
-2. Before issuing any query, the SQLAlchemy middleware sets `SET LOCAL app.current_tenant_id = '<uuid>'`.
-3. RLS policies on every tenant-scoped table (`cases`, `alerts`, `connectors`, `detection_rules`, `api_keys`, `playbooks`, `audit_log`, …) enforce `tenant_id = current_tenant_id()`.
-4. The `FORCE ROW LEVEL SECURITY` flag ensures even the table owner is subject to the policy — there is no superuser escape hatch via the application's DB role.
+2. Before issuing any query, the session sets `SET LOCAL app.current_tenant_id = '<uuid>'`.
+3. RLS policies on tenant-scoped tables enforce `tenant_id = current_tenant_id()`.
+4. `FORCE ROW LEVEL SECURITY` is set on every one of them, so the *table owner* is also subject to the policy.
-If `app.current_tenant_id` is not set (e.g. an internal job that needs to operate cross-tenant), the policy permits the query. This is intentional for system-level workers but means **the application-level ORM session must always set the tenant** before serving user requests. The middleware that does this is wired in [`services/api/app/api/v1/deps.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/api/v1/deps.py).
+[`002_rls.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/002_rls.sql) introduced this for six tables. [`060_rls_coverage.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/060_rls_coverage.sql) extended it to the rest of the API chain, and the four services that manage their own schema (honeytokens, osquery-tls, purple-team, ueba) each carry a matching alembic revision. Coverage went from **31 of 95 tenant-scoped tables to 92 of 95**. Run `python scripts/check_tenant_query_predicates.py --inventory` for the live figure rather than trusting this one.
-The `users` table is excluded from RLS deliberately — it would create a chicken-and-egg problem during authentication. Tenant filtering on `users` is enforced at the application layer through `get_current_user()`.
+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
+
+**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.
+
+To make the policies live, connect the services as a role with neither attribute:
+
+```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;
+```
+
+Then point `DATABASE_URL` at `aisoc_app` and keep migrations running as the owner. Verify with:
+
+```sql
+SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user;
+```
+
+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.
+
+**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.
+
+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.
+
+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()`.
### The tenant comes from the credential, never from the request
@@ -205,12 +233,12 @@ table.
### Reads addressed by an id still filter on a tenant
-Tenant isolation is enforced at read time, per store, and **most of this schema
-has nothing behind that**: of 95 tenant-scoped tables only 31 carry an RLS
-policy, and RLS engages only on a session that has run
-`SET LOCAL app.current_tenant_id` (a `TenantDBSession`). On an `aisoc_*` table
-read through a plain session, a missing predicate is a leak, not a
-defence-in-depth gap.
+Tenant isolation is enforced at read time, per store, and the predicate is the
+control 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.
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
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 800d36397..ee8dfda3b 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` | PARTIAL (Postgres only, compiled-SQL not live DB) | Phase 1.3 |
+| 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 |
| 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 |
@@ -128,7 +128,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only |
| 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 and a key this function already validated against the caller's tenant. 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 | 34 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 writes scoped by an RLS context set on the connection rather than by a predicate the AST can see |
+| 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. 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 |
| 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 | - |
@@ -142,8 +143,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 122
-- PARTIAL: 9
+- GATED: 124
+- 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.)
> **Counting note.** These figures previously read 46 / 9, which did not match
@@ -166,12 +167,19 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
### On the PARTIAL rows
They are not closed by editing this column. Each names a gate that does not
-exist yet — a live-DB cross-tenant test, a hermetic ledger-replay e2e, a
-per-language SDK contract-drift check, a 150-payload adversarial eval, an
-egress-blocked air-gapped job. Relabelling any of them GATED without building
-the gate would make this file a liability rather than a control, since its
-whole value is that a reader can trust the Status column without reading the
-workflows.
+exist yet — a hermetic ledger-replay e2e, a per-language SDK contract-drift
+check, a 150-payload adversarial eval, an egress-blocked air-gapped job.
+Relabelling any of them GATED without building the gate would make this file a
+liability rather than a control, since its whole value is that a reader can
+trust the Status column without reading the workflows.
+
+"Cross-tenant isolation (Postgres)" left this list the only way it may: its gap
+read "compiled-SQL not live DB", and `tests/isolation/test_postgres_rls.py` is
+that live DB — the real migration chain on `postgres:16`, two tenants seeded
+into every RLS-covered table, read back as a role that does not bypass RLS. The
+row's caveat column now carries what the gate still does *not* prove (it reads
+as a probe role, not as the deployed one) rather than dropping the caveat with
+the status.
The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.
diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.py
index 1a3b8e749..e834c02a0 100644
--- a/scripts/check_tenant_query_predicates.py
+++ b/scripts/check_tenant_query_predicates.py
@@ -12,11 +12,29 @@ parameter gate cannot see those: they take no tenant parameter, which is
precisely why they were broken. The addressing mode is irrelevant; the predicate
is the control.
-It is the *only* control on most of this schema. Of the 81 tenant-scoped tables
-in the migrations, 32 carry an RLS policy and 49 do not, and RLS only engages on
-a session that ran ``SET LOCAL app.current_tenant_id`` (``TenantDBSession``). On
-an ``aisoc_*`` table read through a plain ``DBSession``, a missing predicate is a
-leak, not a defence-in-depth gap.
+It was the *only* control on most of this schema. Of 95 tenant-scoped tables,
+31 carried an RLS policy and 64 did not; ``060_rls_coverage.sql`` plus a
+revision in each of the four services that manage their own schema takes that
+to every table bar ``users``, which is excluded so authentication can resolve a
+principal before a tenant exists. Run ``--inventory`` for the live figures
+rather than trusting these; they are a description, not a gate.
+
+That does **not** demote the predicate, for two reasons worth stating where
+somebody reading this file will see them:
+
+* RLS engages only on a session that ran ``SET LOCAL app.current_tenant_id``.
+ That is ``TenantDBSession`` in the API, ``_set_rls_context`` in the agents
+ ledger / hunt store / LLM resolver, and the per-hunt rebind in the hunt
+ scheduler. Every other connection — ingest, fusion, the workers — leaves it
+ unset, 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.
+
+So on most reads a missing predicate is still a leak rather than a
+defence-in-depth gap, and this gate is still the control that matters.
What counts as scoped
---------------------
@@ -29,7 +47,17 @@ Structural signals only, because a naming convention is exactly what drifts:
* a predicate binding the row to the **authenticated principal's own identity**
(``PasskeyCredential.user_id == user.user_id``), which is strictly narrower
than their tenant. Only an identity arriving through an auth dependency
- counts — a ``user_id`` the caller typed is not a credential.
+ counts — a ``user_id`` the caller typed is not a credential;
+* a key an **enforcing** guard already checked against the caller's tenant.
+ "Enforcing" is the load-bearing word: a guard that logs and continues reads
+ exactly like one that raises, so :func:`_guard_enforces` decides it
+ structurally and refuses to guess when it cannot (see that docstring);
+* an **RLS context bound on the connection**, on a table that actually carries
+ 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.
Anything else is a finding, and must be on the ratchet with a reason.
@@ -114,6 +142,10 @@ PREDICATE_CALLS = frozenset({"where", "filter", "filter_by", "having", "join", "
#: is tenant-filtered.
TENANT_TOKENS = frozenset({"tenant_id", "tenant_ids", "tenant_uuid", "current_tenant_id"})
+#: The Postgres session variable the RLS policies read. A function that sets
+#: it has scoped the whole connection, which no predicate in the SQL will show.
+RLS_SESSION_VARIABLE = "app.current_tenant_id"
+
#: Annotations that establish an authenticated principal, so a predicate
#: comparing against one of that object's attributes is principal-derived
#: rather than caller-supplied. Mirrors AUTH_DEPENDENCY_NAMES in
@@ -235,18 +267,21 @@ RATCHET: dict[str, str] = {
"services/osquery-tls/app/services/node_registry.py::mark_seen::OsqueryNode": (
"heartbeat write to the node row the key above already resolved, by primary key"
),
- # -- scoped by a mechanism the AST cannot see, named so it can be re-checked
- "services/agents/app/investigator/ledger.py::complete_run::investigation_runs": (
- "connection runs _set_rls_context(conn, tenant_id) first and investigation_runs carries an RLS policy"
- ),
- "services/agents/app/investigator/ledger.py::persist_auto_triage::investigation_runs": (
- "same RLS-context connection as complete_run, on the same RLS-covered table"
- ),
+ # -- SQL fragments, assembled by a caller the gate scores separately -----
+ # These two were on the ratchet as "run on a per-tenant RLS session". They
+ # are not: ``_purge_alerts`` runs with row security *disabled* so it can
+ # enumerate tenants, and appends ``AND tenant_id = :tenant_id`` itself. The
+ # old reason named a mechanism the only caller deliberately avoids, which
+ # is worse than no reason — it would have survived the caller dropping the
+ # predicate. Re-checking every entry instead of trusting the two the RLS
+ # rule was written for is what surfaced this.
"services/api/app/services/retention.py::build_alert_purge_sql::alerts": (
- "returns SQL for the purge worker to run on a per-tenant RLS session; alerts carries an RLS policy"
+ "returns a SQL string and never executes it; the sole caller (workers/retention_purge.py::_purge_alerts) "
+ "appends AND tenant_id = :tenant_id, and that assembled statement is scored on its own"
),
"services/api/app/workers/retention_purge.py::build_alert_count_sql::alerts": (
- "dry-run counterpart of build_alert_purge_sql, run on the same per-tenant RLS session"
+ "same fragment shape as build_alert_purge_sql: _purge_alerts concatenates the tenant predicate onto it "
+ "before executing"
),
"services/api/app/api/v1/endpoints/investigations.py::_fetch_model_costs::aisoc_run_costs": (
"deliberate: the agents service writes whatever tenant_id string the request carried, so the run_id (tenant-bound in "
@@ -260,7 +295,7 @@ RATCHET: dict[str, str] = {
#: Raising this is a deliberate act with a diff attached. Appending to RATCHET
#: without raising it fails the gate, which is the whole point.
-MAX_RATCHET = 34
+MAX_RATCHET = 32
# ---------------------------------------------------------------------------
@@ -326,7 +361,18 @@ def build_inventory(root: Path) -> Inventory:
if "tenant_id" in fields and table is not None:
inv.models[node.name] = table
- for sql in sorted(root.glob("services/*/migrations/*.sql")):
+ # Four services manage their own schema through alembic rather than this
+ # chain of .sql files, so a glob that only saw the latter reported their
+ # twelve tenant-scoped tables as unprotected however many policies they
+ # carried. The regexes below are applied to the revision text unchanged —
+ # which is why those revisions spell each ALTER TABLE out rather than
+ # looping over a tuple of names.
+ schema_files = [
+ *root.glob("services/*/migrations/*.sql"),
+ *root.glob("services/*/alembic/versions/*.py"),
+ *root.glob("services/*/app/db/versions/*.py"),
+ ]
+ for sql in sorted(schema_files):
text = sql.read_text(encoding="utf-8", errors="ignore")
bodies: dict[str, str] = {}
for m in re.finditer(r'CREATE TABLE(?:\s+IF NOT EXISTS)?\s+([\w".]+)\s*\((.*?)\n\s*\);', text, re.S | re.I):
@@ -446,7 +492,93 @@ def _scoping_helpers(tree: ast.AST) -> set[str]:
return helpers
-def _tenant_validated_keys(fn: ast.AST, auth_names: set[str]) -> set[str]:
+def _module_functions(tree: ast.AST) -> dict[str, ast.AST]:
+ """name → definition, for functions defined in this module."""
+ return {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)}
+
+
+def _transfers_control(body: list[ast.stmt]) -> bool:
+ """Does this block stop execution reaching what follows it?
+
+ Approximate on purpose, and approximate in the safe direction: a block
+ containing ``raise``/``return``/``continue``/``break`` anywhere counts as
+ exiting. The alternative — full reachability analysis — buys nothing here,
+ because the shape being told apart is a handler that *only* logs.
+ """
+ for node in body:
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Raise | ast.Return | ast.Continue | ast.Break):
+ return True
+ return False
+
+
+def _guard_enforces(fn: ast.AST, call: ast.Call, parents: dict[ast.AST, ast.AST], module_fns: dict[str, ast.AST]) -> bool:
+ """Can execution reach the query when this guard did *not* find the row?
+
+ This is the difference between a guard and a log line, and it is the one
+ thing the old rule could not see. It credited any call that received the
+ caller's tenant, so::
+
+ case = await _load_case(db, case_id, user.tenant_id)
+ if case is None:
+ logger.warning("case %s not found", case_id) # and carries on
+ ...
+ await db.execute(text("SELECT ... FROM aisoc_cases WHERE id = :cid"))
+
+ read exactly like ``investigations.py``'s ``_fetch_run``, which 404s. The
+ real instance of the fail-soft shape in this tree was caught only because
+ its unscoped query sat in a different function; written inline it would
+ have been credited.
+
+ Three cases, in order, and the undecidable remainder is refused rather
+ than guessed:
+
+ 1. The result is bound and tested. Then the answer is *visible*: if no
+ branch testing it transfers control out, the guard demonstrably
+ continues on failure and earns no credit. This is the decidable core.
+ 2. The result is not tested. Then the guard's contract must be to raise,
+ which is answerable when the callee is defined in this module — the
+ same "resolve it by what it wraps" move that found the aliased
+ playbook-execute route. A callee whose body contains no ``raise``
+ cannot be enforcing.
+ 3. The callee is not resolvable here (imported, a method, an attribute
+ call). Undecidable, so **not credited** — the statement becomes a
+ finding and needs a ratchet entry naming why. Refusing to guess is the
+ narrowing; the previous rule guessed yes.
+ """
+ bound: str | None = None
+ node: ast.AST = call
+ while True:
+ parent = parents.get(node)
+ if parent is None:
+ break
+ if isinstance(parent, ast.Await):
+ node = parent
+ continue
+ if isinstance(parent, ast.Assign) and len(parent.targets) == 1 and isinstance(parent.targets[0], ast.Name):
+ bound = parent.targets[0].id
+ break
+
+ if bound is not None:
+ tests = [n for n in ast.walk(fn) if isinstance(n, ast.If) and bound in _names(n.test)]
+ if tests:
+ # Credited only if some branch that inspects the result leaves.
+ return any(_transfers_control(t.body) or _transfers_control(t.orelse) for t in tests)
+
+ func = call.func
+ name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else None
+ callee = module_fns.get(name) if name else None
+ if callee is None:
+ return False
+ return any(isinstance(n, ast.Raise) for n in ast.walk(callee))
+
+
+def _tenant_validated_keys(
+ fn: ast.AST,
+ auth_names: set[str],
+ parents: dict[ast.AST, ast.AST],
+ module_fns: dict[str, ast.AST],
+) -> set[str]:
"""Keys this function already validated against the caller's tenant.
``investigations.py`` never puts a tenant on the child queries, and is
@@ -456,16 +588,11 @@ def _tenant_validated_keys(fn: ast.AST, auth_names: set[str]) -> set[str]:
by a key the caller's tenant was checked against, which is the property —
not the literal presence of a ``tenant_id`` column in the predicate.
- So: find calls that receive the principal's own tenant, and treat the
- other plain-name arguments of those calls as validated. The link is
- explicit — the statement only gets credit if its predicate names one of
- *those* keys.
-
- Known limit, stated rather than hidden: a guard that fails soft and lets
- execution continue cannot be told from one that raises. That is
- undecidable here, and it is why the ratchet exists. The real instance of
- it in this tree (``get_attack_path``'s relational fallback) is still
- caught, because the unscoped query lives in a different function.
+ So: find calls that receive the principal's own tenant, keep only those
+ whose failure actually stops execution (see :func:`_guard_enforces`), and
+ treat the other plain-name arguments of *those* calls as validated. The
+ link is explicit — the statement only gets credit if its predicate names
+ one of those keys.
"""
validated: set[str] = set()
if not auth_names:
@@ -485,12 +612,64 @@ def _tenant_validated_keys(fn: ast.AST, auth_names: set[str]) -> set[str]:
carries_tenant = True
if not carries_tenant:
continue
+ if not _guard_enforces(fn, node, parents, module_fns):
+ continue
for expr in [*node.args, *[kw.value for kw in node.keywords]]:
if isinstance(expr, ast.Name):
validated.add(expr.id)
return validated
+def _rls_context_setters(tree: ast.AST) -> set[str]:
+ """Functions that bind a connection to one tenant via the Postgres GUC.
+
+ Four statements in this tree are scoped by an RLS context set on the
+ connection rather than by a predicate in the SQL — the agents ledger's
+ ``complete_run`` and ``persist_auto_triage``, and the two retention purge
+ SQL builders. They are correct, and the gate could not see it, so all four
+ sat on the ratchet describing a mechanism instead of a defect.
+
+ Detected by what the function *does* — executes a statement naming
+ ``app.current_tenant_id`` and takes a tenant — not by being called
+ ``_set_rls_context``. A hand-written vocabulary of helper names is the
+ thing that made an aliased ``ExecuteUser`` read as anonymous.
+ """
+ setters: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ params = {a.arg for a in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]}
+ if not any("tenant" in p for p in params):
+ continue
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Constant) and isinstance(sub.value, str) and RLS_SESSION_VARIABLE in sub.value:
+ setters.add(node.name)
+ break
+ return setters
+
+
+def _binds_rls_context(fn: ast.AST | None, setters: set[str]) -> bool:
+ """Does this function bind the connection to a tenant before querying?
+
+ The call must carry something tenant-shaped: ``_set_rls_context(conn)``
+ with no tenant is not a scope, and crediting it would turn the rule into
+ "mentions a helper".
+ """
+ if fn is None or not setters:
+ return False
+ for node in ast.walk(fn):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else None
+ if name not in setters:
+ continue
+ args = _names(ast.Tuple(elts=[*node.args, *[kw.value for kw in node.keywords]], ctx=ast.Load()))
+ if any("tenant" in a for a in args):
+ return True
+ return False
+
+
def _auth_bound_names(fn: ast.AST) -> set[str]:
"""Parameters annotated with an auth dependency, plus ``self``-ish aliases.
@@ -524,6 +703,11 @@ class Finding:
kind: str # "orm" | "sql"
rls: bool
predicates: list[str] = field(default_factory=list)
+ #: Scoped by an RLS context bound on the connection rather than by a
+ #: predicate. Not a finding, but counted and reported, because the credit
+ #: is conditional on the deployment connecting as a role that does not
+ #: bypass RLS — see ``apps/docs/docs/operations/security.md``.
+ via_rls_context: bool = False
@property
def key(self) -> str:
@@ -545,10 +729,13 @@ def _scan_orm(
rel: str,
parents: dict[ast.AST, ast.AST],
fn_of: dict[ast.AST, ast.AST],
-) -> tuple[list[Finding], int]:
+) -> tuple[list[Finding], int, int]:
helpers = _scoping_helpers(tree)
+ module_fns = _module_functions(tree)
+ setters = _rls_context_setters(tree)
findings: list[Finding] = []
total = 0
+ rls_scoped = 0
for node in ast.walk(tree):
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in STATEMENT_FUNCS):
@@ -633,10 +820,16 @@ def _scan_orm(
continue
# Addressed by a key this function already checked against the
# caller's tenant.
- if fn is not None and (_tenant_validated_keys(fn, auth_names) & resolved):
+ if fn is not None and (_tenant_validated_keys(fn, auth_names, parents, module_fns) & resolved):
continue
table = inv.models.get(entity, entity)
+ # Scoped by an RLS context on the connection. Only counts on a table
+ # that actually carries a policy: setting the GUC against a table with
+ # no policy scopes nothing at all.
+ if table in inv.rls_tables and _binds_rls_context(fn, setters):
+ rls_scoped += 1
+ continue
findings.append(
Finding(
service=service,
@@ -650,7 +843,7 @@ def _scan_orm(
predicates=sorted(resolved)[:10],
)
)
- return findings, total
+ return findings, total, rls_scoped
def _docstring_nodes(tree: ast.AST) -> set[int]:
@@ -689,10 +882,13 @@ def _scan_sql(
rel: str,
parents: dict[ast.AST, ast.AST],
fn_of: dict[ast.AST, ast.AST],
-) -> tuple[list[Finding], int]:
+) -> tuple[list[Finding], int, int]:
docstrings = _docstring_nodes(tree)
+ module_fns = _module_functions(tree)
+ setters = _rls_context_setters(tree)
findings: list[Finding] = []
total = 0
+ rls_scoped = 0
seen: set[tuple[int, str]] = set()
for node in ast.walk(tree):
@@ -739,7 +935,12 @@ def _scan_sql(
auth_names = _auth_bound_names(fn) if fn is not None else set()
if auth_names & names:
continue
- if fn is not None and (_tenant_validated_keys(fn, auth_names) & resolved):
+ if fn is not None and (_tenant_validated_keys(fn, auth_names, parents, module_fns) & resolved):
+ continue
+ # Scoped by an RLS context on the connection rather than by anything
+ # visible in the SQL. Only on a table that carries a policy.
+ if table in inv.rls_tables and _binds_rls_context(fn, setters):
+ rls_scoped += 1
continue
findings.append(
@@ -755,15 +956,33 @@ def _scan_sql(
predicates=sorted(n for n in resolved if len(n) < 40)[:10],
)
)
- return findings, total
+ return findings, total, rls_scoped
-def scan(root: Path | None = None) -> tuple[list[Finding], Inventory, int, int]:
+@dataclass
+class ScanResult:
+ findings: list[Finding]
+ inventory: Inventory
+ files: int
+ statements: int
+ #: 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.
+ rls_scoped: int
+
+ def __iter__(self):
+ """Unpack as the 4-tuple the older call sites expect."""
+ return iter((self.findings, self.inventory, self.files, self.statements))
+
+
+def scan(root: Path | None = None) -> ScanResult:
base = root or REPO_ROOT
inv = build_inventory(base)
findings: list[Finding] = []
files = 0
statements = 0
+ rls_scoped = 0
for py in _python_files(base):
try:
@@ -780,13 +999,14 @@ def scan(root: Path | None = None) -> tuple[list[Finding], Inventory, int, int]:
for child in ast.walk(fn):
fn_of[child] = fn
- orm, n_orm = _scan_orm(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)
- sql, n_sql = _scan_sql(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)
+ orm, n_orm, rls_orm = _scan_orm(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)
+ sql, n_sql, rls_sql = _scan_sql(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)
findings.extend(orm)
findings.extend(sql)
statements += n_orm + n_sql
+ rls_scoped += rls_orm + rls_sql
- return findings, inv, files, statements
+ return ScanResult(findings, inv, files, statements, rls_scoped)
# ---------------------------------------------------------------------------
@@ -802,12 +1022,13 @@ def partition(findings: list[Finding]) -> tuple[list[Finding], list[str]]:
return unratcheted, stale
-def _print_inventory(findings: list[Finding], inv: Inventory, files: int, statements: int) -> None:
+def _print_inventory(findings: list[Finding], inv: Inventory, files: int, statements: int, rls_scoped: int = 0) -> None:
print(f"Tenant-predicate inventory — scanned {files} files under {SERVICES_DIR}")
print(f" tenant-scoped ORM models : {len(inv.models)}")
print(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()
services = sorted({f.service for f in findings})
print(f"{'service':<16}{'findings':>10}{'ratcheted':>11}{'open':>7}{'no-RLS':>8}")
@@ -903,6 +1124,103 @@ async def my_widgets(user: AuthUser, db):
return await db.execute(select(Widget).where(Widget.owner_id == user.user_id))
"""
+_GUARD_THAT_RAISES = """
+from typing import Annotated
+from sqlalchemy import select
+from app.api.v1.deps import AuthUser
+from app.models.widget import Widget
+
+async def _fetch_widget(db, widget_id, tenant_id):
+ row = (await db.execute(select(Widget).where(Widget.id == widget_id, Widget.tenant_id == tenant_id))).scalar_one_or_none()
+ if row is None:
+ raise HTTPException(status_code=404)
+ return row
+
+async def read_parts(widget_id, user: AuthUser, db):
+ await _fetch_widget(db, widget_id, user.tenant_id)
+ return await db.execute(select(Widget).where(Widget.id == widget_id))
+"""
+
+_GUARD_THAT_FAILS_SOFT = """
+from typing import Annotated
+from sqlalchemy import select
+from app.api.v1.deps import AuthUser
+from app.models.widget import Widget
+
+async def _find_widget(db, widget_id, tenant_id):
+ return (await db.execute(select(Widget).where(Widget.id == widget_id, Widget.tenant_id == tenant_id))).scalar_one_or_none()
+
+async def read_parts(widget_id, user: AuthUser, db):
+ owned = await _find_widget(db, widget_id, user.tenant_id)
+ if owned is None:
+ logger.warning("widget %s not found for this tenant", widget_id)
+ return await db.execute(select(Widget).where(Widget.id == widget_id))
+"""
+
+_GUARD_TESTED_AND_RAISES = """
+from typing import Annotated
+from sqlalchemy import select
+from app.api.v1.deps import AuthUser
+from app.models.widget import Widget
+
+async def _find_widget(db, widget_id, tenant_id):
+ return (await db.execute(select(Widget).where(Widget.id == widget_id, Widget.tenant_id == tenant_id))).scalar_one_or_none()
+
+async def read_parts(widget_id, user: AuthUser, db):
+ owned = await _find_widget(db, widget_id, user.tenant_id)
+ if owned is None:
+ raise HTTPException(status_code=404)
+ return await db.execute(select(Widget).where(Widget.id == widget_id))
+"""
+
+_GUARD_NOT_RESOLVABLE = """
+from typing import Annotated
+from sqlalchemy import select
+from app.api.v1.deps import AuthUser
+from app.models.widget import Widget
+from app.services.elsewhere import assert_owned
+
+async def read_parts(widget_id, user: AuthUser, db):
+ await assert_owned(db, widget_id, user.tenant_id)
+ return await db.execute(select(Widget).where(Widget.id == widget_id))
+"""
+
+_RLS_CONTEXT_ON_COVERED_TABLE = """
+async def _set_rls_context(conn, tenant_id):
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))
+
+async def finish(conn_pool, widget_id, tenant_id):
+ async with conn_pool.acquire() as conn:
+ await _set_rls_context(conn, tenant_id)
+ await conn.execute("UPDATE widgets SET status = 'done' WHERE id = $1", widget_id)
+"""
+
+_RLS_CONTEXT_ON_UNCOVERED_TABLE = """
+async def _set_rls_context(conn, tenant_id):
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))
+
+async def finish(conn_pool, gadget_id, tenant_id):
+ async with conn_pool.acquire() as conn:
+ await _set_rls_context(conn, tenant_id)
+ await conn.execute("UPDATE gadgets SET status = 'done' WHERE id = $1", gadget_id)
+"""
+
+#: A migration giving ``widgets`` a policy but leaving ``gadgets`` without one,
+#: so the RLS-context rule can be exercised on both sides of its condition.
+_PROBE_MIGRATION = """
+CREATE TABLE IF NOT EXISTS widgets (
+ id UUID PRIMARY KEY,
+ tenant_id UUID NOT NULL
+);
+CREATE TABLE IF NOT EXISTS gadgets (
+ id UUID PRIMARY KEY,
+ tenant_id UUID NOT NULL
+);
+ALTER TABLE widgets ENABLE ROW LEVEL SECURITY;
+CREATE POLICY widgets_tenant ON widgets
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+"""
+
_DOCSTRING_ONLY = '''
"""Widget helpers.
@@ -915,32 +1233,44 @@ def helper():
'''
-def _write_probe(root: Path, sources: dict[str, str]) -> None:
+def _write_probe(root: Path, sources: dict[str, str], *, migration: str | None = None) -> None:
pkg = root / "services" / "probe" / "app"
(pkg / "models").mkdir(parents=True, exist_ok=True)
(pkg / "models" / "widget.py").write_text(_PROBE_MODEL, encoding="utf-8")
for name, src in sources.items():
(pkg / name).write_text(src, encoding="utf-8")
+ if migration is not None:
+ mig = root / "services" / "probe" / "migrations"
+ mig.mkdir(parents=True, exist_ok=True)
+ (mig / "001_probe.sql").write_text(migration, encoding="utf-8")
def _self_test() -> int:
"""Prove the gate fails on injected drift, both ways, and drops a stale entry."""
- cases: list[tuple[str, dict[str, str], int]] = [
- ("clean: by-id read carries a tenant predicate", {"r.py": _CLEAN}, 0),
- ("drift A: by-id ORM read with no tenant predicate", {"r.py": _UNSCOPED}, 1),
- ("drift B: by-id raw SQL with no tenant predicate", {"r.py": _UNSCOPED_SQL}, 1),
- ("control: predicate built in a filters list", {"r.py": _SCOPED_VIA_LIST}, 0),
- ("control: predicate applied by a wrapping helper", {"r.py": _SCOPED_VIA_HELPER}, 0),
- ("control: predicate added by a later q = q.where()", {"r.py": _SCOPED_VIA_REBIND}, 0),
- ("control: scoped on the authenticated principal's own id", {"r.py": _SCOPED_VIA_PRINCIPAL}, 0),
- ("control: SQL in a docstring is prose, not a query", {"r.py": _DOCSTRING_ONLY}, 0),
+ cases: list[tuple[str, dict[str, str], int, str | None]] = [
+ ("clean: by-id read carries a tenant predicate", {"r.py": _CLEAN}, 0, None),
+ ("drift A: by-id ORM read with no tenant predicate", {"r.py": _UNSCOPED}, 1, None),
+ ("drift B: by-id raw SQL with no tenant predicate", {"r.py": _UNSCOPED_SQL}, 1, None),
+ ("control: predicate built in a filters list", {"r.py": _SCOPED_VIA_LIST}, 0, None),
+ ("control: predicate applied by a wrapping helper", {"r.py": _SCOPED_VIA_HELPER}, 0, None),
+ ("control: predicate added by a later q = q.where()", {"r.py": _SCOPED_VIA_REBIND}, 0, None),
+ ("control: scoped on the authenticated principal's own id", {"r.py": _SCOPED_VIA_PRINCIPAL}, 0, None),
+ ("control: SQL in a docstring is prose, not a query", {"r.py": _DOCSTRING_ONLY}, 0, None),
+ # The fail-soft distinction. All four look identical to the old rule.
+ ("control: guard whose callee raises is enforcing", {"r.py": _GUARD_THAT_RAISES}, 0, None),
+ ("control: guard tested with a raising handler is enforcing", {"r.py": _GUARD_TESTED_AND_RAISES}, 0, None),
+ ("drift C: guard that logs and carries on is not a guard", {"r.py": _GUARD_THAT_FAILS_SOFT}, 1, None),
+ ("drift D: guard defined elsewhere is undecidable, so not credited", {"r.py": _GUARD_NOT_RESOLVABLE}, 1, None),
+ # The RLS-context rule, on both sides of its condition.
+ ("control: RLS context bound on a table that has a policy", {"r.py": _RLS_CONTEXT_ON_COVERED_TABLE}, 0, _PROBE_MIGRATION),
+ ("drift E: RLS context bound on a table with no policy", {"r.py": _RLS_CONTEXT_ON_UNCOVERED_TABLE}, 1, _PROBE_MIGRATION),
]
failures = 0
with tempfile.TemporaryDirectory() as tmp:
- for i, (label, sources, want) in enumerate(cases):
+ for i, (label, sources, want, migration) in enumerate(cases):
root = Path(tmp) / f"case{i}"
- _write_probe(root, sources)
+ _write_probe(root, sources, migration=migration)
findings, _inv, files, _stmts = scan(root=root)
got = len(findings)
ok = got == want and files > 0
@@ -954,7 +1284,7 @@ def _self_test() -> int:
if failures:
print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)
return 1
- print("\nself-test passed: drift detected in both directions, six controls clear, and a stale ratchet entry is dropped.")
+ print("\nself-test passed: drift detected in both directions, ten controls clear, and a stale ratchet entry is dropped.")
return 0
@@ -1019,14 +1349,15 @@ def main(argv: list[str] | None = None) -> int:
print(f"ERROR: no services/ directory under {REPO_ROOT} — refusing to report a result for a tree I did not open.", file=sys.stderr)
return 2
- findings, inv, files, statements = scan()
+ result = scan()
+ findings, inv, files, statements = result.findings, result.inventory, result.files, result.statements
if args.json:
print(json.dumps([asdict(f) for f in findings], indent=2))
return 0
if args.inventory:
- _print_inventory(findings, inv, files, statements)
+ _print_inventory(findings, inv, files, statements, result.rls_scoped)
return 0
unratcheted, stale = partition(findings)
@@ -1038,6 +1369,11 @@ def main(argv: list[str] | None = None) -> int:
f"{statements} statements touch {len(inv.tables)} tenant-scoped tables "
f"({len(inv.tables) - len(inv.tables & inv.rls_tables)} of them with no RLS policy)"
)
+ 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."
+ )
if len(RATCHET) > MAX_RATCHET:
print(
diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.json
index 634ece853..06122f20a 100644
--- a/scripts/mypy_baseline.json
+++ b/scripts/mypy_baseline.json
@@ -604,6 +604,9 @@
},
"alembic/versions/0001_initial_honeytoken_tables.py": {
"attr-defined": 1
+ },
+ "alembic/versions/0002_tenant_rls.py": {
+ "attr-defined": 1
}
},
"services/mesh": {},
@@ -622,6 +625,9 @@
"alembic/versions/0002_detection_drift_snapshots.py": {
"attr-defined": 1
},
+ "alembic/versions/0003_tenant_rls.py": {
+ "attr-defined": 1
+ },
"app/services/atomic_loader.py": {
"import-untyped": 1
}
@@ -650,6 +656,9 @@
},
"alembic/versions/0001_initial_ueba_tables.py": {
"attr-defined": 1
+ },
+ "alembic/versions/0002_tenant_rls.py": {
+ "attr-defined": 1
}
}
}
diff --git a/services/agents/app/hunt/store.py b/services/agents/app/hunt/store.py
index 3e0fe951b..fd0c5a83e 100644
--- a/services/agents/app/hunt/store.py
+++ b/services/agents/app/hunt/store.py
@@ -71,7 +71,13 @@ async def _resolve_tenant_id(conn: asyncpg.Connection, tenant_ref: str) -> uuid.
async def _set_rls_context(conn: asyncpg.Connection, tenant_id: uuid.UUID) -> None:
- await conn.execute("SELECT set_config('app.tenant_id', $1, true)", str(tenant_id))
+ """Bind this connection to one tenant for the enclosing transaction.
+
+ ``app.current_tenant_id`` is the variable every policy in this schema
+ reads; this said ``app.tenant_id`` until 2026-09, so the scope was never
+ applied. See the note in ``app/investigator/ledger.py``.
+ """
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))
# ---------------------------------------------------------------------------
diff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.py
index 696e5277d..114d0106d 100644
--- a/services/agents/app/investigator/ledger.py
+++ b/services/agents/app/investigator/ledger.py
@@ -150,8 +150,16 @@ async def resolve_tenant(tenant_ref: str) -> uuid.UUID | None:
async def _set_rls_context(conn: asyncpg.Connection, tenant_id: uuid.UUID) -> None:
"""Match the API service's set_rls_context — required so the audit-log
- immutability trigger and tenant policies allow our INSERTs."""
- await conn.execute("SELECT set_config('app.tenant_id', $1, true)", str(tenant_id))
+ immutability trigger and tenant policies allow our INSERTs.
+
+ The variable is ``app.current_tenant_id``. It said ``app.tenant_id`` until
+ 2026-09, which is a name no policy in this schema reads, so the scoping
+ this function exists to provide was never applied: every policy fell
+ through its ``current_tenant_id() IS NULL`` arm and admitted everything.
+ Nothing failed, because failing open is what an unset context does — and
+ because the role the services connect as bypasses RLS outright.
+ """
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))
async def start_run(
diff --git a/services/agents/app/investigator/splunk_evidence.py b/services/agents/app/investigator/splunk_evidence.py
index b6b60b44d..7bf6e0b31 100644
--- a/services/agents/app/investigator/splunk_evidence.py
+++ b/services/agents/app/investigator/splunk_evidence.py
@@ -207,7 +207,10 @@ async def resolve_splunk_credentials(state: InvestigationState) -> SplunkCreds |
return None
try:
async with pool.acquire() as conn:
- await conn.execute("SELECT set_config('app.tenant_id', $1, true)", str(state.tenant_id))
+ # app.current_tenant_id is the variable the connectors policy
+ # reads; this said app.tenant_id until 2026-09. See
+ # app/investigator/ledger.py.
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(state.tenant_id))
row = await conn.fetchrow(
"""
SELECT auth_config, connector_config
diff --git a/services/agents/app/security/llm_resolver.py b/services/agents/app/security/llm_resolver.py
index fdc74edc6..9e6c69489 100644
--- a/services/agents/app/security/llm_resolver.py
+++ b/services/agents/app/security/llm_resolver.py
@@ -235,8 +235,12 @@ async def _resolve_tenant_uuid(conn: asyncpg.Connection, tenant_ref: str) -> uui
async def _set_rls_context(conn: asyncpg.Connection, tenant_id: uuid.UUID) -> None:
- """Set the RLS GUC so policies on ``tenant_llm_credentials`` admit us."""
- await conn.execute("SELECT set_config('app.tenant_id', $1, true)", str(tenant_id))
+ """Set the RLS GUC so policies on ``tenant_llm_credentials`` admit us.
+
+ ``app.current_tenant_id`` is the variable that table's policy reads; this
+ said ``app.tenant_id`` until 2026-09. See ``app/investigator/ledger.py``.
+ """
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))
async def _fetch_tenant_credential(pool: asyncpg.Pool, tenant_ref: str) -> dict[str, Any] | None:
diff --git a/services/agents/tests/test_graph_freshness.py b/services/agents/tests/test_graph_freshness.py
index a8d66938b..86079ee78 100644
--- a/services/agents/tests/test_graph_freshness.py
+++ b/services/agents/tests/test_graph_freshness.py
@@ -67,6 +67,39 @@ def _import_or_skip(mod_name: str, hint: str) -> Any:
return None # unreachable; pytest.skip raises, but keeps return paths consistent
+def _require_ingest_service(httpx: Any) -> None:
+ """Skip unless the thing on ``INGEST_BASE_URL`` really is the ingest service.
+
+ ``AISOC_INGEST_URL`` defaults to ``http://localhost:8080``, which is the
+ single most contended port on a developer machine. The suite's only
+ escape hatch was a connection exception, so *anything* that answered was
+ treated as ingest: a local gateway returning
+ ``401 {"detail":"node credential required"}`` became a test failure
+ reading "fusion should never block on graph", which is neither what
+ happened nor anybody's bug.
+
+ ``GET /health`` on the real service returns ``{"status":"ok",
+ "service":"ingest"}`` (``services/ingest/internal/handler/handler.go``),
+ so identity is checkable rather than assumed. A skip here names what
+ answered, because "skipped" with no reason is how a suite quietly stops
+ testing anything.
+ """
+ try:
+ resp = httpx.get(f"{INGEST_BASE_URL}/health", timeout=2.0)
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"no service answering at {INGEST_BASE_URL}: {exc}")
+ return
+ try:
+ service = resp.json().get("service")
+ except (ValueError, AttributeError):
+ service = None
+ if resp.status_code != 200 or service != "ingest":
+ pytest.skip(
+ f"{INGEST_BASE_URL}/health answered {resp.status_code} as service={service!r}, not the AiSOC "
+ "ingest service — something else owns that port. Set AISOC_INGEST_URL to the real one."
+ )
+
+
def _build_event(idx: int) -> dict:
"""Synthetic AWS Security Hub event with deterministic natural keys."""
return {
@@ -136,6 +169,7 @@ def test_graph_freshness_p95_under_2s() -> None:
"""
httpx = _import_or_skip("httpx", "`pip install httpx`")
neo4j_pkg = _import_or_skip("neo4j", "`pip install neo4j>=5`")
+ _require_ingest_service(httpx)
tenant = f"test-{uuid.uuid4().hex[:8]}"
@@ -190,6 +224,7 @@ def test_graph_writer_does_not_block_fusion_on_failure() -> None:
Marked integration so it runs in CI alongside the freshness probe.
"""
httpx = _import_or_skip("httpx", "`pip install httpx`")
+ _require_ingest_service(httpx)
tenant = f"failtest-{uuid.uuid4().hex[:8]}"
event = _build_event(0)
diff --git a/services/agents/tests/test_router_report.py b/services/agents/tests/test_router_report.py
index 712868a01..e696c5299 100644
--- a/services/agents/tests/test_router_report.py
+++ b/services/agents/tests/test_router_report.py
@@ -190,7 +190,21 @@ def test_markdown_renders_without_info_dict() -> None:
def test_html_wraps_markdown_with_document_chrome() -> None:
- """The HTML output is a full document with the case id in the title."""
+ """The HTML output is a full document with the case id in the title.
+
+ The ``<h1>``/``<table>`` assertions are about what the ``markdown``
+ library produces, so without it this asserted the ``<pre>`` fallback's
+ output against the rendered form and failed. ``markdown`` is a declared
+ dependency of this service (``pyproject.toml``: ``markdown = "^3.5"``) and
+ is installed in CI, so a missing one means an incomplete environment
+ rather than a defect — hence a skip that says so, not a red test nobody
+ reads. The fallback branch has its own coverage immediately below.
+ """
+ pytest.importorskip(
+ "markdown",
+ reason="markdown is a declared agents dependency; these assertions are about its rendering, "
+ "and the <pre> fallback is covered by test_html_fallback_when_markdown_module_missing",
+ )
md = "# Incident Report — case-42\n\n## Summary\n\n| Field | Value |\n|---|---|\n| Verdict | tp |\n"
html = render_router_report_html(md, case_id="case-42")
@@ -257,6 +271,14 @@ def test_findings_with_html_tags_are_escaped() -> None:
pipeline (``render_router_report_md`` → ``markdown.markdown``) must
escape these so a payload like ``<script>alert(1)</script>`` ships as
literal text rather than an executable script tag.
+
+ The property holds on both rendering branches, so this asserts it on
+ whichever one ran. It used to require the literal ``&lt;script&gt;`` in
+ the HTML, which only the ``markdown`` branch produces: the ``<pre>``
+ fallback escapes the already-escaped Markdown body a second time and
+ emits ``&amp;lt;script&amp;gt;``. That is *more* escaped, not less, so the
+ old assertion failed on a branch that was behaving correctly — a
+ misleading red for a payload that was never executable either way.
"""
payload = "<script>alert('xss')</script>"
state = _build_state(findings=[payload])
@@ -266,10 +288,16 @@ def test_findings_with_html_tags_are_escaped() -> None:
# Markdown body keeps the escaped form, not the raw tag
assert "<script>" not in md
assert "&lt;script&gt;" in md
- # Rendered HTML must not contain an executable script tag derived
- # from the finding
+ # The property that matters, and it is branch-independent: nothing a
+ # finding carried can reach the document as an executable tag.
assert "<script>alert" not in html_out
- assert "&lt;script&gt;" in html_out
+ assert "<script>" not in html_out
+ # The payload is still *present*, escaped, so this is not passing because
+ # the finding was silently dropped.
+ assert "script" in html_out
+ # Either branch's escaping is acceptable; naming both keeps the assertion
+ # honest about which one ran rather than skipping the fallback.
+ assert "&lt;script&gt;" in html_out or "&amp;lt;script&amp;gt;" in html_out
def test_error_field_with_html_is_escaped() -> None:
diff --git a/services/api/migrations/060_rls_coverage.sql b/services/api/migrations/060_rls_coverage.sql
new file mode 100644
index 000000000..89e62b9f3
--- /dev/null
+++ b/services/api/migrations/060_rls_coverage.sql
@@ -0,0 +1,471 @@
+-- Row-level security for every tenant-scoped table in this chain, and a
+-- repair for the seven policies that were wired to a session variable
+-- nothing sets.
+--
+-- Why this migration exists
+-- -------------------------
+-- The repository's stated design is that tenant isolation is enforced at the
+-- query layer *with RLS as defence in depth*. Measured against the tree, 31 of
+-- 95 tenant-scoped tables carried a policy. On the other 64 the query
+-- predicate was the only thing between two customers, so one missing
+-- ``WHERE tenant_id`` was a leak rather than something a second layer caught.
+-- 002_rls.sql covered six tables and every migration since added tables
+-- without adding policies.
+--
+-- What this does NOT change
+-- -------------------------
+-- The query predicate stays the primary control. Nothing here relaxes a
+-- filter, and ``scripts/check_tenant_query_predicates.py`` still requires one
+-- on every statement. Two independent layers is the point; this is the second.
+--
+-- Seven policies that were already wrong
+-- --------------------------------------
+-- Verified against postgres:16-alpine as a non-superuser, fresh session, no
+-- tenant context — i.e. exactly how a background worker connects:
+--
+-- external_assets, external_asset_drift current_setting('app.current_tenant_id')
+-- with no missing_ok argument, so the
+-- query raises
+-- "unrecognized configuration parameter"
+-- instead of returning rows.
+-- alert_sla_events, tenant_sla_config read app.tenant_id — a GUC no code
+-- path sets — so they return zero rows.
+-- custom_parsers, retention_policies read app.current_tenant, same.
+-- compliance_evidence reads the right GUC but has no
+-- "IS NULL" arm, so an unset context
+-- returns zero rows.
+--
+-- None of this was observable because the application bypasses RLS entirely
+-- (see below), which is precisely why a policy nobody exercises is worse than
+-- no policy: it reads as protection in a schema dump.
+--
+-- The canonical predicate
+-- -----------------------
+-- USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)
+--
+-- ``current_tenant_id()`` (002_rls.sql) reads app.current_tenant_id and
+-- returns NULL when it is unset. The "OR ... IS NULL" arm is deliberate and
+-- pre-existing: a session that never ran ``SET LOCAL app.current_tenant_id``
+-- sees everything, because the ingest, fusion, scheduler and purge workers all
+-- operate cross-tenant by design and would otherwise silently process nothing.
+-- Fail-open on an unset context, fail-closed on a set one.
+--
+-- Read this as the honest statement of the guarantee: RLS engages only on a
+-- session that established a tenant. Those are ``TenantDBSession`` in the API,
+-- ``_set_rls_context`` in the agents ledger / hunt store / LLM resolver, and
+-- the per-hunt rebind in the hunt scheduler. On every other connection these
+-- policies are inert by design and the query predicate is the only control.
+--
+-- The role the application connects as
+-- ------------------------------------
+-- A superuser, or a role with BYPASSRLS, ignores policies even with FORCE ROW
+-- LEVEL SECURITY. docker-compose and the CI services both run the API as
+-- POSTGRES_USER=aisoc, which the postgres image creates as a superuser, so
+-- today **every policy in this database — the 31 that existed and the 49 added
+-- here — is bypassed**. Measured, not assumed: with two alerts seeded one per
+-- tenant and the context set to tenant A, `aisoc` sees 2 and `aisoc_app` sees 1.
+--
+-- This migration does not change the connection role, because doing so needs a
+-- password and a grant review that belong to a deployment, not to a schema
+-- change. It makes the policies correct and provable so that switching the
+-- role is the only remaining step. ``apps/docs/docs/operations/security.md``
+-- documents that step, and tests/isolation/test_postgres_rls.py proves the
+-- policies isolate by connecting as a non-superuser.
+--
+-- Excluded on purpose
+-- -------------------
+-- users 002_rls.sql excluded it so authentication can resolve a
+-- principal before any tenant exists, and platform-admin user
+-- administration in tenants.py is cross-tenant by design. Both
+-- still read through a plain session, so a policy here would be
+-- inert anyway — but stating the exclusion is better than leaving
+-- a reader to infer it from an absence.
+-- tenants has no tenant_id column; it is the tenant.
+--
+-- Two API ORM models — case_tasks, case_timeline — declare a tenant_id but no
+-- migration creates their tables, so there is nothing here to protect. They
+-- are reported by the isolation suite rather than silently skipped.
+
+-- ─── 1. Repair the policies that read a session variable nothing sets ────────
+-- Dropped by the name each migration actually used: these predate the
+-- <table>_tenant convention and carry four different names between them.
+
+DROP POLICY IF EXISTS tenant_isolation ON alert_sla_events;
+DROP POLICY IF EXISTS alert_sla_events_tenant ON alert_sla_events;
+ALTER TABLE alert_sla_events ENABLE ROW LEVEL SECURITY;
+ALTER TABLE alert_sla_events FORCE ROW LEVEL SECURITY;
+CREATE POLICY alert_sla_events_tenant ON alert_sla_events
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS compliance_evidence_tenant_isolation ON compliance_evidence;
+DROP POLICY IF EXISTS compliance_evidence_tenant ON compliance_evidence;
+ALTER TABLE compliance_evidence ENABLE ROW LEVEL SECURITY;
+ALTER TABLE compliance_evidence FORCE ROW LEVEL SECURITY;
+CREATE POLICY compliance_evidence_tenant ON compliance_evidence
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS custom_parsers_tenant ON custom_parsers;
+ALTER TABLE custom_parsers ENABLE ROW LEVEL SECURITY;
+ALTER TABLE custom_parsers FORCE ROW LEVEL SECURITY;
+CREATE POLICY custom_parsers_tenant ON custom_parsers
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS easm_drift_tenant_isolation ON external_asset_drift;
+DROP POLICY IF EXISTS external_asset_drift_tenant ON external_asset_drift;
+ALTER TABLE external_asset_drift ENABLE ROW LEVEL SECURITY;
+ALTER TABLE external_asset_drift FORCE ROW LEVEL SECURITY;
+CREATE POLICY external_asset_drift_tenant ON external_asset_drift
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS easm_tenant_isolation ON external_assets;
+DROP POLICY IF EXISTS external_assets_tenant ON external_assets;
+ALTER TABLE external_assets ENABLE ROW LEVEL SECURITY;
+ALTER TABLE external_assets FORCE ROW LEVEL SECURITY;
+CREATE POLICY external_assets_tenant ON external_assets
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS retention_policies_tenant ON retention_policies;
+ALTER TABLE retention_policies ENABLE ROW LEVEL SECURITY;
+ALTER TABLE retention_policies FORCE ROW LEVEL SECURITY;
+CREATE POLICY retention_policies_tenant ON retention_policies
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+DROP POLICY IF EXISTS tenant_isolation ON tenant_sla_config;
+DROP POLICY IF EXISTS tenant_sla_config_tenant ON tenant_sla_config;
+ALTER TABLE tenant_sla_config ENABLE ROW LEVEL SECURITY;
+ALTER TABLE tenant_sla_config FORCE ROW LEVEL SECURITY;
+CREATE POLICY tenant_sla_config_tenant ON tenant_sla_config
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+-- ─── 2. A policy on every remaining tenant-scoped table in this chain ────────
+
+ALTER TABLE aisoc_action_records ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_action_records FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_action_records_tenant ON aisoc_action_records;
+CREATE POLICY aisoc_action_records_tenant ON aisoc_action_records
+ USING (tenant_id = current_tenant_id()::text OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_analyst_feedback ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_analyst_feedback FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_analyst_feedback_tenant ON aisoc_analyst_feedback;
+CREATE POLICY aisoc_analyst_feedback_tenant ON aisoc_analyst_feedback
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_autonomy_thresholds ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_autonomy_thresholds FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_autonomy_thresholds_tenant ON aisoc_autonomy_thresholds;
+CREATE POLICY aisoc_autonomy_thresholds_tenant ON aisoc_autonomy_thresholds
+ USING (tenant_id = current_tenant_id()::text OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_business_context_rule_sets ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_business_context_rule_sets FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_business_context_rule_sets_tenant ON aisoc_business_context_rule_sets;
+CREATE POLICY aisoc_business_context_rule_sets_tenant ON aisoc_business_context_rule_sets
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_case_comments ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_case_comments FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_case_comments_tenant ON aisoc_case_comments;
+CREATE POLICY aisoc_case_comments_tenant ON aisoc_case_comments
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_case_tasks ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_case_tasks FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_case_tasks_tenant ON aisoc_case_tasks;
+CREATE POLICY aisoc_case_tasks_tenant ON aisoc_case_tasks
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_cases ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_cases FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_cases_tenant ON aisoc_cases;
+CREATE POLICY aisoc_cases_tenant ON aisoc_cases
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_compliance_evidence ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_compliance_evidence FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_compliance_evidence_tenant ON aisoc_compliance_evidence;
+CREATE POLICY aisoc_compliance_evidence_tenant ON aisoc_compliance_evidence
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_context_statements ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_context_statements FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_context_statements_tenant ON aisoc_context_statements;
+CREATE POLICY aisoc_context_statements_tenant ON aisoc_context_statements
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_dead_letters ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_dead_letters FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_dead_letters_tenant ON aisoc_dead_letters;
+CREATE POLICY aisoc_dead_letters_tenant ON aisoc_dead_letters
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_hunt_runs ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_hunt_runs FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_hunt_runs_tenant ON aisoc_hunt_runs;
+CREATE POLICY aisoc_hunt_runs_tenant ON aisoc_hunt_runs
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_hunts ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_hunts FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_hunts_tenant ON aisoc_hunts;
+CREATE POLICY aisoc_hunts_tenant ON aisoc_hunts
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_institutional_memory ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_institutional_memory FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_institutional_memory_tenant ON aisoc_institutional_memory;
+CREATE POLICY aisoc_institutional_memory_tenant ON aisoc_institutional_memory
+ USING (tenant_id = current_tenant_id()::text OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_kb_documents ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_kb_documents FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_kb_documents_tenant ON aisoc_kb_documents;
+CREATE POLICY aisoc_kb_documents_tenant ON aisoc_kb_documents
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_outcome_suppressions ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_outcome_suppressions FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_outcome_suppressions_tenant ON aisoc_outcome_suppressions;
+CREATE POLICY aisoc_outcome_suppressions_tenant ON aisoc_outcome_suppressions
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_phishing_submissions ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_phishing_submissions FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_phishing_submissions_tenant ON aisoc_phishing_submissions;
+CREATE POLICY aisoc_phishing_submissions_tenant ON aisoc_phishing_submissions
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE aisoc_run_costs ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_run_costs FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_run_costs_tenant ON aisoc_run_costs;
+CREATE POLICY aisoc_run_costs_tenant ON aisoc_run_costs
+ USING (tenant_id = current_tenant_id()::text OR current_tenant_id() IS NULL);
+
+ALTER TABLE alert_asset_correlations ENABLE ROW LEVEL SECURITY;
+ALTER TABLE alert_asset_correlations FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS alert_asset_correlations_tenant ON alert_asset_correlations;
+CREATE POLICY alert_asset_correlations_tenant ON alert_asset_correlations
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE alert_identity_links ENABLE ROW LEVEL SECURITY;
+ALTER TABLE alert_identity_links FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS alert_identity_links_tenant ON alert_identity_links;
+CREATE POLICY alert_identity_links_tenant ON alert_identity_links
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE asset_vulnerabilities ENABLE ROW LEVEL SECURITY;
+ALTER TABLE asset_vulnerabilities FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS asset_vulnerabilities_tenant ON asset_vulnerabilities;
+CREATE POLICY asset_vulnerabilities_tenant ON asset_vulnerabilities
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE assets ENABLE ROW LEVEL SECURITY;
+ALTER TABLE assets FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS assets_tenant ON assets;
+CREATE POLICY assets_tenant ON assets
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE case_timeline_events ENABLE ROW LEVEL SECURITY;
+ALTER TABLE case_timeline_events FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS case_timeline_events_tenant ON case_timeline_events;
+CREATE POLICY case_timeline_events_tenant ON case_timeline_events
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE identity_edges ENABLE ROW LEVEL SECURITY;
+ALTER TABLE identity_edges FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS identity_edges_tenant ON identity_edges;
+CREATE POLICY identity_edges_tenant ON identity_edges
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE identity_nodes ENABLE ROW LEVEL SECURITY;
+ALTER TABLE identity_nodes FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS identity_nodes_tenant ON identity_nodes;
+CREATE POLICY identity_nodes_tenant ON identity_nodes
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE insider_indicators ENABLE ROW LEVEL SECURITY;
+ALTER TABLE insider_indicators FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS insider_indicators_tenant ON insider_indicators;
+CREATE POLICY insider_indicators_tenant ON insider_indicators
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE insider_peer_groups ENABLE ROW LEVEL SECURITY;
+ALTER TABLE insider_peer_groups FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS insider_peer_groups_tenant ON insider_peer_groups;
+CREATE POLICY insider_peer_groups_tenant ON insider_peer_groups
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE marketplace_entitlements ENABLE ROW LEVEL SECURITY;
+ALTER TABLE marketplace_entitlements FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS marketplace_entitlements_tenant ON marketplace_entitlements;
+CREATE POLICY marketplace_entitlements_tenant ON marketplace_entitlements
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE marketplace_installs ENABLE ROW LEVEL SECURITY;
+ALTER TABLE marketplace_installs FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS marketplace_installs_tenant ON marketplace_installs;
+CREATE POLICY marketplace_installs_tenant ON marketplace_installs
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE marketplace_publishers ENABLE ROW LEVEL SECURITY;
+ALTER TABLE marketplace_publishers FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS marketplace_publishers_tenant ON marketplace_publishers;
+CREATE POLICY marketplace_publishers_tenant ON marketplace_publishers
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE marketplace_submissions ENABLE ROW LEVEL SECURITY;
+ALTER TABLE marketplace_submissions FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS marketplace_submissions_tenant ON marketplace_submissions;
+CREATE POLICY marketplace_submissions_tenant ON marketplace_submissions
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE mssp_tenant_metrics ENABLE ROW LEVEL SECURITY;
+ALTER TABLE mssp_tenant_metrics FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS mssp_tenant_metrics_tenant ON mssp_tenant_metrics;
+CREATE POLICY mssp_tenant_metrics_tenant ON mssp_tenant_metrics
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE oauth_app_credentials ENABLE ROW LEVEL SECURITY;
+ALTER TABLE oauth_app_credentials FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS oauth_app_credentials_tenant ON oauth_app_credentials;
+CREATE POLICY oauth_app_credentials_tenant ON oauth_app_credentials
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE oauth_states ENABLE ROW LEVEL SECURITY;
+ALTER TABLE oauth_states FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS oauth_states_tenant ON oauth_states;
+CREATE POLICY oauth_states_tenant ON oauth_states
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE organization_member_tenants ENABLE ROW LEVEL SECURITY;
+ALTER TABLE organization_member_tenants FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS organization_member_tenants_tenant ON organization_member_tenants;
+CREATE POLICY organization_member_tenants_tenant ON organization_member_tenants
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE organization_tenants ENABLE ROW LEVEL SECURITY;
+ALTER TABLE organization_tenants FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS organization_tenants_tenant ON organization_tenants;
+CREATE POLICY organization_tenants_tenant ON organization_tenants
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE passkey_challenges ENABLE ROW LEVEL SECURITY;
+ALTER TABLE passkey_challenges FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS passkey_challenges_tenant ON passkey_challenges;
+CREATE POLICY passkey_challenges_tenant ON passkey_challenges
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE posture_drift_events ENABLE ROW LEVEL SECURITY;
+ALTER TABLE posture_drift_events FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS posture_drift_events_tenant ON posture_drift_events;
+CREATE POLICY posture_drift_events_tenant ON posture_drift_events
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE posture_findings ENABLE ROW LEVEL SECURITY;
+ALTER TABLE posture_findings FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS posture_findings_tenant ON posture_findings;
+CREATE POLICY posture_findings_tenant ON posture_findings
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE posture_scan_runs ENABLE ROW LEVEL SECURITY;
+ALTER TABLE posture_scan_runs FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS posture_scan_runs_tenant ON posture_scan_runs;
+CREATE POLICY posture_scan_runs_tenant ON posture_scan_runs
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE published_replays ENABLE ROW LEVEL SECURITY;
+ALTER TABLE published_replays FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS published_replays_tenant ON published_replays;
+CREATE POLICY published_replays_tenant ON published_replays
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE remediation_gate_log ENABLE ROW LEVEL SECURITY;
+ALTER TABLE remediation_gate_log FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS remediation_gate_log_tenant ON remediation_gate_log;
+CREATE POLICY remediation_gate_log_tenant ON remediation_gate_log
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE remediation_maturity ENABLE ROW LEVEL SECURITY;
+ALTER TABLE remediation_maturity FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS remediation_maturity_tenant ON remediation_maturity;
+CREATE POLICY remediation_maturity_tenant ON remediation_maturity
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE remediation_whitelist ENABLE ROW LEVEL SECURITY;
+ALTER TABLE remediation_whitelist FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS remediation_whitelist_tenant ON remediation_whitelist;
+CREATE POLICY remediation_whitelist_tenant ON remediation_whitelist
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE report_artefacts ENABLE ROW LEVEL SECURITY;
+ALTER TABLE report_artefacts FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS report_artefacts_tenant ON report_artefacts;
+CREATE POLICY report_artefacts_tenant ON report_artefacts
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE report_templates ENABLE ROW LEVEL SECURITY;
+ALTER TABLE report_templates FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS report_templates_tenant ON report_templates;
+CREATE POLICY report_templates_tenant ON report_templates
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE threat_actors ENABLE ROW LEVEL SECURITY;
+ALTER TABLE threat_actors FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS threat_actors_tenant ON threat_actors;
+CREATE POLICY threat_actors_tenant ON threat_actors
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE threat_intel_feeds ENABLE ROW LEVEL SECURITY;
+ALTER TABLE threat_intel_feeds FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS threat_intel_feeds_tenant ON threat_intel_feeds;
+CREATE POLICY threat_intel_feeds_tenant ON threat_intel_feeds
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE threat_intel_iocs ENABLE ROW LEVEL SECURITY;
+ALTER TABLE threat_intel_iocs FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS threat_intel_iocs_tenant ON threat_intel_iocs;
+CREATE POLICY threat_intel_iocs_tenant ON threat_intel_iocs
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+ALTER TABLE user_risk_profiles ENABLE ROW LEVEL SECURITY;
+ALTER TABLE user_risk_profiles FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS user_risk_profiles_tenant ON user_risk_profiles;
+CREATE POLICY user_risk_profiles_tenant ON user_risk_profiles
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+-- ─── 3. Refuse to finish having protected less than was claimed ─────────────
+--
+-- Spelled out above as 56 literal ALTER/CREATE POLICY statements rather than a
+-- loop over information_schema, for two reasons. A reviewer can see exactly
+-- which tables were given a policy and with which predicate; and
+-- ``scripts/check_tenant_query_predicates.py`` derives its RLS inventory by
+-- reading these files, so a policy created inside a PL/pgSQL EXECUTE is a
+-- policy the gate cannot see — it would go on reporting 64 unprotected tables
+-- while the database had 1.
+--
+-- This block asserts the outcome rather than repeating the list: every table
+-- in this database that carries a tenant_id must now have RLS, FORCE and a
+-- policy, or the migration fails and nothing is recorded as applied.
+
+DO $$
+DECLARE
+ gap text;
+BEGIN
+ SELECT string_agg(c.relname, ', ' ORDER BY c.relname) INTO gap
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public'
+ AND c.relkind = 'r'
+ AND c.relname <> 'users'
+ AND EXISTS (SELECT 1 FROM pg_attribute a
+ WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND NOT a.attisdropped)
+ AND (NOT c.relrowsecurity
+ OR NOT c.relforcerowsecurity
+ OR NOT EXISTS (SELECT 1 FROM pg_policies p
+ WHERE p.schemaname = 'public' AND p.tablename = c.relname));
+ IF gap IS NOT NULL THEN
+ RAISE EXCEPTION
+ '060_rls_coverage: these tenant-scoped tables still lack RLS, FORCE or a policy: %', gap;
+ END IF;
+END
+$$;
diff --git a/services/api/tests/test_hunt_scheduler_cron.py b/services/api/tests/test_hunt_scheduler_cron.py
index 55c7d4767..b79e83499 100644
--- a/services/api/tests/test_hunt_scheduler_cron.py
+++ b/services/api/tests/test_hunt_scheduler_cron.py
@@ -14,7 +14,7 @@ landed yet.
from __future__ import annotations
import uuid
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any
from unittest.mock import MagicMock
@@ -74,12 +74,29 @@ class TestNextFireAt:
"""The helper used by ``_is_due`` to step a single tick forward."""
def test_basic_hourly(self) -> None:
- next_at = hunt_scheduler._next_fire_at(
- "0 * * * *",
- after=datetime(2026, 5, 15, 12, 30, tzinfo=UTC),
- )
+ """Both branches, each against the contract it actually has.
+
+ This asserted the croniter answer unconditionally while sitting
+ outside the ``_CRONITER_AVAILABLE`` guard one class up, so it failed
+ — not skipped, failed — in any environment without the dependency.
+ It is not an environmental failure: the fallback has a defined
+ behaviour and nothing was checking it, so the fix is to assert the
+ right thing on each path rather than to skip one of them.
+
+ croniter aligns to the cron expression, giving the top of the next
+ hour. The fallback is an interval stepper, not a parser, so it
+ advances one cadence from ``after`` and lands at :30. A hunt on the
+ fallback path therefore drifts off the hour — which is the documented
+ cost of running without croniter, and is now visible here.
+ """
+ after = datetime(2026, 5, 15, 12, 30, tzinfo=UTC)
+ next_at = hunt_scheduler._next_fire_at("0 * * * *", after=after)
assert next_at is not None
- assert next_at == datetime(2026, 5, 15, 13, 0, tzinfo=UTC)
+
+ if hunt_scheduler._CRONITER_AVAILABLE:
+ assert next_at == datetime(2026, 5, 15, 13, 0, tzinfo=UTC)
+ else:
+ assert next_at == after + timedelta(seconds=3600)
def test_invalid_schedule_returns_none(self) -> None:
assert hunt_scheduler._next_fire_at("not a schedule", after=datetime.now(UTC)) is None
diff --git a/services/honeytokens/alembic/__init__.py b/services/honeytokens/alembic/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/services/honeytokens/alembic/env.py b/services/honeytokens/alembic/env.py
index ccaa2b36d..f85e84b64 100644
--- a/services/honeytokens/alembic/env.py
+++ b/services/honeytokens/alembic/env.py
@@ -6,11 +6,10 @@ import asyncio
import os
from logging.config import fileConfig
+from alembic import context
from app.models.honeytoken import Base
from sqlalchemy.ext.asyncio import create_async_engine
-from alembic import context
-
config = context.config
if config.config_file_name is not None:
diff --git a/services/honeytokens/alembic/versions/0001_initial_honeytoken_tables.py b/services/honeytokens/alembic/versions/0001_initial_honeytoken_tables.py
index 91faf75d0..449702caa 100644
--- a/services/honeytokens/alembic/versions/0001_initial_honeytoken_tables.py
+++ b/services/honeytokens/alembic/versions/0001_initial_honeytoken_tables.py
@@ -8,9 +8,8 @@ Create Date: 2026-05-03
from __future__ import annotations
import sqlalchemy as sa
-from sqlalchemy.dialects.postgresql import JSONB, UUID
-
from alembic import op
+from sqlalchemy.dialects.postgresql import JSONB, UUID
revision = "0001"
down_revision = None
diff --git a/services/honeytokens/alembic/versions/0002_tenant_rls.py b/services/honeytokens/alembic/versions/0002_tenant_rls.py
new file mode 100644
index 000000000..a89d2d851
--- /dev/null
+++ b/services/honeytokens/alembic/versions/0002_tenant_rls.py
@@ -0,0 +1,75 @@
+"""Row-level security on the honeytoken tables.
+
+Revision ID: 0002
+Revises: 0001
+Create Date: 2026-09-24
+
+Companion to ``services/api/migrations/060_rls_coverage.sql``. This service
+shares one Postgres database with the API but manages its own schema, so its
+two tenant-scoped tables were outside that chain's reach and carried no policy.
+
+The predicate is spelled inline rather than calling ``current_tenant_id()``
+(defined by the API's 002_rls.sql) because nothing orders the two chains
+against each other: this revision can run against a database the API chain has
+not touched yet, and a policy that fails to create is a policy nobody has.
+
+Semantics match the API chain exactly — fail open on a session with no tenant
+context, fail closed on one that set it:
+
+ tenant_id = <context> OR <context> IS NULL
+
+Honest scope: this service never calls ``set_rls_context``, so on its own
+connections the context is always unset and these policies are inert by
+design. They engage for any other service that reads these tables through a
+tenant-scoped session, and they stop being bypassed the moment the deployment
+connects as a role without BYPASSRLS. See
+``apps/docs/docs/operations/security.md``.
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "0002"
+down_revision = "0001"
+branch_labels = None
+depends_on = None
+
+# Spelled out one table at a time rather than looped over a tuple:
+# scripts/check_tenant_query_predicates.py derives which tables carry a
+# policy by reading migration text, and a table name that only exists as
+# a Python variable is a policy the gate cannot see.
+
+
+def upgrade() -> None:
+ op.execute("ALTER TABLE honeytokens ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE honeytokens FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS honeytokens_tenant ON honeytokens")
+ op.execute(
+ "CREATE POLICY honeytokens_tenant ON honeytokens "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE honeytoken_triggers ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE honeytoken_triggers FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS honeytoken_triggers_tenant ON honeytoken_triggers")
+ op.execute(
+ "CREATE POLICY honeytoken_triggers_tenant ON honeytoken_triggers "
+ "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() -> None:
+ op.execute("DROP POLICY IF EXISTS honeytokens_tenant ON honeytokens")
+ op.execute("ALTER TABLE honeytokens NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE honeytokens DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS honeytoken_triggers_tenant ON honeytoken_triggers")
+ op.execute("ALTER TABLE honeytoken_triggers NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE honeytoken_triggers DISABLE ROW LEVEL SECURITY")
diff --git a/services/osquery-tls/app/db/versions/004_tenant_rls.py b/services/osquery-tls/app/db/versions/004_tenant_rls.py
new file mode 100644
index 000000000..3530c9a2f
--- /dev/null
+++ b/services/osquery-tls/app/db/versions/004_tenant_rls.py
@@ -0,0 +1,102 @@
+"""Row-level security on the osquery-TLS tables.
+
+Revision ID: 004
+Revises: 003
+Create Date: 2026-09-24
+
+Companion to ``services/api/migrations/060_rls_coverage.sql``. This service
+shares one Postgres database with the API but manages its own schema, so its
+three tenant-scoped tables were outside that chain's reach and carried no
+policy.
+
+The predicate is spelled inline rather than calling ``current_tenant_id()``
+(defined by the API's 002_rls.sql) because nothing orders the two chains
+against each other: this revision can run against a database the API chain has
+not touched yet, and a policy that fails to create is a policy nobody has.
+
+Semantics match the API chain — fail open on a session with no tenant context,
+fail closed on one that set it:
+
+ tenant_id = <context> OR <context> IS NULL
+
+Two caveats, stated rather than left to be discovered:
+
+* ``tenant_id`` here is ``VARCHAR(64)``, not ``uuid``, and 001_init gives it
+ ``server_default='default'``. The comparison is therefore text-to-text, and
+ a row carrying the literal ``'default'`` will not match a session bound to a
+ UUID. That is a property of the column, not of the policy; re-typing it is a
+ data migration this revision deliberately does not attempt.
+* This service never calls ``set_rls_context``, so on its own connections the
+ context is always unset and these policies are inert by design. They engage
+ for any other service reading these tables through a tenant-scoped session,
+ and they stop being bypassed the moment the deployment connects as a role
+ without BYPASSRLS. See ``apps/docs/docs/operations/security.md``.
+
+The predicate is not the control here and was never meant to be: the
+node-registry lookups are keyed on the enrolment credential, and
+``get_query_by_id`` joins through ``osquery_node`` to reach a tenant. This adds
+the second layer under them.
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "004"
+down_revision = "003"
+branch_labels = None
+depends_on = None
+
+# Spelled out one table at a time rather than looped over a tuple:
+# scripts/check_tenant_query_predicates.py derives which tables carry a
+# policy by reading migration text, and a table name that only exists as
+# a Python variable is a policy the gate cannot see.
+
+
+def upgrade() -> None:
+ op.execute("ALTER TABLE osquery_node ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE osquery_node FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS osquery_node_tenant ON osquery_node")
+ op.execute(
+ "CREATE POLICY osquery_node_tenant ON osquery_node "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), '')) "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE osquery_pack_assignment ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE osquery_pack_assignment FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS osquery_pack_assignment_tenant ON osquery_pack_assignment")
+ op.execute(
+ "CREATE POLICY osquery_pack_assignment_tenant ON osquery_pack_assignment "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), '')) "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE fim_event ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE fim_event FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS fim_event_tenant ON fim_event")
+ op.execute(
+ "CREATE POLICY fim_event_tenant ON fim_event "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), '')) "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+
+def downgrade() -> None:
+ op.execute("DROP POLICY IF EXISTS osquery_node_tenant ON osquery_node")
+ op.execute("ALTER TABLE osquery_node NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE osquery_node DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS osquery_pack_assignment_tenant ON osquery_pack_assignment")
+ op.execute("ALTER TABLE osquery_pack_assignment NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE osquery_pack_assignment DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS fim_event_tenant ON fim_event")
+ op.execute("ALTER TABLE fim_event NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE fim_event DISABLE ROW LEVEL SECURITY")
diff --git a/services/purple-team/alembic/__init__.py b/services/purple-team/alembic/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/services/purple-team/alembic/env.py b/services/purple-team/alembic/env.py
index f169c164d..74a894b1b 100644
--- a/services/purple-team/alembic/env.py
+++ b/services/purple-team/alembic/env.py
@@ -6,11 +6,10 @@ import asyncio
import os
from logging.config import fileConfig
+from alembic import context
from app.models.purple_team import Base
from sqlalchemy.ext.asyncio import create_async_engine
-from alembic import context
-
config = context.config
if config.config_file_name is not None:
diff --git a/services/purple-team/alembic/versions/0001_initial_purple_team_tables.py b/services/purple-team/alembic/versions/0001_initial_purple_team_tables.py
index bfb1dfe06..c20bdf91e 100644
--- a/services/purple-team/alembic/versions/0001_initial_purple_team_tables.py
+++ b/services/purple-team/alembic/versions/0001_initial_purple_team_tables.py
@@ -8,9 +8,8 @@ Create Date: 2026-05-03
from __future__ import annotations
import sqlalchemy as sa
-from sqlalchemy.dialects.postgresql import JSONB, UUID
-
from alembic import op
+from sqlalchemy.dialects.postgresql import JSONB, UUID
revision = "0001"
down_revision = None
diff --git a/services/purple-team/alembic/versions/0002_detection_drift_snapshots.py b/services/purple-team/alembic/versions/0002_detection_drift_snapshots.py
index 1bf596dce..d549a1b1b 100644
--- a/services/purple-team/alembic/versions/0002_detection_drift_snapshots.py
+++ b/services/purple-team/alembic/versions/0002_detection_drift_snapshots.py
@@ -8,9 +8,8 @@ Create Date: 2026-05-05
from __future__ import annotations
import sqlalchemy as sa
-from sqlalchemy.dialects.postgresql import JSONB, UUID
-
from alembic import op
+from sqlalchemy.dialects.postgresql import JSONB, UUID
revision = "0002"
down_revision = "0001"
diff --git a/services/purple-team/alembic/versions/0003_tenant_rls.py b/services/purple-team/alembic/versions/0003_tenant_rls.py
new file mode 100644
index 000000000..e158716c9
--- /dev/null
+++ b/services/purple-team/alembic/versions/0003_tenant_rls.py
@@ -0,0 +1,106 @@
+"""Row-level security on the purple-team tables.
+
+Revision ID: 0003
+Revises: 0002
+Create Date: 2026-09-24
+
+Companion to ``services/api/migrations/060_rls_coverage.sql``. This service
+shares one Postgres database with the API but manages its own schema, so its
+four tenant-scoped tables were outside that chain's reach and carried no
+policy.
+
+The predicate is spelled inline rather than calling ``current_tenant_id()``
+(defined by the API's 002_rls.sql) because nothing orders the two chains
+against each other: this revision can run against a database the API chain has
+not touched yet, and a policy that fails to create is a policy nobody has.
+
+Semantics match the API chain exactly — fail open on a session with no tenant
+context, fail closed on one that set it:
+
+ tenant_id = <context> OR <context> IS NULL
+
+Honest scope: this service never calls ``set_rls_context``, so on its own
+connections the context is always unset and these policies are inert by
+design. They engage for any other service that reads these tables through a
+tenant-scoped session, and they stop being bypassed the moment the deployment
+connects as a role without BYPASSRLS. See
+``apps/docs/docs/operations/security.md``.
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "0003"
+down_revision = "0002"
+branch_labels = None
+depends_on = None
+
+# Spelled out one table at a time rather than looped over a tuple:
+# scripts/check_tenant_query_predicates.py derives which tables carry a
+# policy by reading migration text, and a table name that only exists as
+# a Python variable is a policy the gate cannot see.
+
+
+def upgrade() -> None:
+ op.execute("ALTER TABLE purple_team_atomic_tests ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE purple_team_atomic_tests FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS purple_team_atomic_tests_tenant ON purple_team_atomic_tests")
+ op.execute(
+ "CREATE POLICY purple_team_atomic_tests_tenant ON purple_team_atomic_tests "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE purple_team_executions ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE purple_team_executions FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS purple_team_executions_tenant ON purple_team_executions")
+ op.execute(
+ "CREATE POLICY purple_team_executions_tenant ON purple_team_executions "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE purple_team_tabletop_sessions ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE purple_team_tabletop_sessions FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS purple_team_tabletop_sessions_tenant ON purple_team_tabletop_sessions")
+ op.execute(
+ "CREATE POLICY purple_team_tabletop_sessions_tenant ON purple_team_tabletop_sessions "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE purple_team_detection_drift_snapshots ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE purple_team_detection_drift_snapshots FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS purple_team_detection_drift_snapshots_tenant ON purple_team_detection_drift_snapshots")
+ op.execute(
+ "CREATE POLICY purple_team_detection_drift_snapshots_tenant ON purple_team_detection_drift_snapshots "
+ "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() -> None:
+ op.execute("DROP POLICY IF EXISTS purple_team_atomic_tests_tenant ON purple_team_atomic_tests")
+ op.execute("ALTER TABLE purple_team_atomic_tests NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE purple_team_atomic_tests DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS purple_team_executions_tenant ON purple_team_executions")
+ op.execute("ALTER TABLE purple_team_executions NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE purple_team_executions DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS purple_team_tabletop_sessions_tenant ON purple_team_tabletop_sessions")
+ op.execute("ALTER TABLE purple_team_tabletop_sessions NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE purple_team_tabletop_sessions DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS purple_team_detection_drift_snapshots_tenant ON purple_team_detection_drift_snapshots")
+ op.execute("ALTER TABLE purple_team_detection_drift_snapshots NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE purple_team_detection_drift_snapshots DISABLE ROW LEVEL SECURITY")
diff --git a/services/ueba/alembic/versions/0002_tenant_rls.py b/services/ueba/alembic/versions/0002_tenant_rls.py
new file mode 100644
index 000000000..ff1671c19
--- /dev/null
+++ b/services/ueba/alembic/versions/0002_tenant_rls.py
@@ -0,0 +1,91 @@
+"""Row-level security on the UEBA tables.
+
+Revision ID: 0002
+Revises: 0001
+Create Date: 2026-09-24
+
+Companion to ``services/api/migrations/060_rls_coverage.sql``. This service
+shares one Postgres database with the API but manages its own schema, so its
+three tenant-scoped tables were outside that chain's reach and carried no
+policy.
+
+The predicate is spelled inline rather than calling ``current_tenant_id()``
+(defined by the API's 002_rls.sql) because nothing orders the two chains
+against each other: this revision can run against a database the API chain has
+not touched yet, and a policy that fails to create is a policy nobody has.
+
+Semantics match the API chain exactly — fail open on a session with no tenant
+context, fail closed on one that set it:
+
+ tenant_id = <context> OR <context> IS NULL
+
+Honest scope: this service never calls ``set_rls_context``, so on its own
+connections the context is always unset and these policies are inert by
+design. They engage for any other service that reads these tables through a
+tenant-scoped session, and they stop being bypassed the moment the deployment
+connects as a role without BYPASSRLS. See
+``apps/docs/docs/operations/security.md``.
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "0002"
+down_revision = "0001"
+branch_labels = None
+depends_on = None
+
+# Spelled out one table at a time rather than looped over a tuple:
+# scripts/check_tenant_query_predicates.py derives which tables carry a
+# policy by reading migration text, and a table name that only exists as
+# a Python variable is a policy the gate cannot see.
+
+
+def upgrade() -> None:
+ op.execute("ALTER TABLE ueba_entity_baselines ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE ueba_entity_baselines FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS ueba_entity_baselines_tenant ON ueba_entity_baselines")
+ op.execute(
+ "CREATE POLICY ueba_entity_baselines_tenant ON ueba_entity_baselines "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE ueba_anomalies ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE ueba_anomalies FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS ueba_anomalies_tenant ON ueba_anomalies")
+ op.execute(
+ "CREATE POLICY ueba_anomalies_tenant ON ueba_anomalies "
+ "USING (tenant_id = (NULLIF(current_setting('app.current_tenant_id', true), ''))::uuid "
+ "OR (NULLIF(current_setting('app.current_tenant_id', true), '')) IS NULL)"
+ )
+
+ op.execute("ALTER TABLE ueba_peer_groups ENABLE ROW LEVEL SECURITY")
+ # Without FORCE the table owner bypasses the policy, and this
+ # service owns the tables it created.
+ op.execute("ALTER TABLE ueba_peer_groups FORCE ROW LEVEL SECURITY")
+ op.execute("DROP POLICY IF EXISTS ueba_peer_groups_tenant ON ueba_peer_groups")
+ op.execute(
+ "CREATE POLICY ueba_peer_groups_tenant ON ueba_peer_groups "
+ "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() -> None:
+ op.execute("DROP POLICY IF EXISTS ueba_entity_baselines_tenant ON ueba_entity_baselines")
+ op.execute("ALTER TABLE ueba_entity_baselines NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE ueba_entity_baselines DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS ueba_anomalies_tenant ON ueba_anomalies")
+ op.execute("ALTER TABLE ueba_anomalies NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE ueba_anomalies DISABLE ROW LEVEL SECURITY")
+
+ op.execute("DROP POLICY IF EXISTS ueba_peer_groups_tenant ON ueba_peer_groups")
+ op.execute("ALTER TABLE ueba_peer_groups NO FORCE ROW LEVEL SECURITY")
+ op.execute("ALTER TABLE ueba_peer_groups DISABLE ROW LEVEL SECURITY")
diff --git a/tests/isolation/README.md b/tests/isolation/README.md
index e10ed8f7c..f44a92049 100644
--- a/tests/isolation/README.md
+++ b/tests/isolation/README.md
@@ -84,11 +84,44 @@ See `stores.py::STORES`. Each store is one of:
- `offline_gated` — query-construction isolation asserted here, every PR
(Qdrant).
-- `rls` — enforced by Postgres RLS + query-layer filters (tested in
+- `rls` — query-layer filters with Postgres RLS beneath them, replayed live in
+ `integration.yml` (`test_postgres_rls.py`, plus
`services/api/tests/test_*_tenant_isolation.py`).
- `container_gated` — live-container A-vs-B replay in `isolation-live.yml`
(Neo4j, Redis, ClickHouse, Kafka).
+## What "RLS" is worth, stated where somebody will read it
+
+Two conditions have to hold before a policy does anything, and in the shipped
+configuration the second does not.
+
+**The session must have bound a tenant.** A policy reads
+`app.current_tenant_id`, and permits everything when it is unset. That is
+deliberate — ingest, fusion, the hunt scheduler and the retention purge all
+work across tenants and would otherwise process nothing, silently — but it
+means RLS only engages on `TenantDBSession` and the agents' `_set_rls_context`
+paths. Everywhere else the query predicate is the only control, which is why
+`scripts/check_tenant_query_predicates.py` is the gate that matters and RLS is
+the layer under it.
+
+**The role must not bypass RLS.** A superuser, or any role with `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
+run every service as `POSTGRES_USER=aisoc`, which the postgres image creates
+as a superuser. So out of the box **no policy in this database is doing
+anything**, and `test_postgres_rls.py` asserts that rather than footnoting it:
+if the connecting role ever stops bypassing RLS, that test tells you, and the
+docs should stop hedging. Everything else in that file reads as a
+purpose-made `NOSUPERUSER NOBYPASSRLS` role, which is the configuration the
+policies are written for and the one
+`apps/docs/docs/operations/security.md` gives the grants for.
+
+The suite also holds the line on three things that made policies inert before
+anyone noticed: a tenant-scoped table with no policy at all, a policy without
+`FORCE`, and a policy keyed on a session variable nothing sets (four read
+`app.tenant_id` or `app.current_tenant`; two raised
+`unrecognized configuration parameter` on an unbound session).
+
## Deliberate cross-tenant reads
The MSSP portfolio surface reads several tenants at once by design, which
diff --git a/tests/isolation/stores.py b/tests/isolation/stores.py
index 0a1cb1fac..1b68e20c3 100644
--- a/tests/isolation/stores.py
+++ b/tests/isolation/stores.py
@@ -21,9 +21,14 @@ STORES: tuple[StoreCoverage, ...] = (
StoreCoverage(
"postgres",
"rls",
- "migrations/002_rls.sql + query-layer WHERE tenant_id; services/api/tests/test_*_tenant_isolation.py; "
- "deliberate cross-tenant reads (MSSP portfolio) resolve their tenant list through org_scope and are "
- "replayed against live Postgres by test_mssp_portfolio_isolation.py (integration.yml)",
+ "query-layer WHERE tenant_id (the primary control, gated by check_tenant_query_predicates.py) with RLS "
+ "beneath it: migrations/002_rls.sql covered six tables, 060_rls_coverage.sql plus one alembic revision in "
+ "each of honeytokens / osquery-tls / purple-team / ueba take it to 92 of 95 tenant-scoped tables. "
+ "test_postgres_rls.py replays two tenants through every covered table against live Postgres "
+ "(integration.yml) as a NOSUPERUSER NOBYPASSRLS role — and asserts that the role the services actually "
+ "ship with bypasses RLS entirely, so the coverage figure is never read as a live guarantee. "
+ "services/api/tests/test_*_tenant_isolation.py; deliberate cross-tenant reads (MSSP portfolio) resolve "
+ "their tenant list through org_scope and are replayed by test_mssp_portfolio_isolation.py",
),
StoreCoverage(
"qdrant",
diff --git a/tests/isolation/test_postgres_rls.py b/tests/isolation/test_postgres_rls.py
new file mode 100644
index 000000000..180b9c7ba
--- /dev/null
+++ b/tests/isolation/test_postgres_rls.py
@@ -0,0 +1,645 @@
+"""Live-Postgres proof that the row-level security policies actually isolate.
+
+Why this file exists
+--------------------
+Of 95 tenant-scoped tables, 31 carried an RLS policy and 64 did not, so on two
+thirds of the schema the query predicate was the only thing between two
+customers. ``services/api/migrations/060_rls_coverage.sql`` closes that. A
+migration that adds 49 policies is worth exactly as much as the evidence that
+they filter, so this is the evidence.
+
+Shape of every assertion, borrowed from ``test_live_stores.py`` and
+``services/api/tests/test_mssp_portfolio_isolation.py`` because it is what
+makes such a test mean anything:
+
+1. Seed a row for tenant A **and** a row for tenant B.
+2. Assert an unscoped read sees both — a scoped read that returns nothing on an
+ empty table passes for the wrong reason, and that is the failure mode this
+ 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*
+--------------------------------------------------------
+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.
+
+Skips when no database answers, so a local ``pytest tests/isolation`` stays
+green — but **cannot** skip where it is supposed to run. ``integration.yml``
+sets ``POSTGRES_RLS_ISOLATION_REQUIRED=1`` and an unreachable database is then
+a failure. A gate that quietly declines to run looks identical to one that
+passed.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import re
+import subprocess
+import sys
+import uuid
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+MIGRATIONS = REPO_ROOT / "services" / "api" / "migrations"
+
+DSN = os.environ.get("DATABASE_URL", "")
+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
+#: of module-wide, because two of the checks here are pure file reads and a
+#: blanket asyncio mark on a synchronous function is an error in strict mode.
+pytestmark = pytest.mark.skipif(
+ "postgres" not in DSN and not REQUIRED,
+ reason="needs a live Postgres with the migration chain applied (integration.yml)",
+)
+
+# Fixed ids so a failure names something greppable.
+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.
+INTENTIONALLY_UNPROTECTED = frozenset({"users"})
+
+#: API ORM models that declare a ``tenant_id`` but that no migration creates.
+#: Named here rather than silently absent: a table nothing creates cannot carry
+#: a policy, and the reason should be visible next to the exclusion.
+ORM_MODELS_WITHOUT_A_TABLE = frozenset({"case_tasks", "case_timeline"})
+
+
+def _asyncpg_dsn(url: str) -> str:
+ """SQLAlchemy URL → bare DSN asyncpg accepts."""
+ for prefix in ("postgresql+asyncpg://", "postgresql+psycopg://"):
+ if url.startswith(prefix):
+ return "postgresql://" + url[len(prefix) :]
+ return url
+
+
+#: Quoted literals inside a CHECK constraint, e.g.
+#: ``CHECK (node_type = ANY (ARRAY['user'::text, 'host'::text]))``.
+_CHECK_LITERAL = re.compile(r"'([^']+)'")
+
+
+def _literal_for(
+ data_type: str,
+ udt: str,
+ enum_labels: dict[str, list[str]],
+ *,
+ nonce: str,
+ allowed: list[str] | None = None,
+ max_len: int | None = None,
+) -> str:
+ """A syntactically valid value for a NOT NULL column with no default.
+
+ Every table here has a different set of required columns, so the seeder
+ derives them from ``information_schema`` instead of carrying 60
+ hand-written INSERTs that go stale the first time a column is added.
+
+ Three details earn their keep, each found by the seeder failing on a real
+ table rather than by guessing:
+
+ * ``nonce`` differs per seeded row. Several tables have a unique
+ constraint that does *not* include ``tenant_id``, so A and B sharing a
+ literal collides and the table silently drops out of the replay.
+ * ``allowed`` carries the literals named in the column's CHECK constraint.
+ ``identity_nodes.node_type`` and four others accept a fixed vocabulary.
+ * ``max_len`` respects ``varchar(n)``; ``aisoc_attack_chains`` has a
+ ``varchar(8)``.
+ """
+ if allowed:
+ return f"'{allowed[0]}'"
+ if data_type == "uuid":
+ return f"'{uuid.uuid4()}'::uuid"
+ if data_type in ("character varying", "text", "character"):
+ value = f"p{nonce}"
+ if max_len is not None:
+ value = value[:max_len]
+ return f"'{value}'"
+ if data_type in ("integer", "bigint", "smallint"):
+ return "1"
+ if data_type in ("numeric", "double precision", "real"):
+ return "1"
+ if data_type == "boolean":
+ return "false"
+ if data_type in ("timestamp with time zone", "timestamp without time zone"):
+ return "now()"
+ if data_type == "date":
+ return "current_date"
+ if data_type == "jsonb":
+ return "'{}'::jsonb"
+ if data_type == "json":
+ return "'{}'::json"
+ if data_type == "inet":
+ return "'198.51.100.1'::inet"
+ if data_type == "ARRAY":
+ # udt_name for an array is the element type prefixed with '_'.
+ return f"'{{}}'::{udt.lstrip('_')}[]"
+ if data_type == "USER-DEFINED":
+ labels = enum_labels.get(udt) or []
+ if labels:
+ return f"'{labels[0]}'::{udt}"
+ # Let Postgres decide; if it cannot, the seeder reports the column by name.
+ return "DEFAULT"
+
+
+async def _protected_tables(conn) -> list[str]:
+ """Tenant-scoped tables in *this* database that carry an RLS policy."""
+ rows = await conn.fetch(
+ """
+ SELECT c.relname AS t
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public'
+ AND c.relkind = 'r'
+ AND c.relrowsecurity
+ AND EXISTS (
+ SELECT 1 FROM pg_attribute a
+ WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND NOT a.attisdropped)
+ ORDER BY 1
+ """
+ )
+ return [r["t"] for r in rows]
+
+
+async def _check_vocabularies(conn, table: str) -> dict[str, list[str]]:
+ """column → literals its CHECK constraint permits.
+
+ Only single-column checks are used: a multi-column check tells us nothing
+ about which value belongs to which column.
+ """
+ rows = await conn.fetch(
+ """
+ SELECT a.attname AS col, pg_get_constraintdef(c.oid) AS def
+ FROM pg_constraint c
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
+ WHERE c.contype = 'c'
+ AND c.conrelid = to_regclass('public.' || quote_ident($1))
+ AND array_length(c.conkey, 1) = 1
+ """,
+ table,
+ )
+ out: dict[str, list[str]] = {}
+ for row in rows:
+ literals = [m for m in _CHECK_LITERAL.findall(row["def"]) if not m.endswith("::text")]
+ if literals:
+ out.setdefault(row["col"], []).extend(literals)
+ return out
+
+
+async def _seed_row(conn, table: str, tenant: uuid.UUID, enum_labels: dict[str, list[str]], nonce: str) -> None:
+ """Insert one row owned by ``tenant``, filling only what the schema demands."""
+ cols = await conn.fetch(
+ """
+ SELECT column_name, data_type, udt_name, character_maximum_length
+ FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = $1
+ AND is_nullable = 'NO' AND column_default IS NULL
+ AND column_name <> 'tenant_id'
+ ORDER BY ordinal_position
+ """,
+ table,
+ )
+ vocab = await _check_vocabularies(conn, table)
+ tenant_type = await conn.fetchval(
+ """
+ SELECT format_type(a.atttypid, a.atttypmod)
+ FROM pg_attribute a
+ WHERE a.attrelid = to_regclass('public.' || quote_ident($1))
+ AND a.attname = 'tenant_id' AND NOT a.attisdropped
+ """,
+ table,
+ )
+ tenant_literal = f"'{tenant}'::uuid" if tenant_type == "uuid" else f"'{tenant}'"
+
+ names = ["tenant_id"]
+ values = [tenant_literal]
+ for col in cols:
+ literal = _literal_for(
+ col["data_type"],
+ col["udt_name"],
+ enum_labels,
+ nonce=nonce,
+ allowed=vocab.get(col["column_name"]),
+ max_len=col["character_maximum_length"],
+ )
+ if literal == "DEFAULT":
+ continue
+ names.append(f'"{col["column_name"]}"')
+ values.append(literal)
+
+ # Every literal above is generated here from the column's own type; none
+ # of it comes from outside this process.
+ 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."""
+ asyncpg = pytest.importorskip("asyncpg")
+ if not DSN:
+ pytest.skip("DATABASE_URL not set")
+ admin_dsn = _asyncpg_dsn(DSN)
+ try:
+ admin = await asyncpg.connect(admin_dsn)
+ except Exception as exc: # noqa: BLE001
+ if 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)
+
+
+#: Populated once by :func:`_seeded`. A module-scoped *async* fixture binds
+#: itself to one event loop and pytest-asyncio gives each test a fresh one, so
+#: the state is cached here instead.
+_STATE: dict[str, object] = {}
+
+
+async def _seeded() -> dict:
+ """Seed one A row and one B row into every RLS-covered tenant table.
+
+ Seeding runs as the owner with replication-role ``replica`` so foreign keys
+ do 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.
+ """
+ if _STATE:
+ return dict(_STATE)
+ probe_dsn = await _make_probe_role()
+ asyncpg = pytest.importorskip("asyncpg")
+ admin = await asyncpg.connect(_asyncpg_dsn(DSN))
+ enum_labels: dict[str, list[str]] = {}
+ seeded_tables: list[str] = []
+ unseedable: dict[str, str] = {}
+ try:
+ for row in await admin.fetch(
+ "SELECT t.typname, e.enumlabel FROM pg_type t JOIN pg_enum e ON e.enumtypid = t.oid ORDER BY e.enumsortorder"
+ ):
+ enum_labels.setdefault(row["typname"], []).append(row["enumlabel"])
+
+ tables = await _protected_tables(admin)
+ await admin.execute("SET session_replication_role = replica")
+ # Clear any rows a previous run left behind. Without this the
+ # "exactly 2 rows" assertions drift upward on every re-run and the
+ # suite starts failing for a reason that has nothing to do with
+ # isolation — which is how a test earns a reputation for flakiness.
+ for table in tables:
+ with contextlib.suppress(Exception):
+ await admin.execute(
+ f'DELETE FROM public."{table}" WHERE tenant_id::text = ANY($1::text[])', # noqa: S608
+ [str(TENANT_A), str(TENANT_B)],
+ )
+ for table in tables:
+ try:
+ async with admin.transaction():
+ await _seed_row(admin, table, TENANT_A, enum_labels, uuid.uuid4().hex[:6])
+ await _seed_row(admin, table, TENANT_B, enum_labels, uuid.uuid4().hex[:6])
+ except Exception as exc: # noqa: BLE001
+ unseedable[table] = f"{type(exc).__name__}: {exc}"
+ continue
+ seeded_tables.append(table)
+ finally:
+ await admin.close()
+
+ _STATE.update({"tables": tables, "seeded": seeded_tables, "unseedable": unseedable, "probe_dsn": probe_dsn})
+ return dict(_STATE)
+
+
+# ---------------------------------------------------------------------------
+# The measured fact that makes every other result in this file conditional
+# ---------------------------------------------------------------------------
+
+
+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.
+ """
+ await _seeded()
+ asyncpg = pytest.importorskip("asyncpg")
+ admin = await asyncpg.connect(_asyncpg_dsn(DSN))
+ 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"
+ )
+ finally:
+ await admin.close()
+
+
+# ---------------------------------------------------------------------------
+# The two-tenant replay, once per protected table
+# ---------------------------------------------------------------------------
+
+
+async def test_every_protected_table_is_seeded_for_both_tenants() -> None:
+ """Non-vacuity, asserted once and loudly rather than per-table.
+
+ A table the seeder could not populate would make its isolation assertion
+ below trivially true, so the seeder's failures are a test result, not a
+ log line.
+ """
+ seeded = await _seeded()
+ assert seeded["tables"], "no RLS-covered tenant table found — the migration chain did not apply"
+ assert not seeded["unseedable"], (
+ "these RLS-covered tables could not be seeded, so their isolation assertions "
+ f"would pass vacuously: {seeded['unseedable']}"
+ )
+
+
+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"])
+ leaked: list[str] = []
+ vacuous: list[str] = []
+ checked = 0
+ try:
+ for table in seeded["seeded"]:
+ # (2) Unscoped: both tenants' rows are really there.
+ unscoped = await probe.fetchval(
+ f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = ANY($1::text[])', # noqa: S608
+ [str(TENANT_A), str(TENANT_B)],
+ )
+ if unscoped != 2:
+ vacuous.append(f"{table}: unscoped read saw {unscoped} of the 2 seeded rows")
+ 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(
+ f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = $1', # noqa: S608
+ str(TENANT_A),
+ )
+ seen_b = await probe.fetchval(
+ f'SELECT count(*) FROM public."{table}" WHERE tenant_id::text = $1', # noqa: S608
+ str(TENANT_B),
+ )
+ if seen_b != 0:
+ leaked.append(f"{table}: tenant B's row was visible to a session bound to tenant A")
+ elif seen_a != 1:
+ leaked.append(f"{table}: tenant A could not see its own row ({seen_a}), so the policy is over-tight")
+ checked += 1
+ finally:
+ await probe.close()
+
+ assert not vacuous, "seeded rows were not visible even unscoped, so the scoped assertions prove nothing: " + "; ".join(vacuous)
+ assert not leaked, "; ".join(leaked)
+ assert checked >= 40, f"only {checked} tables were replayed; the chain should protect far more"
+
+
+async def test_a_session_with_no_tenant_context_still_sees_everything() -> None:
+ """Fail open on an unset context — the documented, deliberate semantic.
+
+ Ingest, fusion, the hunt scheduler and the retention purge all operate
+ across tenants on connections that never bind one. If this ever fails
+ closed they stop processing silently, which is the failure mode that left
+ ``tenant_sla_config`` returning zero rows for anybody who looked.
+ """
+ seeded = await _seeded()
+ asyncpg = pytest.importorskip("asyncpg")
+ probe = await asyncpg.connect(seeded["probe_dsn"])
+ try:
+ for table in seeded["seeded"][:20]:
+ both = await probe.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()
+
+
+async def test_no_policy_reads_a_session_variable_nothing_sets() -> None:
+ """The bug class 060 repaired, kept repaired.
+
+ Seven policies read ``app.tenant_id`` or ``app.current_tenant`` — names no
+ code path sets — or called ``current_setting`` without ``missing_ok``, so
+ they either returned zero rows forever or raised
+ ``unrecognized configuration parameter``. Both are invisible while a
+ superuser bypasses them.
+ """
+ asyncpg = pytest.importorskip("asyncpg")
+ admin = await asyncpg.connect(_asyncpg_dsn(DSN))
+ try:
+ rows = await admin.fetch("SELECT tablename, policyname, qual FROM pg_policies WHERE schemaname = 'public'")
+ finally:
+ await admin.close()
+
+ wrong_variable: list[str] = []
+ would_raise: list[str] = []
+ for row in rows:
+ qual = row["qual"] or ""
+ for setting in re.findall(r"current_setting\(\s*'([^']+)'([^)]*)\)", qual):
+ name, rest = setting
+ if name != "app.current_tenant_id":
+ wrong_variable.append(f"{row['tablename']}.{row['policyname']} reads {name!r}")
+ elif "true" not in rest:
+ would_raise.append(f"{row['tablename']}.{row['policyname']} omits missing_ok, so an unset context raises")
+
+ assert not wrong_variable, (
+ "a policy keyed on a session variable nothing sets returns zero rows forever: " + "; ".join(wrong_variable)
+ )
+ assert not would_raise, "; ".join(would_raise)
+
+
+async def test_every_tenant_table_is_protected_or_named() -> None:
+ """Coverage, both directions.
+
+ Forward: a tenant-scoped table with no policy fails unless it is one of the
+ two documented exclusions. Reverse: an exclusion that no longer describes
+ an unprotected table fails too, so the list cannot outlive its reason.
+ """
+ asyncpg = pytest.importorskip("asyncpg")
+ admin = await asyncpg.connect(_asyncpg_dsn(DSN))
+ try:
+ unprotected = {
+ r["t"]
+ for r in await admin.fetch(
+ """
+ SELECT c.relname AS t
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind = 'r' AND NOT c.relrowsecurity
+ AND EXISTS (SELECT 1 FROM pg_attribute a
+ WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND NOT a.attisdropped)
+ """
+ )
+ }
+ unforced = {
+ r["t"]
+ for r in await admin.fetch(
+ """
+ SELECT c.relname AS t FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relrowsecurity AND NOT c.relforcerowsecurity
+ """
+ )
+ }
+ finally:
+ await admin.close()
+
+ surprises = unprotected - INTENTIONALLY_UNPROTECTED
+ assert not surprises, (
+ f"tenant-scoped tables with no RLS policy: {sorted(surprises)}. "
+ "Add one in a migration, or add the table to INTENTIONALLY_UNPROTECTED with the reason."
+ )
+ stale = INTENTIONALLY_UNPROTECTED - unprotected
+ assert not stale, f"these are now protected, so the exclusion is stale and must come out: {sorted(stale)}"
+ assert not unforced, (
+ f"RLS is enabled but not FORCEd on {sorted(unforced)}, so the table owner — which is the "
+ "application — walks straight past the policy"
+ )
+
+
+def test_orm_models_without_a_table_are_still_absent() -> None:
+ """Two API models declare a tenant_id that no migration ever creates.
+
+ Named rather than ignored. If a migration later creates one of these, this
+ fails and the table needs a policy like every other.
+ """
+ sql = "\n".join(p.read_text(encoding="utf-8") for p in sorted(MIGRATIONS.glob("*.sql")))
+ for table in sorted(ORM_MODELS_WITHOUT_A_TABLE):
+ assert not re.search(rf'CREATE TABLE(?:\s+IF NOT EXISTS)?\s+"?{table}"?\b', sql, re.I), (
+ f"{table} now has a migration, so it needs an RLS policy and must come out of ORM_MODELS_WITHOUT_A_TABLE"
+ )
+
+
+# ---------------------------------------------------------------------------
+# The attack-path relational fallback, replayed for real
+# ---------------------------------------------------------------------------
+
+
+async def test_attack_path_relational_fallback_refuses_another_tenants_case() -> None:
+ """Tenant B names tenant A's case UUID and is refused.
+
+ ``GET /graph/attack-path/{case_id}`` reads ``aisoc_cases`` by id when the
+ Neo4j traversal fails — which, for a deployment that ships no graph
+ database, is *always*. It gained a tenant predicate, but that fix was
+ covered by the gate and by review only: the statement uses
+ ``CAST(:cid AS UUID)``, which SQLite mangles, so the offline suites cannot
+ execute it. This runs it against the database it is written for.
+ """
+ pytest.importorskip("asyncpg")
+ pytest.importorskip("greenlet")
+ sqlalchemy_asyncio = pytest.importorskip("sqlalchemy.ext.asyncio")
+
+ api_root = REPO_ROOT / "services" / "api"
+ if str(api_root) not in sys.path:
+ 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]
+ engine = sqlalchemy_asyncio.create_async_engine(sa_url)
+ case_a = uuid.uuid4()
+ case_b = uuid.uuid4()
+ try:
+ from sqlalchemy import text # noqa: PLC0415
+
+ async with sqlalchemy_asyncio.async_sessionmaker(engine, expire_on_commit=False)() as db:
+ await db.execute(text("SET session_replication_role = replica"))
+ for case_id, tenant, title in ((case_a, TENANT_A, "A: ransomware"), (case_b, TENANT_B, "B: phishing")):
+ # jsonb and uuid[] are cast from text rather than bound as
+ # Python lists: asyncpg refuses a list for a jsonb parameter,
+ # and the point of this test is the statement's own SQL.
+ await db.execute(
+ text(
+ "INSERT INTO aisoc_cases (id, tenant_id, title, severity, status, mitre_techniques, alert_ids) "
+ "VALUES (CAST(:id AS UUID), CAST(:tid AS UUID), :title, 'high', 'investigating', "
+ "CAST(:tech AS JSONB), CAST(:alerts AS UUID[]))"
+ ).bindparams(
+ id=str(case_id),
+ tid=str(tenant),
+ title=title,
+ tech='["T1486"]',
+ alerts="{" + str(uuid.uuid4()) + "}",
+ )
+ )
+ await db.commit()
+
+ # (2) Non-vacuity: A's case genuinely exists and is readable by A.
+ own = await _attack_path_from_relational(db, str(case_a), TENANT_A)
+ assert own is not None, "tenant A's own case was not found — every assertion below would be vacuous"
+ assert own["nodes"], "tenant A's case produced no graph, so the read below proves nothing"
+
+ # (3) The read that must be refused.
+ leaked = await _attack_path_from_relational(db, str(case_a), TENANT_B)
+ assert leaked is None, "tenant B reconstructed tenant A's attack path by naming its case UUID"
+
+ crossed = await _attack_path_from_relational(db, str(case_b), TENANT_A)
+ assert crossed is None, "tenant A reconstructed tenant B's attack path"
+ finally:
+ async with engine.begin() as conn:
+ from sqlalchemy import text as _text # noqa: PLC0415
+
+ await conn.execute(_text("DELETE FROM aisoc_cases WHERE id = ANY(:ids)").bindparams(ids=[case_a, case_b]))
+ await engine.dispose()
+
+
+# ---------------------------------------------------------------------------
+# The gate this suite backs, run as a meta-assertion
+# ---------------------------------------------------------------------------
+
+
+def test_predicate_gate_still_reports_no_violations() -> None:
+ """RLS is the second layer, not a reason to relax the first one."""
+ result = subprocess.run(
+ [sys.executable, str(REPO_ROOT / "scripts" / "check_tenant_query_predicates.py")],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr