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.

fix(authz): make the database authoritative for every permission (#1085)

Beenu Arorad343492ff227
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 393375cc8..915a0ee0a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -344,6 +344,16 @@ jobs:
# themselves the same published number.
- name: Verify vendored aisoc_benchmark is in sync
run: python scripts/sync_vendored_benchmark.py --check
+ # Two permission models shipped side by side: 275 route dependencies
+ # read the hardcoded ROLE_PERMISSIONS map while 27 read the
+ # user_roles / role_permissions tables the console's RBAC screen
+ # writes to. An operator could grant a permission, watch it appear in
+ # the UI, and have 275 of 302 routes ignore it. There is one model
+ # now; this keeps it one.
+ - name: One permission model — self-test
+ run: python scripts/check_one_permission_model.py --self-test
+ - name: Verify the database is authoritative for permissions
+ run: python scripts/check_one_permission_model.py
# Thirteen Kafka clients across Python, Go and TypeScript, and not one
# passed a security protocol — so every one took the library default,
# which is PLAINTEXT in all three. The spine carries raw event bodies,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 71bba2e06..024b67cf1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- **Two permission models shipped side by side, and the one almost every route used ignored the database.** 275 route dependencies called the synchronous `require_permission`, which reads the hardcoded `ROLE_PERMISSIONS` map; 27 called `require_permission_db`, which reads the `user_roles` / `role_permissions` tables. The console ships a full RBAC administration screen writing to those tables — so an operator could grant a permission, watch it appear in the UI, and have **275 of 302 routes ignore it**. Revoking worked no better.
+
+ Not fixed by editing 275 call sites. `get_current_user` resolves the principal's effective permissions once, from the database, and `CurrentUser.require_permission` reads what it resolved — so every site changed at once and there is no second model left to drift.
+
+- **Resolving inside the permission check was tried first and was wrong.** It added a four-table join to every request and, far worse, made a transient database fault deny *every* request on the platform — a blip at the authorization layer becoming an outage. It also broke 84 tests that legitimately drive routes with a mocked session. Resolution happens at authentication, where a session already exists, and **fails open to the static map** with an `error` log rather than closed: that is the behaviour which shipped for the last fourteen releases, so falling back is no worse than before, while failing closed would be a new and much louder outage.
+
+- **The old fallback restored a deprovisioned user's access.** `has_permission_db` fell back to the static map whenever a user had no rows in `user_roles` — right for a fresh tenant with no RBAC configured, and wrong for a user whose roles were just removed, because **removing every role gave them their static permissions back**. The two cases are indistinguishable from the user's row count alone; the resolver asks one level up, whether the *tenant* has any roles at all. Tenant has none → static map. Tenant has roles, user has none → **deny**.
+
+- **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.
+
+
### Security
- **Four MSSP routes that manage portfolio membership and cross-tenant grants were counted as unauthorized, and were not.** They are guarded by `_admin_scope`, which resolves the caller's role inside an MSSP organisation and raises 403 unless they administer it — an authorization decision by any definition. The gate missed it twice over: organisation roles are a separate ordered ladder rather than tenant permissions, and `Depends(_admin_scope)` passes the dependency *by name* while the matcher only recognised `Depends(factory(...))`. Both fixed in the gate rather than worked around in the routes; the alternative was bolting a redundant tenant permission onto a surface that is not tenant-scoped, which is a worse design adopted to satisfy a gate, and that is how gates start being gamed.
diff --git a/ROADMAP.md b/ROADMAP.md
index c9c4327af..089d451a8 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 **253 rows — 253 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 **253 rows — 253 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 **253 rows — 253 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 **253 rows — 253 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 **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).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 4a15a7a7c..0a5dd5057 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: 253 rows
-The last row is the one worth reading first. It is the honest index: 253 rows
-The last row is the one worth reading first. It is the honest index: 253 rows
-The last row is the one worth reading first. It is the honest index: 253 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: 254 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 count
copied into prose goes stale in silence, which is why
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 869472a39..747965e3f 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -261,26 +261,27 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Every state-changing route makes an authorization decision, or declares why identity is one | `apps/docs/docs/operations/security.md` (RBAC); `README.md` | `ci.yml :: Python — Lint & Type-check` (`check_route_authz.py` — 224 of 245 state-changing routes authorize; the remaining 21 must each sit in a module carrying a written reason, checked in both directions so an undeclared module fails *and* a declaration describing no route fails) | GATED | **Proven by perturbation**: removing a real declaration and adding one for a nonexistent module were each run and each failed the gate. 218 → 224 authorizing. Two corrections worth recording: four MSSP routes guarding cross-tenant grants were counted as unauthorized while being correctly guarded by an organisation-role dependency, fixed in the gate rather than by bolting a redundant tenant permission onto a surface that is not tenant-scoped; and one route was gated and then **reverted**, because its existing pin argued every authenticated principal is a legitimate rater and the permission added here contradicted that — a prior decision with its reasoning written down outranks a later sweep that did not read it. One limit: the gate reads the signature, so it proves a decision is *made*, not that the permission chosen is the right one |
| 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 |
## Summary
-- GATED: 253
+- GATED: 254
## Summary
-- GATED: 253
+- GATED: 254
## Summary
-- GATED: 253
+- GATED: 254
## Summary
-- GATED: 253
+- GATED: 254
## Summary
-- GATED: 253
+- GATED: 254
- 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/scripts/check_one_permission_model.py b/scripts/check_one_permission_model.py
new file mode 100644
index 000000000..52d41a834
--- /dev/null
+++ b/scripts/check_one_permission_model.py
@@ -0,0 +1,273 @@
+#!/usr/bin/env python3
+"""There is one permission model, and the database is authoritative.
+
+Two shipped side by side. 275 route dependencies called the synchronous
+`require_permission`, reading the hardcoded `ROLE_PERMISSIONS` map; 27
+called `require_permission_db`, reading the `user_roles` /
+`role_permissions` tables the console's RBAC screen writes to. An operator
+could grant a permission, watch it appear in the UI, and have 275 of 302
+routes ignore it.
+
+The fix made the one factory they all already call read what authentication
+resolved from the database, so there is nothing left to edit per route —
+and nothing left for this gate to count. What it checks instead is that the
+single path stays single:
+
+1. **`CurrentUser.require_permission` consults the resolved set.** If it
+ goes back to reading only the static map, every route silently reverts.
+2. **`get_current_user` resolves one.** A principal built without it falls
+ through to the static map by design, which is right for a test double
+ and wrong for a real session.
+3. **Every RBAC write invalidates.** A grant that does not bump the version
+ leaves stale permissions cached on every replica, and for a *revoke*
+ that is the dangerous direction.
+4. **The static map is not read directly by route modules.** One importer
+ is the resolver's bootstrap path; a second is a route deciding for
+ itself, which is how the second model gets rebuilt.
+
+Each is checked structurally with `ast`, because every one of them is a
+question about which function calls which, and a text search cannot tell a
+call from a mention in a docstring.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import pathlib
+import sys
+from dataclasses import dataclass, field
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+
+from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
+
+DEPS = "services/api/app/api/v1/deps.py"
+RESOLVER = "services/api/app/core/permission_cache.py"
+RBAC_ROUTES = "services/api/app/api/v1/endpoints/rbac.py"
+ENDPOINTS = "services/api/app/api/v1/endpoints"
+
+#: Modules allowed to import the static map, each because it is the one
+#: place the fallback is supposed to live.
+STATIC_MAP_IMPORTERS = {
+ "services/api/app/core/permission_cache.py": "the resolver's bootstrap path, when a tenant has no roles",
+ "services/api/app/core/security.py": "defines it",
+ "services/api/app/core/role_grants.py": "derives the grantable-role ladder from it",
+ "services/api/app/api/v1/deps.py": "the fallback when nothing resolved a set",
+}
+
+
+@dataclass
+class Report:
+ findings: list[str] = field(default_factory=list)
+ files_read: int = 0
+ rbac_commits: int = 0
+ rbac_invalidations: int = 0
+ static_importers: list[str] = field(default_factory=list)
+
+
+def _tree(root: pathlib.Path, rel: str) -> ast.Module | None:
+ path = root / rel
+ if not path.is_file():
+ return None
+ try:
+ return ast.parse(path.read_text(encoding="utf-8"))
+ except SyntaxError:
+ return None
+
+
+def _function(tree: ast.AST, name: str) -> ast.FunctionDef | ast.AsyncFunctionDef | None:
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
+ return node
+ return None
+
+
+def _calls(node: ast.AST) -> set[str]:
+ return {getattr(c.func, "id", getattr(c.func, "attr", "")) for c in ast.walk(node) if isinstance(c, ast.Call)}
+
+
+def _reads(node: ast.AST, attribute: str) -> bool:
+ return any(isinstance(n, ast.Attribute) and n.attr == attribute for n in ast.walk(node))
+
+
+def inspect(root: pathlib.Path) -> Report:
+ report = Report()
+
+ deps = _tree(root, DEPS)
+ if deps is None:
+ report.findings.append(f"{DEPS} is missing or unparseable")
+ return report
+ report.files_read += 1
+
+ # 1. the check consults the resolved set
+ check = _function(deps, "require_permission")
+ enforcer = None
+ for node in ast.walk(deps):
+ if isinstance(node, ast.ClassDef) and node.name == "CurrentUser":
+ enforcer = _function(node, "require_permission")
+ if enforcer is None:
+ report.findings.append("CurrentUser.require_permission is gone")
+ else:
+ if not _reads(enforcer, "resolved_permissions"):
+ report.findings.append(
+ "CurrentUser.require_permission does not read `resolved_permissions`, so every route is back on the static map"
+ )
+ if "grants" not in _calls(enforcer):
+ report.findings.append(
+ "CurrentUser.require_permission does not call `grants()`, so wildcard handling has drifted from the resolver's"
+ )
+ if check is None:
+ report.findings.append("the require_permission factory is gone")
+
+ # 2. authentication resolves one
+ auth = _function(deps, "get_current_user")
+ if auth is None:
+ report.findings.append("get_current_user is gone")
+ elif "resolve_permissions" not in _calls(auth):
+ report.findings.append(
+ "get_current_user does not call `resolve_permissions`, so no principal ever carries "
+ "a database-backed set and the static map is the only model again"
+ )
+
+ # 3. every RBAC write invalidates
+ rbac = _tree(root, RBAC_ROUTES)
+ if rbac is None:
+ report.findings.append(f"{RBAC_ROUTES} is missing or unparseable")
+ else:
+ report.files_read += 1
+ for node in ast.walk(rbac):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ calls = _calls(node)
+ commits = sum(
+ 1 for c in ast.walk(node) if isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute) and c.func.attr == "commit"
+ )
+ if not commits:
+ continue
+ report.rbac_commits += commits
+ if "bump_version" in calls:
+ report.rbac_invalidations += 1
+ else:
+ report.findings.append(
+ f"{RBAC_ROUTES}:{node.lineno} {node.name}() commits an RBAC change and never "
+ "calls bump_version, so the old permissions stay cached on every replica"
+ )
+
+ # 4. no route module reads the static map directly
+ directory = root / ENDPOINTS
+ if directory.is_dir():
+ for path in sorted(directory.glob("*.py")):
+ rel = path.relative_to(root).as_posix()
+ if rel in STATIC_MAP_IMPORTERS:
+ continue
+ source = path.read_text(encoding="utf-8", errors="replace")
+ report.files_read += 1
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module == "app.core.security":
+ if any(a.name in ("ROLE_PERMISSIONS", "has_permission") for a in node.names):
+ report.static_importers.append(f"{rel}:{node.lineno}")
+
+ for site in report.static_importers:
+ report.findings.append(
+ f"{site} imports the static permission map directly. A route deciding for itself is "
+ "how the second model gets rebuilt; depend on require_permission instead"
+ )
+
+ return report
+
+
+def _verdict(report: Report) -> int:
+ if report.files_read == 0:
+ print(
+ "check_one_permission_model: read no files — refusing to report a tree with nothing in it as clean",
+ file=sys.stderr,
+ )
+ return 2
+ if report.findings:
+ print("check_one_permission_model: FAIL", file=sys.stderr)
+ for finding in report.findings:
+ print(f" {finding}", file=sys.stderr)
+ return 1
+ print(
+ f"check_one_permission_model: OK — the permission check reads what authentication "
+ f"resolved from the database, {report.rbac_invalidations} RBAC mutation(s) covering "
+ f"{report.rbac_commits} commit(s) invalidate the cache, and no route module reads the "
+ f"static map directly ({report.files_read} files)."
+ )
+ return 0
+
+
+def self_test() -> int:
+ import tempfile
+
+ root = repo_root()
+ extra: list[tuple[str, bool]] = [("the real tree passes", not inspect(root).findings)]
+
+ deps_source = (root / DEPS).read_text(encoding="utf-8")
+ rbac_source = (root / RBAC_ROUTES).read_text(encoding="utf-8")
+
+ def probe(description: str, *, deps: str | None = None, rbac: str | None = None) -> None:
+ with tempfile.TemporaryDirectory(prefix="aisoc-perm-gate-") as tmp:
+ base = pathlib.Path(tmp)
+ (base / DEPS).parent.mkdir(parents=True, exist_ok=True)
+ (base / RBAC_ROUTES).parent.mkdir(parents=True, exist_ok=True)
+ (base / DEPS).write_text(deps if deps is not None else deps_source, encoding="utf-8")
+ (base / RBAC_ROUTES).write_text(rbac if rbac is not None else rbac_source, encoding="utf-8")
+ extra.append((description, bool(inspect(base).findings)))
+
+ # The whole branch, not just its condition. A first draft flipped the
+ # condition to `False` and the case passed — `grants(self.resolved_...)`
+ # was still in the body, so the attribute was still mentioned and the
+ # structural read still found it. A regression removes the branch.
+ probe(
+ "detects a check that stops reading the resolved set",
+ deps=deps_source.replace(
+ """ elif self.resolved_permissions is not None:
+ # Database-backed: what the RBAC tables actually grant.
+ if not grants(self.resolved_permissions, permission):
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"Permission denied: {permission}",
+ )
+ elif not has_permission(self.role, permission):""",
+ """ elif not has_permission(self.role, permission):""",
+ ),
+ )
+ probe(
+ "detects authentication that stops resolving one",
+ deps=deps_source.replace("await resolve_permissions(", "await _disabled("),
+ )
+ probe(
+ "detects an RBAC write that does not invalidate",
+ rbac=rbac_source.replace("await bump_version(str(current_user.tenant_id))", "pass", 1),
+ )
+
+ # And a direction it must not fire in.
+ with tempfile.TemporaryDirectory(prefix="aisoc-perm-gate-ok-") as tmp:
+ base = pathlib.Path(tmp)
+ (base / DEPS).parent.mkdir(parents=True, exist_ok=True)
+ (base / RBAC_ROUTES).parent.mkdir(parents=True, exist_ok=True)
+ (base / DEPS).write_text(deps_source, encoding="utf-8")
+ (base / RBAC_ROUTES).write_text(rbac_source, encoding="utf-8")
+ extra.append(("accepts the unmodified pair", not inspect(base).findings))
+
+ return self_test_main(pathlib.Path(__file__).name, ["--check"], extra)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--check", action="store_true")
+ parser.add_argument(SELF_TEST_FLAG, action="store_true", dest="self_test")
+ args = parser.parse_args()
+ if args.self_test:
+ return self_test()
+ return _verdict(inspect(repo_root()))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.py
index 47196e359..e88d4323d 100644
--- a/services/api/app/api/v1/deps.py
+++ b/services/api/app/api/v1/deps.py
@@ -21,6 +21,7 @@ activates the RLS policies defined in ``migrations/002_rls.sql``.
...
"""
+import logging
import uuid
from datetime import UTC, datetime
from typing import Annotated
@@ -38,10 +39,13 @@ from app.api.v1.dev_auth import (
DEMO_USER_ROLE,
is_dev_mode,
)
+from app.core.permission_cache import grants, resolve_permissions
from app.core.security import decode_token, has_permission, hash_api_key, token_is_revoked
from app.db.database import get_db
from app.models.tenant import ApiKey, User
+logger = logging.getLogger("aisoc.deps")
+
bearer_scheme = HTTPBearer(auto_error=False)
_API_KEY_PREFIX = "aisoc_"
@@ -68,6 +72,7 @@ class CurrentUser:
email: str,
scopes: list[str] | None = None,
api_key_prefix: str | None = None,
+ resolved_permissions: frozenset[str] | None = None,
) -> None:
self.user_id = user_id
self.tenant_id = tenant_id
@@ -83,6 +88,17 @@ class CurrentUser:
# key, or disable a person — and the log could not tell an
# investigator which one had happened.
self.api_key_prefix = api_key_prefix
+ # What the RBAC tables say this principal holds, resolved once at
+ # authentication. `None` means "nothing resolved it", which is the
+ # case for a directly-constructed principal in a test and for the
+ # dev-mode user, and falls through to the static map.
+ #
+ # The whole reason this field exists: 275 route dependencies checked
+ # the hardcoded `ROLE_PERMISSIONS` map while 27 checked the tables
+ # the console's RBAC screen writes to, so an operator could grant a
+ # permission, watch it appear in the UI, and have 275 of 302 routes
+ # ignore it.
+ self.resolved_permissions = resolved_permissions
def __repr__(self) -> str:
# Without this a stray `str(user)` persists `<...CurrentUser object at
@@ -101,13 +117,20 @@ class CurrentUser:
status_code=status.HTTP_403_FORBIDDEN,
detail=f"API key missing scope: {permission}",
)
- else:
- # JWT / role path — static ROLE_PERMISSIONS fallback
- if not has_permission(self.role, permission):
+ elif self.resolved_permissions is not None:
+ # Database-backed: what the RBAC tables actually grant.
+ if not grants(self.resolved_permissions, permission):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied: {permission}",
)
+ elif not has_permission(self.role, permission):
+ # Nothing resolved a set for this principal, so the static map
+ # is the only answer available.
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"Permission denied: {permission}",
+ )
async def has_permission_db(self, permission: str, db: AsyncSession) -> bool:
"""Check permission via RBAC tables (granular RBAC).
@@ -273,11 +296,32 @@ async def get_current_user(
headers={"WWW-Authenticate": "Bearer"},
)
+ # Resolved once, here, where a session already exists. Doing it in the
+ # permission dependency instead would mean a query per check and would
+ # make a database blip deny every request.
+ #
+ # Fails *open to the static map* rather than closed, deliberately: this
+ # is authentication, and a transient database fault must not lock every
+ # operator out of the platform mid-incident. The static map is the
+ # behaviour that shipped for the last fourteen releases, so falling back
+ # to it is no worse than before — whereas failing closed would be a new
+ # and much louder outage. The event is logged at error, not debug.
+ resolved: frozenset[str] | None = None
+ try:
+ resolved = await resolve_permissions(db, tenant_id=user.tenant_id, user_id=user.id, static_role=user.role)
+ except Exception as exc: # noqa: BLE001
+ logger.error(
+ "permission resolution failed for user %s; falling back to the static role map: %s",
+ str(user.id).replace("\r", "").replace("\n", " ")[:64],
+ str(exc).replace("\r", "").replace("\n", " ")[:200],
+ )
+
return CurrentUser(
user_id=user.id,
tenant_id=user.tenant_id,
role=user.role,
email=user.email,
+ resolved_permissions=resolved,
)
@@ -288,7 +332,27 @@ async def get_current_active_user(
def require_permission(permission: str):
- """Factory for permission-checking dependencies."""
+ """Factory for permission-checking dependencies, database-backed.
+
+ This used to consult the hardcoded `ROLE_PERMISSIONS` map only, while a
+ second factory, `require_permission_db`, consulted the `user_roles` /
+ `role_permissions` tables the console's RBAC administration surface
+ writes to. 275 routes used the first and 27 used the second, so an
+ operator could grant a permission, watch it appear in the UI, and have
+ 275 of 302 routes ignore it.
+
+ The resolution happens once, in `get_current_user`, where a session
+ already exists — not here. A query per permission check would mean a
+ database blip denies every request, turning a transient fault into a
+ platform-wide outage at the authorization layer, and it broke 84 tests
+ that legitimately drive routes with a mocked session.
+
+ So this stays synchronous and reads what authentication resolved.
+
+ API keys keep their own path. A key's scopes are an explicit, narrower
+ grant chosen at mint time — resolving a key to its owner's full role
+ would widen it, which is the opposite of what a scoped key is for.
+ """
async def _check(current_user: Annotated[CurrentUser, Depends(get_current_user)]) -> CurrentUser:
current_user.require_permission(permission)
diff --git a/services/api/app/api/v1/endpoints/rbac.py b/services/api/app/api/v1/endpoints/rbac.py
index be0c23609..669e5169b 100644
--- a/services/api/app/api/v1/endpoints/rbac.py
+++ b/services/api/app/api/v1/endpoints/rbac.py
@@ -18,6 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.api.v1.deps import AuthUser, require_permission
+from app.core.permission_cache import bump_version
from app.core.role_grants import RoleGrantDenied, authorize_permission_grant
from app.db.rls import TenantDBSession
from app.models.rbac import Permission, Role, RolePermission, UserRole
@@ -181,6 +182,7 @@ async def create_role(
db.add(RolePermission(role_id=role.id, permission_id=perm.id))
await db.commit()
+ await bump_version(str(current_user.tenant_id))
await db.refresh(role)
return RoleOut(
@@ -242,6 +244,7 @@ async def update_role(
db.add(RolePermission(role_id=role.id, permission_id=perm.id))
await db.commit()
+ await bump_version(str(current_user.tenant_id))
await db.refresh(role)
perms_out = await _load_role_permissions(db, role.id)
return RoleOut(
@@ -265,6 +268,7 @@ async def delete_role(
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="System roles cannot be deleted")
await db.delete(role)
await db.commit()
+ await bump_version(str(current_user.tenant_id))
# ──────────────────────────────────────────────
@@ -327,6 +331,7 @@ async def assign_role(
assignment = UserRole(user_id=user_id, role_id=role.id, assigned_by=current_user.user_id)
db.add(assignment)
await db.commit()
+ await bump_version(str(current_user.tenant_id))
return UserRoleOut(user_id=user_id, role_id=role.id, role_name=role.name)
@@ -340,6 +345,7 @@ async def revoke_role(
"""Revoke a role from a user."""
await db.execute(delete(UserRole).where(UserRole.user_id == user_id, UserRole.role_id == role_id))
await db.commit()
+ await bump_version(str(current_user.tenant_id))
# ──────────────────────────────────────────────
diff --git a/services/api/app/core/permission_cache.py b/services/api/app/core/permission_cache.py
new file mode 100644
index 000000000..a69d5fb85
--- /dev/null
+++ b/services/api/app/core/permission_cache.py
@@ -0,0 +1,266 @@
+"""One permission model, read from the database, cached per replica.
+
+The problem
+-----------
+Two permission models shipped side by side. 275 route dependencies called
+the **synchronous** `require_permission`, which consults the hardcoded
+`ROLE_PERMISSIONS` map in `app/core/security.py`; 27 called the **async**
+`require_permission_db`, which consults the `user_roles` /
+`role_permissions` tables. The console has a full RBAC administration
+surface writing to those tables, so an operator could grant a permission,
+watch it appear in the UI, and have 275 of 302 routes ignore it entirely.
+
+The fix is not to edit 275 call sites. It is to make the one factory they
+all already call read from the database, which changes every site at once
+and leaves no second model to drift.
+
+The fallback, and why its old shape was wrong
+---------------------------------------------
+`has_permission_db` fell back to the static map whenever a user had no rows
+in `user_roles`. That is right for bootstrap — a fresh tenant has no RBAC
+configured and must still work — and wrong for deprovisioning: **removing
+every role from a user restored their static permissions** rather than
+removing their access. The two cases look identical from the user's row
+count alone, and the distinguishing fact is one level up: does the *tenant*
+have any roles at all?
+
+* tenant has no roles configured → static map (bootstrap, nothing to read)
+* tenant has roles, this user has none → **deny** (they were deprovisioned)
+* tenant has roles, this user has some → those, and only those
+
+The cache
+---------
+A permission check on every request would mean a four-table join on every
+request. Resolved sets are cached per replica, keyed by
+`(tenant_id, user_id, version)`.
+
+`version` is the point. A TTL alone means a revoked permission keeps
+working for the length of the TTL on every replica that has it cached,
+which for an access revocation is the wrong failure mode. The version is a
+per-tenant counter in Redis, bumped whenever a grant changes, so a revoke
+invalidates **every** replica on its next request rather than when their
+clocks happen to expire.
+
+Without Redis the version is unavailable and the cache falls back to a
+short TTL, which is honest about what it can offer: a single-process
+deployment is correct either way, and a multi-replica one without Redis
+converges within the TTL. That degradation is logged once, not silently.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from dataclasses import dataclass, field
+from functools import lru_cache
+from typing import Any, Final
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = logging.getLogger("aisoc.permissions")
+
+#: How long a resolved set survives when no version counter is reachable.
+#: Short, because this is the window in which a revoked permission still
+#: works on a replica that has not noticed.
+FALLBACK_TTL_SECONDS: Final[float] = 15.0
+
+#: Bound on the number of cached principals per replica. A SOC has far
+#: fewer concurrent operators than this; the cap exists so an attacker
+#: cycling user ids cannot grow the map without limit.
+MAX_ENTRIES: Final[int] = 4096
+
+_REDIS_VERSION_KEY: Final[str] = "aisoc:rbac:version:{tenant_id}"
+
+
+@dataclass
+class _Entry:
+ permissions: frozenset[str]
+ version: str
+ expires_at: float
+
+
+@dataclass
+class PermissionCache:
+ """Per-replica cache of resolved permission sets."""
+
+ _entries: dict[tuple[str, str], _Entry] = field(default_factory=dict)
+ _warned_no_redis: bool = False
+
+ hits: int = 0
+ misses: int = 0
+
+ def get(self, *, tenant_id: str, user_id: str, version: str) -> frozenset[str] | None:
+ entry = self._entries.get((tenant_id, user_id))
+ if entry is None:
+ self.misses += 1
+ return None
+ # A version mismatch beats a live TTL: a grant changed, so whatever
+ # is cached describes the world before that change.
+ if entry.version != version or entry.expires_at <= time.monotonic():
+ self._entries.pop((tenant_id, user_id), None)
+ self.misses += 1
+ return None
+ self.hits += 1
+ return entry.permissions
+
+ def put(self, *, tenant_id: str, user_id: str, version: str, permissions: frozenset[str]) -> None:
+ if len(self._entries) >= MAX_ENTRIES:
+ # Oldest by expiry. Not an LRU: this bound is a safety valve for
+ # a pathological key space, not a hot-path eviction policy, and
+ # an LRU here would add bookkeeping to every read.
+ oldest = min(self._entries, key=lambda k: self._entries[k].expires_at)
+ self._entries.pop(oldest, None)
+ self._entries[(tenant_id, user_id)] = _Entry(
+ permissions=permissions,
+ version=version,
+ expires_at=time.monotonic() + FALLBACK_TTL_SECONDS,
+ )
+
+ def invalidate_tenant(self, tenant_id: str) -> int:
+ """Drop this replica's entries for one tenant.
+
+ Local only. Cross-replica invalidation is the version counter, not
+ this — a method that dropped local entries and called itself
+ "invalidation" would be the kind of control that looks complete and
+ covers one process out of N.
+ """
+ doomed = [k for k in self._entries if k[0] == tenant_id]
+ for key in doomed:
+ self._entries.pop(key, None)
+ return len(doomed)
+
+ def clear(self) -> None:
+ self._entries.clear()
+ self.hits = 0
+ self.misses = 0
+
+
+#: Process-wide instance. One per replica by construction.
+CACHE = PermissionCache()
+
+
+@lru_cache(maxsize=1)
+def _redis_client() -> Any | None:
+ """Built once and reused.
+
+ `from_url` is lazy, so this costs nothing until the first command, and
+ rebuilding it per call would open a connection per permission check.
+
+ Memoised rather than held in a pair of module globals. The first draft
+ used `_CLIENT` plus a `_CLIENT_TRIED` flag to distinguish "no client"
+ from "not asked yet", which CodeQL correctly flagged as a global whose
+ only job was bookkeeping the cache already does — `lru_cache` caches a
+ `None` return just as happily as a client.
+ """
+ try:
+ from redis.asyncio import from_url # noqa: PLC0415
+
+ from app.core.config import settings # noqa: PLC0415
+
+ return from_url(str(settings.REDIS_URL), decode_responses=True)
+ except Exception: # noqa: BLE001 - absence is a supported configuration
+ return None
+
+
+def reset_for_tests() -> None:
+ """Drop the cache and the client handle. Tests only."""
+ _redis_client.cache_clear()
+ CACHE.clear()
+ CACHE._warned_no_redis = False
+
+
+async def current_version(tenant_id: str) -> str:
+ """The tenant's RBAC generation, or a TTL-only sentinel.
+
+ Returning a constant when Redis is absent is deliberate: every entry
+ then shares one version and expiry alone governs them, which is the
+ documented degradation rather than a silent one.
+ """
+ client = _redis_client()
+ if client is None:
+ if not CACHE._warned_no_redis:
+ CACHE._warned_no_redis = True
+ logger.warning(
+ "permission cache: no Redis, so a permission change reaches other replicas "
+ "only after the %.0fs TTL rather than on their next request",
+ FALLBACK_TTL_SECONDS,
+ )
+ return "ttl-only"
+ try:
+ raw = await client.get(_REDIS_VERSION_KEY.format(tenant_id=tenant_id))
+ return (raw.decode() if isinstance(raw, bytes) else str(raw)) if raw else "0"
+ except Exception: # noqa: BLE001 - a Redis blip must not deny a request
+ return "ttl-only"
+
+
+async def bump_version(tenant_id: str) -> None:
+ """Invalidate this tenant's cached permissions on every replica.
+
+ Called after any write to `user_roles` or `role_permissions`. Failing
+ soft on a Redis error is correct here and only here: the TTL still
+ bounds the staleness, and refusing the *grant* because the cache could
+ not be invalidated would make RBAC administration depend on Redis.
+ """
+ client = _redis_client()
+ if client is None:
+ CACHE.invalidate_tenant(tenant_id)
+ return
+ try:
+ await client.incr(_REDIS_VERSION_KEY.format(tenant_id=tenant_id))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("permission cache: could not bump the RBAC version: %s", exc)
+ CACHE.invalidate_tenant(tenant_id)
+
+
+async def _tenant_has_rbac(db: AsyncSession, tenant_id: Any) -> bool:
+ """Whether this tenant has configured any roles at all.
+
+ The fact that separates bootstrap from deprovisioning, and the reason
+ the old fallback was unsafe.
+ """
+ from app.models.rbac import Role # noqa: PLC0415
+
+ total = await db.scalar(select(func.count()).select_from(Role).where(Role.tenant_id == tenant_id))
+ return bool(total)
+
+
+async def resolve_permissions(db: AsyncSession, *, tenant_id: Any, user_id: Any, static_role: str) -> frozenset[str]:
+ """This principal's effective permissions, database first.
+
+ `static_role` is consulted only on the bootstrap path, where the tenant
+ has no roles for the database to answer with.
+ """
+ from app.core.security import ROLE_PERMISSIONS # noqa: PLC0415
+ from app.models.rbac import Permission as PermModel # noqa: PLC0415
+ from app.models.rbac import Role, RolePermission, UserRole # noqa: PLC0415
+
+ tenant_key, user_key = str(tenant_id), str(user_id)
+ version = await current_version(tenant_key)
+ cached = CACHE.get(tenant_id=tenant_key, user_id=user_key, version=version)
+ if cached is not None:
+ return cached
+
+ rows = await db.execute(
+ select(PermModel.name)
+ .join(RolePermission, RolePermission.permission_id == PermModel.id)
+ .join(Role, Role.id == RolePermission.role_id)
+ .join(UserRole, UserRole.role_id == Role.id)
+ .where(UserRole.user_id == user_id, Role.tenant_id == tenant_id)
+ )
+ granted = {row[0] for row in rows.all()}
+
+ if not granted and not await _tenant_has_rbac(db, tenant_id):
+ # Bootstrap: nothing to read, so the static map is the only answer
+ # there is. A tenant that *has* roles and gave this user none has
+ # answered the question — with "none".
+ granted = set(ROLE_PERMISSIONS.get(static_role, []))
+
+ resolved = frozenset(granted)
+ CACHE.put(tenant_id=tenant_key, user_id=user_key, version=version, permissions=resolved)
+ return resolved
+
+
+def grants(permissions: frozenset[str], wanted: str) -> bool:
+ """Whether a resolved set covers *wanted*, including wildcards."""
+ return "*" in permissions or wanted in permissions or f"{wanted.split(':')[0]}:*" in permissions
diff --git a/services/api/tests/test_database_backed_permissions.py b/services/api/tests/test_database_backed_permissions.py
new file mode 100644
index 000000000..6d4cb981d
--- /dev/null
+++ b/services/api/tests/test_database_backed_permissions.py
@@ -0,0 +1,255 @@
+"""One permission model, and the database is authoritative.
+
+Two models shipped side by side. 275 route dependencies called the
+synchronous `require_permission`, which reads the hardcoded
+`ROLE_PERMISSIONS` map; 27 called `require_permission_db`, which reads the
+`user_roles` / `role_permissions` tables. The console ships a full RBAC
+administration surface writing to those tables — so an operator could grant
+a permission, watch it appear in the UI, and have **275 of 302 routes
+ignore it**.
+
+Tested in both directions, which is the only way this means anything:
+
+* a permission the database grants and the static map does not must be
+ **allowed** — otherwise the RBAC screen is decorative;
+* a permission the static map grants and the database does not must be
+ **denied** — otherwise revoking access does nothing.
+
+The second is the one that was broken in a subtle way. `has_permission_db`
+fell back to the static map whenever a user had no rows in `user_roles`,
+which is right for a fresh tenant and wrong for a deprovisioned user:
+**removing every role restored their static permissions.** The two cases
+are indistinguishable from the user's row count alone, so the resolver asks
+one level up — does the *tenant* have any roles at all?
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.core.permission_cache import (
+ CACHE,
+ FALLBACK_TTL_SECONDS,
+ PermissionCache,
+ grants,
+ reset_for_tests,
+ resolve_permissions,
+)
+from app.core.security import ROLE_PERMISSIONS
+from fastapi import HTTPException
+
+
[email protected](autouse=True)
+def _clean_cache():
+ reset_for_tests()
+ yield
+ reset_for_tests()
+
+
+class _FakeResult:
+ def __init__(self, rows: list[tuple[str]]) -> None:
+ self._rows = rows
+
+ def all(self) -> list[tuple[str]]:
+ return self._rows
+
+
+class _FakeSession:
+ """A session that answers the two queries the resolver makes.
+
+ `granted` is what `user_roles` joins to; `tenant_role_count` is how many
+ roles the tenant has configured, which is the fact that separates a
+ fresh tenant from a deprovisioned user.
+ """
+
+ def __init__(self, *, granted: list[str], tenant_role_count: int) -> None:
+ self._granted = granted
+ self._tenant_role_count = tenant_role_count
+ self.executed = 0
+
+ async def execute(self, *_args, **_kwargs):
+ self.executed += 1
+ return _FakeResult([(name,) for name in self._granted])
+
+ async def scalar(self, *_args, **_kwargs) -> int:
+ return self._tenant_role_count
+
+
+TENANT = uuid.uuid4()
+USER = uuid.uuid4()
+
+
+class TestTheDatabaseIsAuthoritative:
+ async def test_a_database_grant_the_static_map_lacks_is_allowed(self) -> None:
+ """Otherwise the console's RBAC screen is decorative."""
+ assert "lake:admin" not in ROLE_PERMISSIONS["viewer"]
+ resolved = await resolve_permissions(
+ _FakeSession(granted=["lake:admin"], tenant_role_count=3),
+ tenant_id=TENANT,
+ user_id=USER,
+ static_role="viewer",
+ )
+ assert grants(resolved, "lake:admin")
+
+ async def test_a_static_grant_the_database_lacks_is_denied(self) -> None:
+ """Otherwise revoking access does nothing.
+
+ `tenant_admin` holds `alerts:write` statically. A tenant that has
+ configured roles and given this user none has answered the
+ question, and the answer is "none".
+ """
+ assert "alerts:write" in ROLE_PERMISSIONS["tenant_admin"]
+ resolved = await resolve_permissions(
+ _FakeSession(granted=[], tenant_role_count=4),
+ tenant_id=TENANT,
+ user_id=USER,
+ static_role="tenant_admin",
+ )
+ assert not grants(resolved, "alerts:write")
+ assert resolved == frozenset()
+
+ async def test_a_tenant_with_no_roles_falls_back_to_the_static_map(self) -> None:
+ """Bootstrap. A fresh tenant has nothing for the database to answer with.
+
+ This is the case the old fallback was written for, and it stays —
+ the defect was that it also covered the case above.
+ """
+ resolved = await resolve_permissions(
+ _FakeSession(granted=[], tenant_role_count=0),
+ tenant_id=TENANT,
+ user_id=USER,
+ static_role="tenant_admin",
+ )
+ assert grants(resolved, "alerts:write")
+
+ async def test_the_two_empty_cases_are_distinguished_by_the_tenant_not_the_user(self) -> None:
+ """The whole correction, stated as one assertion.
+
+ Both principals have zero rows in `user_roles`. One is a fresh
+ tenant and must work; the other was deprovisioned and must not.
+ """
+ fresh = await resolve_permissions(
+ _FakeSession(granted=[], tenant_role_count=0),
+ tenant_id=TENANT,
+ user_id=USER,
+ static_role="soc_analyst",
+ )
+ deprovisioned = await resolve_permissions(
+ _FakeSession(granted=[], tenant_role_count=7),
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ static_role="soc_analyst",
+ )
+ assert fresh != deprovisioned
+ assert fresh and not deprovisioned
+
+
+class TestThePrincipalUsesWhatWasResolved:
+ def test_a_resolved_set_overrides_the_static_role(self) -> None:
+ user = CurrentUser(
+ user_id=USER,
+ tenant_id=TENANT,
+ role="tenant_admin",
+ resolved_permissions=frozenset({"alerts:read"}),
+ )
+ user.require_permission("alerts:read")
+ with pytest.raises(HTTPException) as exc:
+ user.require_permission("alerts:write")
+ assert exc.value.status_code == 403
+
+ def test_no_resolved_set_falls_through_to_the_static_map(self) -> None:
+ """Which is what keeps directly-constructed principals working.
+
+ Every test that drives a route with a mocked session builds a
+ `CurrentUser` by hand. Making the permission dependency itself
+ query would have broken 84 of them — and, more importantly, would
+ mean a database blip denies every request on the platform.
+ """
+ user = CurrentUser(user_id=USER, tenant_id=TENANT, role="tenant_admin", email="[email protected]")
+ user.require_permission("alerts:write")
+
+ def test_an_api_key_still_uses_its_own_scopes(self) -> None:
+ """A key's scopes are a deliberately narrower grant.
+
+ Resolving a key to its owner's full role would widen it, which is
+ the opposite of what a scoped key is for.
+ """
+ user = CurrentUser(
+ user_id=USER,
+ tenant_id=TENANT,
+ role="tenant_admin",
+ scopes=["alerts:read"],
+ resolved_permissions=frozenset({"*"}),
+ )
+ user.require_permission("alerts:read")
+ with pytest.raises(HTTPException):
+ user.require_permission("alerts:write")
+
+
+class TestTheCacheInvalidates:
+ def test_a_version_change_beats_a_live_ttl(self) -> None:
+ """A revoke must not wait for a clock.
+
+ 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.
+ """
+ cache = PermissionCache()
+ cache.put(tenant_id="t", user_id="u", version="1", permissions=frozenset({"a"}))
+ assert cache.get(tenant_id="t", user_id="u", version="1") == frozenset({"a"})
+ assert cache.get(tenant_id="t", user_id="u", version="2") is None
+
+ def test_invalidating_a_tenant_leaves_other_tenants_alone(self) -> None:
+ cache = PermissionCache()
+ cache.put(tenant_id="t1", user_id="u", version="1", permissions=frozenset({"a"}))
+ cache.put(tenant_id="t2", user_id="u", version="1", permissions=frozenset({"b"}))
+ assert cache.invalidate_tenant("t1") == 1
+ assert cache.get(tenant_id="t1", user_id="u", version="1") is None
+ assert cache.get(tenant_id="t2", user_id="u", version="1") == frozenset({"b"})
+
+ def test_the_entry_count_is_bounded(self) -> None:
+ """So an attacker cycling user ids cannot grow the map without limit."""
+ from app.core.permission_cache import MAX_ENTRIES
+
+ cache = PermissionCache()
+ for index in range(MAX_ENTRIES + 50):
+ cache.put(tenant_id="t", user_id=str(index), version="1", permissions=frozenset())
+ assert len(cache._entries) <= MAX_ENTRIES
+
+ def test_the_ttl_is_short_enough_to_bound_a_redis_outage(self) -> None:
+ """It is the whole staleness window when no version counter answers."""
+ assert 0 < FALLBACK_TTL_SECONDS <= 30
+
+ async def test_a_second_resolution_does_not_requery(self) -> None:
+ """A four-table join per request is what the cache exists to avoid."""
+ session = _FakeSession(granted=["alerts:read"], tenant_role_count=2)
+ for _ in range(3):
+ await resolve_permissions(session, tenant_id=TENANT, user_id=USER, static_role="viewer")
+ assert session.executed == 1, f"queried {session.executed} times; the cache is not holding"
+
+
+class TestWildcards:
+ @pytest.mark.parametrize(
+ ("held", "wanted", "expected"),
+ [
+ (frozenset({"*"}), "anything:at:all", True),
+ (frozenset({"alerts:*"}), "alerts:write", True),
+ (frozenset({"alerts:*"}), "cases:write", False),
+ (frozenset({"alerts:read"}), "alerts:write", False),
+ (frozenset(), "alerts:read", False),
+ ],
+ )
+ def test_grants(self, held: frozenset[str], wanted: str, expected: bool) -> None:
+ assert grants(held, wanted) is expected
+
+
+def test_the_cache_is_a_single_process_wide_instance() -> None:
+ """One per replica by construction, which is what the version counter assumes."""
+ from app.core import permission_cache
+
+ assert isinstance(permission_cache.CACHE, PermissionCache)
+ assert permission_cache.CACHE is CACHE