Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(mssp): row-level security on the six tables that had none (#1084)
Beenu Arorae6a1c68f5fc9
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex a03041db7..c8d15218b 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -105,7 +105,7 @@ jobs:set -euo pipefailspine_paths='services/ingest/ services/fusion/ services/realtime/ docker-compose.yml scripts/integration/ .github/workflows/integration.yml'- migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py scripts/check_runtime_db_role.py .github/workflows/integration.yml'+ migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py .github/workflows/integration.yml'# backup_crypt.py was missing from the old filter, and it is where# every byte of the AES-256-GCM implementation lives — so a change# to the encryption itself did not run the gate that proves the@@ -812,6 +812,18 @@ jobs:POSTGRES_RLS_ISOLATION_REQUIRED: '1'run: python -m pytest tests/isolation/test_postgres_rls.py -v --tb=short+ # The suite above discovers tables by looking for a column literally+ # named `tenant_id`, so every `mssp_*` table was invisible to it — they+ # name their tenants `parent_tenant_id`/`child_tenant_id` — and six of+ # the seven carried no policy at all for as long as that blind spot+ # lasted. They also cannot be asserted the same way: an MSSP row joins+ # two tenants and *both* must read it, so the shape is "exactly one of+ # two seeded rows from four directions, and zero from a fifth tenant".+ - name: MSSP row-level security isolation (live, two portfolios)+ env:+ POSTGRES_RLS_ISOLATION_REQUIRED: '1'+ run: python -m pytest tests/isolation/test_mssp_rls_live.py -v --tb=short+# `POST /alerts/{id}/explain` logged `audit: failed to compute hash chain`# on every call against a default install, and the audit row was not# merely unchained — it was never written. A best-effort cost INSERTdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 024b67cf1..6c429858f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Invalidation is a version counter, not a TTL.** A TTL alone means a revoked permission keeps working for the length of the TTL on every replica holding it, which for an access revocation is the wrong failure mode. A per-tenant counter in Redis is bumped on every RBAC write, so a revoke invalidates every replica on its next request. Without Redis the cache degrades to a 15-second TTL and says so in a log — a single-process deployment is correct either way, and a multi-replica one converges within the window.- **`scripts/check_one_permission_model.py` keeps the single path single**: the check reads the resolved set, authentication resolves one, every RBAC write invalidates, and no route module imports the static map directly. One of its own probes was wrong first — flipping the branch condition to `False` left `grants(self.resolved_permissions, …)` in the body, so the attribute was still mentioned and the structural read still found it. A real regression removes the branch, and the probe now does.+- **Six of the seven `mssp_*` tables carried no row-level security.** Only `mssp_tenant_metrics` had a policy, so on the rest the query predicate was the only thing between one MSSP's portfolio and another's. Not hypothetical here: `POST /mssp/overrides` with `action: "exclude"` wrote a caller-supplied child tenant id onto a row the effective-rule resolver read back filtered on the *victim's* tenant id, letting any authenticated user silently delete a critical detection from another tenant. The route guard was fixed at the time; this is the layer that would have contained it had the guard been wrong, which is the entire argument for defence in depth. Forced RLS now covers **123 tables, up from 117**.++ These rows are not shaped like the rest of the schema. They join **two** tenants — the parent that manages and the child that is managed — and both have a legitimate read, because a policy naming only the parent would hide from a customer the overrides applied to their own detections.++- **The obvious way to write that produces mutually recursive policies, and only a real database found it.** A pack visible to anyone it is assigned to, an assignment visible to the owning pack's parent: both true, and together Postgres answers `infinite recursion detected in policy for relation "mssp_rule_packs"` on the first `SELECT`. `check_rls_policy_shape.py` passed throughout, because the shape was right. The cycle is broken by giving the assignment row its own `parent_tenant_id` so its policy needs no subquery — and that denormalisation is held honest by a **composite foreign key** on `(pack_id, parent_tenant_id)`, not by a trigger and not by application code, so a row naming the wrong parent cannot be inserted at all. The alternative was a `SECURITY DEFINER` helper reading the pack table with RLS bypassed, and this schema has been bitten by exactly that before.++- **`tests/isolation/test_mssp_rls_live.py` exists because the existing live suite could not see these tables.** `test_postgres_rls.py` discovers tables by looking for a column literally named `tenant_id`, so all seven `mssp_*` tables were outside its coverage figure — which is why six went unpoliced for as long as they did. **Measured against a real Postgres**: two rows per table, each of four parties saw exactly its own one, a fifth tenant party to neither saw zero in all six, and the composite key refused an assignment claiming a parent that does not own the pack. With the policies disabled, **30 of the 38 cases fail**.++ Two of my own defects were caught by guards rather than by review, and both are worth recording. The fixture was `async def` under a plain `@pytest.fixture`, so it yielded a generator and seeded nothing — caught only by the unscoped-read assertion that exists to stop a scoped read passing against an empty table. And the migration was **not re-runnable**: it dropped the unique constraint the new foreign key depends on, so a replayed chain failed with `Use DROP ... CASCADE`. Both now hold; the migration applies twice in a row cleanly.### Securitydiff --git a/ROADMAP.md b/ROADMAP.mdindex 089d451a8..905bae3b4 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,10 +44,10 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **254 rows — 254 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **254 rows — 254 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **254 rows — 254 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **254 rows — 254 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **255 rows — 255 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **255 rows — 255 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **255 rows — 255 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **255 rows — 255 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 0a5dd5057..ed761f362 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,10 +33,10 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 254 rows-The last row is the one worth reading first. It is the honest index: 254 rows-The last row is the one worth reading first. It is the honest index: 254 rows-The last row is the one worth reading first. It is the honest index: 254 rows+The last row is the one worth reading first. It is the honest index: 255 rows+The last row is the one worth reading first. It is the honest index: 255 rows+The last row is the one worth reading first. It is the honest index: 255 rows+The last row is the one worth reading first. It is the honest index: 255 rows`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 747965e3f..6dab602dd 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -262,26 +262,27 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The audit log names the credential that acted, and a tenant can read its own trail | `apps/docs/docs/compliance/evidence-pack.md`; `apps/docs/docs/operations/security.md` | `ci.yml :: Python — Lint & Type-check` (`check_audit_coverage.py` — every actor-bearing `emit_audit` records the credential, `tenant_admin` holds `audit_log:read`, the modules whose *reads* are the sensitive act emit audit, and the coverage floor ratchets; 6 self-test cases including two controls) + `ci.yml :: Python — Tests` (`services/api/tests/test_audit_attribution_and_readership.py`) | GATED | **Proven against the pre-fix tree**: 7 of 11 fail at `3c04a21b`, and the gate found two live defects on its first run that the hand-written fix had missed. The honest limit is published rather than hidden: **7 of 86 endpoint modules emit audit at all**, the floor is set at that measured value rather than an aspiration, and the gate prints the largest unaudited surfaces by route count on success so the next step is named. Raising it is ordinary work, not a gap in the control. One correction recorded: the attribution rule first reported the SCIM writer, whose actor is already `scim:<token>` — a scheme-prefixed actor is self-attributing || Only a human-confirmed, unexpired, uninjected prior can auto-close an alert | `apps/docs/docs/concepts/automation-maturity.md`; `apps/docs/docs/console/funnel-kpis.md` | `ci.yml :: Python — Tests` (`services/agents/tests/test_outcome_memory.py` — an AI prior never suppresses at any count or confidence, a prior expires 90 days after its last confirmation, an unparseable timestamp counts as expired, injection-flagged evidence never suppresses, and the refusal names which rule declined; plus `test_outcome_writer_signature_parity.py`, which compares all four `record_outcome` signatures in both directions and asserts the concrete writer forwards the flag) | GATED | **Proven against the pre-fix tree**: `suppression_refusal` does not exist there, so the whole module fails to import, and 2 of the 10 parity cases fail. The durable finding is why the parity test exists: adding the keyword broke four writers and **no test failed on the exception**, because the call sits inside `contextlib.suppress(Exception)` — what surfaced was a zero write-count in an unrelated replay test three files away. One limit: these prove the *rules*, and the injection flag is only as good as the guard that sets it, which scores 98.1% on its tuned corpus and 7.1% on held-out payloads || A permission granted or revoked in the console governs every route | `apps/docs/docs/operations/security.md` (RBAC); `apps/docs/docs/console/settings.md` | `ci.yml :: Python — Lint & Type-check` (`check_one_permission_model.py` — the check reads the resolved set, authentication resolves one, all 5 RBAC mutations invalidate, and no route module imports the static map; 5 self-test cases, one a control) + `ci.yml :: Python — Tests` (`services/api/tests/test_database_backed_permissions.py`, 18 cases **in both directions**: a database grant the static map lacks is allowed, and a static grant the database lacks is denied) | GATED | **The second direction is the one that was broken**: the old fallback restored a deprovisioned user's static permissions whenever their last role was removed, because an empty row set was read as 'not configured'. 275 static sites became database-backed with zero call-site edits by moving resolution into `get_current_user`. Two limits stated rather than hidden: resolution **fails open to the static map** on a database fault, deliberately, because failing closed would turn a blip into a platform-wide lockout mid-incident; and without Redis the invalidation degrades from a version counter to a 15-second TTL, logged, so a multi-replica deployment converges rather than invalidating immediately |+| Every `mssp_*` table isolates one portfolio from another at the database layer | `apps/docs/docs/concepts/multi-tenancy.md`; `apps/docs/docs/mssp/overview.md` | `integration.yml :: MSSP row-level security isolation (live, two portfolios)` (`tests/isolation/test_mssp_rls_live.py`, 38 cases against a real Postgres) + `ci.yml :: Python — Tests` (`services/api/tests/test_mssp_row_level_security.py`, 20 structural cases including a policy-graph cycle detector) | GATED | **Measured, not asserted**: with the policies disabled 30 of the 38 live cases fail; with them, each of four parties sees exactly its own row and a fifth sees zero. Forced RLS 117 → 123 tables. The cycle detector was **proven by re-injecting the real cycle** the first draft had. Two findings worth keeping: the existing live suite discovers tables by a column named `tenant_id`, so all seven `mssp_*` tables sat outside its coverage figure — which is why six went unpoliced; and `check_rls_policy_shape.py` passed on mutually recursive policies that raise `infinite recursion detected` on the first SELECT, so shape is not liveness. One limit: the live job needs a container, so on a developer machine without one these skip |## Summary-- GATED: 254+- GATED: 255## Summary-- GATED: 254+- GATED: 255## Summary-- GATED: 254+- GATED: 255## Summary-- GATED: 254+- GATED: 255## Summary-- GATED: 254+- GATED: 255- PARTIAL: 0- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** 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 last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.pyindex fbb2acc1c..a7bac7690 100644--- a/services/api/app/api/v1/endpoints/mssp.py+++ b/services/api/app/api/v1/endpoints/mssp.py@@ -650,6 +650,11 @@ async def assign_pack_to_child(assignment = MSSPRulePackAssignment(pack_id=pack_id,+ # Taken from the pack that was just loaded and ownership-checked,+ # never from the request. The composite foreign key would reject a+ # mismatch anyway; reading it from the pack means the rejection+ # never has to happen.+ parent_tenant_id=pack.parent_tenant_id,child_tenant_id=body.child_tenant_id,enabled=body.enabled,parameter_overrides=body.parameter_overrides,diff --git a/services/api/app/models/mssp.py b/services/api/app/models/mssp.pyindex 916d2da60..21ee8fcf0 100644--- a/services/api/app/models/mssp.py+++ b/services/api/app/models/mssp.py@@ -105,6 +105,17 @@ class MSSPRulePackAssignment(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)pack_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("mssp_rule_packs.id", ondelete="CASCADE"), nullable=False, index=True)child_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)+ #: The owning pack's parent, carried here so the row-level policy needs+ #: no subquery. Writing it as a subquery over `mssp_rule_packs` was the+ #: first attempt and produced mutually recursive policies — Postgres+ #: answers `infinite recursion detected` on the first SELECT, which no+ #: static check caught.+ #:+ #: Kept honest by a composite foreign key on+ #: `(pack_id, parent_tenant_id)`, not by this assignment: a row naming+ #: the wrong parent cannot be inserted at all, so the denormalisation+ #: cannot drift.+ parent_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)parameter_overrides: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)assigned_by_user: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)diff --git a/services/api/migrations/077_mssp_row_level_security.sql b/services/api/migrations/077_mssp_row_level_security.sqlnew file mode 100644index 000000000..f35c05e22--- /dev/null+++ b/services/api/migrations/077_mssp_row_level_security.sql@@ -0,0 +1,199 @@+-- Row-level security on the six `mssp_*` tables that had none.+--+-- `mssp_tenant_metrics` already had a policy; these six did not, so the only+-- thing standing between one MSSP's portfolio and another's was the query+-- layer. That is not a hypothetical: `POST /mssp/overrides` with+-- `action: "exclude"` wrote a caller-supplied child tenant id onto a row that+-- the effective-rule resolver then read back filtered on the *victim's*+-- tenant id, so any authenticated user could silently delete a critical+-- detection from any other tenant. The route guard was fixed; this is the+-- layer that would have contained it if the guard had been wrong, which is+-- the whole argument for defence in depth.+--+-- These rows are not shaped like the rest of the schema. A normal table has+-- one `tenant_id` and the policy is `tenant_id = current_tenant_id()`. An+-- MSSP row joins **two** tenants — the parent that manages the relationship+-- and the child that is managed — and both have a legitimate read. A policy+-- naming only the parent would hide from a customer the overrides being+-- applied to their own detections, which is the transparency the MSSP+-- adoption flow was rebuilt around: a child must invite a parent, so a child+-- must also be able to see what that parent has done.+--+-- So each policy is `parent = current_tenant_id() OR child = current_tenant_id()`.+--+-- `mssp_rule_pack_rules` has no tenant column at all; it joins a pack to a+-- rule. Its tenancy is inherited, so the policy is an EXISTS over the+-- owning pack. Writing it any other way would mean denormalising a tenant id+-- onto a join table and keeping two copies in step.+--+-- `current_tenant_id() IS NULL` is permitted throughout, matching every other+-- policy in this schema: a connection that has not set the context is an+-- out-of-band migration or an exempt superuser, and the services now connect+-- as the non-exempt `aisoc_app` role, so they cannot reach that branch.++BEGIN;++-- ── parent/child pairs ──────────────────────────────────────────────────────++ALTER TABLE mssp_delegations ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_delegations FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_delegations_tenant ON mssp_delegations;+CREATE POLICY mssp_delegations_tenant ON mssp_delegations+ USING (+ parent_tenant_id = current_tenant_id()+ OR child_tenant_id = current_tenant_id()+ OR current_tenant_id() IS NULL+ );++ALTER TABLE mssp_rule_overrides ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_rule_overrides FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_rule_overrides_tenant ON mssp_rule_overrides;+CREATE POLICY mssp_rule_overrides_tenant ON mssp_rule_overrides+ USING (+ parent_tenant_id = current_tenant_id()+ OR child_tenant_id = current_tenant_id()+ OR current_tenant_id() IS NULL+ );++ALTER TABLE mssp_tenant_notes ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_tenant_notes FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_tenant_notes_tenant ON mssp_tenant_notes;+CREATE POLICY mssp_tenant_notes_tenant ON mssp_tenant_notes+ USING (+ parent_id = current_tenant_id()+ OR child_id = current_tenant_id()+ OR current_tenant_id() IS NULL+ );++-- ── parent-owned, and the recursion that forced a schema change ────────────+--+-- The first draft wrote these two policies as mutual subqueries: a pack was+-- visible to its parent or to any tenant with an assignment, and an+-- assignment was visible to its child or to the owning pack's parent. Both+-- are correct statements about who should see what, and together they are+-- unusable — Postgres answers `infinite recursion detected in policy for+-- relation "mssp_rule_packs"` on the first SELECT.+--+-- Nothing static caught it. `check_rls_policy_shape.py` passed, because the+-- policies have the right shape; it took running them against a real+-- Postgres with two seeded MSSPs to see it at all.+--+-- The cycle is broken by giving the assignment row its own+-- `parent_tenant_id`, so its policy needs no subquery. That is a+-- denormalisation, and a denormalisation that drifts is worse than the+-- recursion it replaced — so it is not maintained by a trigger or by+-- application code, it is a **composite foreign key**: the pair+-- `(pack_id, parent_tenant_id)` must exist in `mssp_rule_packs`. A row+-- naming the wrong parent cannot be inserted, and a pack cannot change+-- owner without the referencing rows moving with it.+--+-- The alternative was a SECURITY DEFINER helper reading the pack table with+-- RLS bypassed. This schema has been bitten by exactly that before — two+-- views that read as their owner silently undid tenant isolation — so a+-- constraint the database enforces is the better trade.++-- Added only if absent, never dropped-then-added. The foreign key below+-- depends on this constraint, so a DROP on a second run fails with+-- `Use DROP ... CASCADE to drop the dependent objects too` — which is how+-- a migration that applied cleanly the first time breaks on re-run, and+-- re-runs happen whenever a deployment replays its chain.+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = 'mssp_rule_packs_id_parent_key'+ AND conrelid = 'mssp_rule_packs'::regclass+ ) THEN+ ALTER TABLE mssp_rule_packs+ ADD CONSTRAINT mssp_rule_packs_id_parent_key UNIQUE (id, parent_tenant_id);+ END IF;+END+$$;++ALTER TABLE mssp_rule_pack_assignments+ ADD COLUMN IF NOT EXISTS parent_tenant_id UUID;++-- Backfill before the constraint, or an existing deployment cannot migrate.+UPDATE mssp_rule_pack_assignments a+ SET parent_tenant_id = p.parent_tenant_id+ FROM mssp_rule_packs p+ WHERE p.id = a.pack_id+ AND a.parent_tenant_id IS DISTINCT FROM p.parent_tenant_id;++ALTER TABLE mssp_rule_pack_assignments+ ALTER COLUMN parent_tenant_id SET NOT NULL;+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = 'mssp_rule_pack_assignments_pack_parent_fk'+ AND conrelid = 'mssp_rule_pack_assignments'::regclass+ ) THEN+ ALTER TABLE mssp_rule_pack_assignments+ ADD CONSTRAINT mssp_rule_pack_assignments_pack_parent_fk+ FOREIGN KEY (pack_id, parent_tenant_id)+ REFERENCES mssp_rule_packs (id, parent_tenant_id) ON DELETE CASCADE;+ END IF;+END+$$;++-- No subquery: this is the end of the chain, so nothing it reads can read+-- back into it.+ALTER TABLE mssp_rule_pack_assignments ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_rule_pack_assignments FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_rule_pack_assignments_tenant ON mssp_rule_pack_assignments;+CREATE POLICY mssp_rule_pack_assignments_tenant ON mssp_rule_pack_assignments+ USING (+ child_tenant_id = current_tenant_id()+ OR parent_tenant_id = current_tenant_id()+ OR current_tenant_id() IS NULL+ );++-- Reads assignments, which now reads nothing. One level, no cycle.+ALTER TABLE mssp_rule_packs ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_rule_packs FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_rule_packs_tenant ON mssp_rule_packs;+CREATE POLICY mssp_rule_packs_tenant ON mssp_rule_packs+ USING (+ parent_tenant_id = current_tenant_id()+ -- A child can see a pack assigned to them. Without this half the+ -- assignment row is readable while the pack it names is not, which+ -- renders as a detection set with no name.+ OR EXISTS (+ SELECT 1+ FROM mssp_rule_pack_assignments a+ WHERE a.pack_id = mssp_rule_packs.id+ AND a.child_tenant_id = current_tenant_id()+ )+ OR current_tenant_id() IS NULL+ );++-- Which rules a pack contains has no tenant of its own. Reads packs, which+-- reads assignments, which reads nothing: two levels, still no cycle.+ALTER TABLE mssp_rule_pack_rules ENABLE ROW LEVEL SECURITY;+ALTER TABLE mssp_rule_pack_rules FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS mssp_rule_pack_rules_tenant ON mssp_rule_pack_rules;+CREATE POLICY mssp_rule_pack_rules_tenant ON mssp_rule_pack_rules+ USING (+ EXISTS (+ SELECT 1+ FROM mssp_rule_packs p+ WHERE p.id = mssp_rule_pack_rules.pack_id+ )+ OR current_tenant_id() IS NULL+ );++-- The EXISTS above reads `mssp_rule_packs` from inside a policy on another+-- table, and a policy subquery runs as the querying role — so `aisoc_app`+-- needs SELECT on it, or the EXISTS raises a permission error instead of+-- returning false. That fails closed, but an operator reading the error+-- would go looking for a missing grant on the wrong table.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT ON mssp_rule_packs, mssp_rule_pack_assignments TO aisoc_app;+ END IF;+END+$$;++COMMIT;diff --git a/services/api/tests/test_mssp_row_level_security.py b/services/api/tests/test_mssp_row_level_security.pynew file mode 100644index 000000000..e7f3c90c4--- /dev/null+++ b/services/api/tests/test_mssp_row_level_security.py@@ -0,0 +1,192 @@+"""The six `mssp_*` tables that had no row-level security now have it.++`mssp_tenant_metrics` carried a policy; the other six did not, so the only+thing between one MSSP's portfolio and another's was the query layer. That+is not hypothetical here: `POST /mssp/overrides` with `action: "exclude"`+wrote a caller-supplied child tenant id onto a row the effective-rule+resolver then read back filtered on the *victim's* tenant id, so any+authenticated user could silently delete a critical detection from another+tenant. The route guard was fixed; this is the layer that would have+contained it had the guard been wrong.++Two things make these rows unlike the rest of the schema.++They join **two** tenants — the parent that manages and the child that is+managed — and both have a legitimate read. A policy naming only the parent+would hide from a customer the overrides applied to their own detections,+which is the transparency the adoption flow was rebuilt around.++And the obvious way to write that produced **mutually recursive policies**:+a pack visible to anyone with an assignment, an assignment visible to the+owning pack's parent. Postgres answers `infinite recursion detected in+policy for relation "mssp_rule_packs"` on the first SELECT, and no static+check caught it — `check_rls_policy_shape.py` passed, because the shape was+right. It took running the policies against a real Postgres with two seeded+MSSPs to see at all.++The structural cases below run without a database. The isolation itself is+measured by `tests/isolation/`, which runs against a container; recorded+here is what that measurement showed:++ two rows per table, and each of four tenants saw exactly its own one,+ an unrelated fifth saw zero in all six, and the composite foreign key+ refused an assignment claiming a parent that does not own the pack.+"""++from __future__ import annotations++import pathlib+import re++import pytest++MIGRATION = pathlib.Path(__file__).resolve().parents[1] / "migrations" / "077_mssp_row_level_security.sql"++#: Every `mssp_*` table that holds tenant-scoped rows.+TABLES = (+ "mssp_delegations",+ "mssp_rule_overrides",+ "mssp_tenant_notes",+ "mssp_rule_packs",+ "mssp_rule_pack_assignments",+ "mssp_rule_pack_rules",+)++[email protected](scope="module")+def sql() -> str:+ return MIGRATION.read_text(encoding="utf-8")++[email protected]("table", TABLES)+def test_the_table_has_forced_row_level_security(sql: str, table: str) -> None:+ assert f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY" in sql+ # FORCE matters: without it the table owner bypasses the policy, and+ # migrations run as the owner.+ assert f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY" in sql++[email protected]("table", TABLES)+def test_the_table_has_exactly_one_policy(sql: str, table: str) -> None:+ created = re.findall(rf"CREATE POLICY (\w+) ON {table}\b", sql)+ assert len(created) == 1, f"{table} has {len(created)} policies: {created}"+++def test_no_policy_is_mutually_recursive(sql: str) -> None:+ """The defect a real database found and the shape gate did not.++ Builds the graph of which policy reads which table and looks for a+ cycle. `mssp_rule_packs` may read `mssp_rule_pack_assignments`; the+ reverse would close the loop and make every SELECT on either raise.+ """+ reads: dict[str, set[str]] = {}+ for match in re.finditer(r"CREATE POLICY \w+ ON (\w+)\s*\n\s*USING \((.*?)\n \);", sql, re.S):+ table, body = match.group(1), match.group(2)+ reads[table] = {t for t in TABLES if re.search(rf"\bFROM {t}\b", body)} - {table}++ assert reads, "no policies parsed; the regex no longer matches the migration"++ def reaches(start: str, target: str, seen: frozenset[str] = frozenset()) -> bool:+ if start in seen:+ return False+ for nxt in reads.get(start, ()):+ if nxt == target or reaches(nxt, target, seen | {start}):+ return True+ return False++ cycles = [t for t in reads if reaches(t, t)]+ assert not cycles, (+ f"policies on {cycles} read a table whose policy reads back into them. Postgres "+ "answers 'infinite recursion detected' on the first SELECT"+ )+++def test_the_assignment_policy_needs_no_subquery(sql: str) -> None:+ """Because it is what breaks the cycle.++ If a future edit reintroduces an EXISTS here, the graph check above+ catches the cycle — but this says *why* the column exists, so the+ column is not deleted as redundant denormalisation.+ """+ policy = re.search(+ r"CREATE POLICY mssp_rule_pack_assignments_tenant ON mssp_rule_pack_assignments\s*\n\s*USING \((.*?)\n \);",+ sql,+ re.S,+ )+ assert policy is not None+ assert "SELECT" not in policy.group(1).upper()+ assert "parent_tenant_id = current_tenant_id()" in policy.group(1)+++def test_the_denormalised_parent_cannot_drift(sql: str) -> None:+ """A composite foreign key, not a trigger and not application code.++ `(pack_id, parent_tenant_id)` must exist in `mssp_rule_packs`, so a row+ naming the wrong parent cannot be inserted. Measured against a real+ Postgres: the insert is refused with+ `violates foreign key constraint "mssp_rule_pack_assignments_pack_parent_fk"`.+ """+ assert "ADD CONSTRAINT mssp_rule_packs_id_parent_key UNIQUE (id, parent_tenant_id)" in sql+ assert "FOREIGN KEY (pack_id, parent_tenant_id)" in sql+ assert "REFERENCES mssp_rule_packs (id, parent_tenant_id)" in sql+++def test_existing_rows_are_backfilled_before_the_constraint(sql: str) -> None:+ """Or a deployment with assignments already in it cannot migrate."""+ backfill = sql.index("UPDATE mssp_rule_pack_assignments")+ not_null = sql.index("ALTER COLUMN parent_tenant_id SET NOT NULL")+ assert backfill < not_null, "the NOT NULL lands before the backfill that satisfies it"+++def test_both_sides_of_the_relationship_can_read(sql: str) -> None:+ """A parent-only policy hides from a customer what is done to them.++ Asserted per table rather than globally, because getting this right on+ five of six is the failure mode: the one that is missed is invisible+ until a customer asks why a page is empty.+ """+ for table, parent, child in (+ ("mssp_delegations", "parent_tenant_id", "child_tenant_id"),+ ("mssp_rule_overrides", "parent_tenant_id", "child_tenant_id"),+ ("mssp_tenant_notes", "parent_id", "child_id"),+ ("mssp_rule_pack_assignments", "parent_tenant_id", "child_tenant_id"),+ ):+ policy = re.search(rf"CREATE POLICY \w+ ON {table}\s*\n\s*USING \((.*?)\n \);", sql, re.S)+ assert policy is not None, f"no policy parsed for {table}"+ body = policy.group(1)+ assert f"{parent} = current_tenant_id()" in body, f"{table} hides the row from the parent"+ assert f"{child} = current_tenant_id()" in body, f"{table} hides the row from the child"+++def test_the_subquerying_policies_grant_select_to_the_app_role(sql: str) -> None:+ """A policy subquery runs as the querying role.++ Without the grant the EXISTS raises a permission error rather than+ returning false — which fails closed, but sends an operator looking for+ a missing grant on the wrong table.+ """+ assert "GRANT SELECT ON mssp_rule_packs, mssp_rule_pack_assignments TO aisoc_app" in sql+++def test_the_orm_model_carries_the_column() -> None:+ """Or every insert fails the NOT NULL the migration adds."""+ from app.models.mssp import MSSPRulePackAssignment++ assert "parent_tenant_id" in MSSPRulePackAssignment.__table__.columns+ assert not MSSPRulePackAssignment.__table__.columns["parent_tenant_id"].nullable+++def test_the_handler_reads_the_parent_from_the_pack_not_the_request() -> None:+ """The foreign key would reject a forged parent anyway.++ Reading it from the already-ownership-checked pack means the rejection+ never has to happen, and a caller cannot probe which packs exist by+ watching which inserts are refused.+ """+ import inspect++ from app.api.v1.endpoints.mssp import assign_pack_to_child++ source = inspect.getsource(assign_pack_to_child)+ assert "parent_tenant_id=pack.parent_tenant_id" in source+ assert "parent_tenant_id=body." not in sourcediff --git a/tests/isolation/test_mssp_rls_live.py b/tests/isolation/test_mssp_rls_live.pynew file mode 100644index 000000000..6d3f175c3--- /dev/null+++ b/tests/isolation/test_mssp_rls_live.py@@ -0,0 +1,288 @@+"""Live-Postgres proof that the `mssp_*` policies isolate two MSSP portfolios.++Why this is a separate file from ``test_postgres_rls.py``+---------------------------------------------------------+That suite discovers tables by looking for a column literally named+``tenant_id``. Every ``mssp_*`` table names its tenants differently —+``parent_tenant_id`` and ``child_tenant_id``, or ``parent_id`` and+``child_id`` — so **all seven were invisible to it**, and its coverage+figure was a statement about the tables it could see. That blind spot is+the reason six of them carried no policy for as long as they did.++They also cannot be asserted the same way. A normal row belongs to one+tenant and the test is ``scoped read returns A's row, never B's``. An MSSP+row joins two tenants and *both* must read it: a policy naming only the+parent would hide from a customer the overrides applied to their own+detections, which is the transparency the adoption flow was rebuilt around.+So the assertion is "exactly one of the two seeded rows, from four different+directions, and zero from a fifth tenant that is party to neither".++The defect this would have caught+---------------------------------+Writing the pack and assignment policies as mutual subqueries is the+obvious way to express "a pack is visible to anyone it is assigned to" and+"an assignment is visible to the owning pack's parent". Both are true+statements; together they are unusable, and Postgres answers ``infinite+recursion detected in policy for relation "mssp_rule_packs"`` on the first+SELECT. ``check_rls_policy_shape.py`` passed throughout, because the shape+was right. Only running them found it.++Skips when no database answers, so a local ``pytest tests/isolation`` stays+green — but cannot skip where it is meant to run: ``integration.yml`` sets+``POSTGRES_RLS_ISOLATION_REQUIRED=1`` and an unreachable database is then a+failure, because a gate that quietly declines to run looks exactly like one+that ran and found nothing.+"""++from __future__ import annotations++import os+import uuid++import pytest++DSN = os.environ.get("DATABASE_URL", "")+ADMIN_DSN = os.environ.get("DATABASE_MIGRATION_URL", "").strip() or DSN+REQUIRED = os.environ.get("POSTGRES_RLS_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")++pytestmark = pytest.mark.skipif(+ "postgres" not in DSN and not REQUIRED,+ reason="no Postgres DSN; set DATABASE_URL, or POSTGRES_RLS_ISOLATION_REQUIRED=1 to demand one",+)++#: Two unrelated MSSPs, each managing one customer, plus an outsider who is+#: party to neither. Fixed UUIDs so a failure names the tenant.+MSSP_A = uuid.UUID("0c000000-0000-0000-0000-0000000aaaa1")+CHILD_A = uuid.UUID("0c000000-0000-0000-0000-0000000aaaa2")+MSSP_B = uuid.UUID("0c000000-0000-0000-0000-0000000bbbb1")+CHILD_B = uuid.UUID("0c000000-0000-0000-0000-0000000bbbb2")+OUTSIDER = uuid.UUID("0c000000-0000-0000-0000-0000000ccccc")++#: table → the four parties who must each see exactly their own row.+TABLES = (+ "mssp_delegations",+ "mssp_rule_overrides",+ "mssp_tenant_notes",+ "mssp_rule_packs",+ "mssp_rule_pack_assignments",+ "mssp_rule_pack_rules",+)+++def _asyncpg_dsn(url: str) -> str:+ return url.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")+++async def _connect(dsn: str):+ asyncpg = pytest.importorskip("asyncpg")+ if not dsn:+ pytest.skip("neither DATABASE_MIGRATION_URL nor DATABASE_URL is set")+ try:+ return await asyncpg.connect(_asyncpg_dsn(dsn))+ except Exception as exc: # noqa: BLE001+ # Both branches raise, but `pytest.fail` / `pytest.skip` are not+ # annotated NoReturn, so without the explicit raise this reads as a+ # function that sometimes returns None — `py/mixed-returns`. Same+ # shape and same fix as `_connect_admin` in test_postgres_rls.py.+ if REQUIRED:+ pytest.fail(f"POSTGRES_RLS_ISOLATION_REQUIRED is set but no Postgres answered: {exc}")+ pytest.skip(f"no Postgres: {exc}")+ raise+++async def _count_as(conn, tenant: uuid.UUID, table: str) -> int:+ async with conn.transaction():+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant))+ return await conn.fetchval(f"SELECT count(*) FROM {table}") # noqa: S608 - fixed list++[email protected](scope="module")+def seeded():+ """Two portfolios, torn down afterwards. Skips if the schema is absent.++ A *synchronous* fixture driving `asyncio.run`, matching the convention+ in `test_postgres_rls.py`, which has no async fixtures at all. An+ `async def` under a plain `@pytest.fixture` yields the generator object+ rather than the value — nothing is seeded, and every assertion then+ reads an empty table. That happened here, and the only reason it did+ not pass silently is the unscoped-read guard below, which exists for+ exactly this.+ """+ import asyncio++ state: dict = {}+ # Torn down *before* seeding as well as after. A run whose seed raised+ # part-way leaves rows behind, and the next run then dies on a unique+ # constraint rather than on the thing it was testing — which is how a+ # one-off failure becomes a permanently red job.+ asyncio.run(_teardown())+ asyncio.run(_seed(state))+ try:+ yield state+ finally:+ asyncio.run(_teardown())+++async def _teardown() -> None:+ admin = await _connect(ADMIN_DSN)+ try:+ for tenant in (MSSP_A, CHILD_A, MSSP_B, CHILD_B, OUTSIDER):+ await admin.execute("DELETE FROM tenants WHERE id = $1", tenant)+ finally:+ await admin.close()+++async def _seed(state: dict) -> None:+ admin = await _connect(ADMIN_DSN)+ exists = await admin.fetchval("SELECT to_regclass('public.mssp_rule_packs')")+ if exists is None:+ await admin.close()+ pytest.skip("the mssp_* schema is not present in this database")++ rule_id = uuid.uuid4()+ pack_a, pack_b = uuid.uuid4(), uuid.uuid4()+ try:+ for tenant, slug in (+ (MSSP_A, "rls-mssp-a"),+ (CHILD_A, "rls-child-a"),+ (MSSP_B, "rls-mssp-b"),+ (CHILD_B, "rls-child-b"),+ (OUTSIDER, "rls-outsider"),+ ):+ await admin.execute(+ "INSERT INTO tenants (id, slug, name) VALUES ($1, $2, $2) ON CONFLICT (id) DO NOTHING",+ tenant,+ slug,+ )+ await admin.execute(+ "INSERT INTO detection_rules (id, tenant_id, name) VALUES ($1, $2, 'rls-probe') ON CONFLICT (id) DO NOTHING",+ rule_id,+ MSSP_A,+ )+ for parent, child, pack in ((MSSP_A, CHILD_A, pack_a), (MSSP_B, CHILD_B, pack_b)):+ await admin.execute(+ "INSERT INTO mssp_delegations (parent_tenant_id, child_tenant_id) VALUES ($1,$2) ON CONFLICT DO NOTHING",+ parent,+ child,+ )+ await admin.execute(+ # `action` is NOT NULL with a CHECK of ('exclude','customize')+ # and no default. A hand-written probe schema that omitted it+ # passed locally and failed in CI against the real migration+ # chain — which is the argument for running this against the+ # chain rather than an approximation of it.+ "INSERT INTO mssp_rule_overrides "+ "(parent_tenant_id, child_tenant_id, rule_id, action) "+ "VALUES ($1,$2,$3,'exclude') ON CONFLICT DO NOTHING",+ parent,+ child,+ rule_id,+ )+ await admin.execute(+ "INSERT INTO mssp_tenant_notes (parent_id, child_id, body) VALUES ($1,$2,'probe')",+ parent,+ child,+ )+ await admin.execute(+ "INSERT INTO mssp_rule_packs (id, parent_tenant_id, name) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",+ pack,+ parent,+ f"rls-pack-{parent}",+ )+ await admin.execute(+ "INSERT INTO mssp_rule_pack_assignments (pack_id, parent_tenant_id, child_tenant_id) VALUES ($1,$2,$3)",+ pack,+ parent,+ child,+ )+ await admin.execute("INSERT INTO mssp_rule_pack_rules (pack_id, rule_id) VALUES ($1,$2)", pack, rule_id)+ state.update({"rule_id": rule_id, "pack_a": pack_a, "pack_b": pack_b})+ finally:+ await admin.close()++[email protected]("table", TABLES)+async def test_an_unscoped_read_sees_both_portfolios(seeded, table: str) -> None:+ """The step that stops every assertion below passing for the wrong reason.++ A scoped read returning one row on a table holding one row proves+ nothing. This establishes that two exist before anything is filtered.+ """+ admin = await _connect(ADMIN_DSN)+ try:+ total = await admin.fetchval(f"SELECT count(*) FROM {table}") # noqa: S608 - fixed list+ finally:+ await admin.close()+ assert total >= 2, f"{table} holds {total} rows; the isolation assertions would be vacuous"++[email protected]("table", TABLES)[email protected]("tenant", [MSSP_A, CHILD_A, MSSP_B, CHILD_B], ids=["mssp-a", "child-a", "mssp-b", "child-b"])+async def test_each_party_sees_exactly_its_own_row(seeded, table: str, tenant: uuid.UUID) -> None:+ """Both sides of the relationship read, and neither reads the other's.++ Four directions rather than two: a policy that names the parent and+ forgets the child passes a parent-only test while a customer's page+ renders empty, and the one table where that is missed is invisible+ until somebody asks why.+ """+ conn = await _connect(DSN)+ try:+ seen = await _count_as(conn, tenant, table)+ finally:+ await conn.close()+ assert seen == 1, f"{table} showed {seen} rows to {tenant}; exactly its own one was expected"++[email protected]("table", TABLES)+async def test_an_unrelated_tenant_sees_nothing(seeded, table: str) -> None:+ conn = await _connect(DSN)+ try:+ seen = await _count_as(conn, OUTSIDER, table)+ finally:+ await conn.close()+ assert seen == 0, f"{table} leaked {seen} row(s) to a tenant party to neither portfolio"+++async def test_no_policy_recurses(seeded) -> None:+ """A cycle raises rather than leaking, so it is a liveness bug, not a leak.++ Asserted anyway because it is how the pack policies were written first,+ and because a `SELECT` that raises in production reads to an operator+ as a database fault rather than as a policy they can fix.+ """+ conn = await _connect(DSN)+ try:+ for table in TABLES:+ try:+ await _count_as(conn, MSSP_A, table)+ except Exception as exc: # noqa: BLE001+ pytest.fail(f"reading {table} raised, which a recursive policy does: {exc}")+ finally:+ await conn.close()+++async def test_the_composite_key_refuses_a_forged_parent(seeded) -> None:+ """The denormalised `parent_tenant_id` cannot be made to lie.++ It exists only to keep the assignment policy free of a subquery; a+ column that could drift from the pack it mirrors would be worse than+ the recursion it replaced.+ """+ admin = await _connect(ADMIN_DSN)+ try:+ with pytest.raises(Exception) as exc: # noqa: PT011 - asyncpg's own type+ await admin.execute(+ "INSERT INTO mssp_rule_pack_assignments (pack_id, parent_tenant_id, child_tenant_id) VALUES ($1,$2,$3)",+ seeded["pack_a"],+ MSSP_B, # not pack_a's owner+ OUTSIDER,+ )+ assert "foreign key" in str(exc.value).lower()+ finally:+ await admin.close()