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): recognise organisation-role decisions and declare the rest (#1081)

Beenu Arorac6bf6b503f4e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 252b5ff51..54c33a1a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### 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.
+
+- **`POST /knowledge-base/query` now requires `knowledge_base:read`.** Its previous pin had deliberately left it ungated and said exactly why: every existing candidate permission was either held by every role including machine keys, or restricted to tenant administrators, which would take the runbooks away from the analysts who need them mid-incident. It asked for a new entitlement to be *written down* rather than reverse-engineered from a role list. This is that entitlement — held by every role that can read an alert including `viewer`, because reading a runbook during an incident is not a privileged act, and deliberately **not** held by `api_service`, so a machine key scoped to ingestion cannot exfiltrate the library. The open half of the original question stands and is recorded: retrieval and LLM synthesis share one entitlement, and splitting them needs a view on what a model call over tenant content costs.
+
+- **`POST /plugins/{id}/rate` was gated and then deliberately un-gated again.** Its existing pin argued that every authenticated principal is a legitimate rater, that the vocabulary has no permission for expressing an opinion, and that the real integrity question is one-vote-per-user — storage and product, not authorization. That reasoning holds, the permission added here excluded `viewer` and so contradicted it, and the change was reverted. Recorded because a prior decision with its reasoning written down should outrank a later sweep that did not read it.
+
+- **The identity-only ceiling is no longer a bare number.** `MAX_UNAUTHORIZED` said "21 routes are excused" and nothing about which or why. Every identity-only route must now sit in a module with a **declared reason** — SCIM authenticates with its own bearer token and resolves no tenant role, passkeys and push and saved views and on-call act on the caller's own resource, `auth.py` is sign-in itself and has no principal to check before authenticating. Checked in both directions: an undeclared module fails, and a declaration that no longer describes any route fails too, so the list cannot become a place excuses outlive the thing they excused. Both directions were proven by perturbing the declaration and watching the gate fail.
+
+ State-changing routes that authorize: **218 → 224**.
+
+
### BREAKING
- **`/api/v1/shifts` is gone, and `/api/v1/threatintel/stix/*` reads answer 404 outside demo mode.** Neither had a caller: nothing in `apps/web`, no SDK, and no other service referenced either, and the console's shift page is demo-gated and renders its own sample data client-side. If you were calling them, you were reading records nobody entered.
diff --git a/ROADMAP.md b/ROADMAP.md
index 367071c07..ada4cf7a9 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,9 +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 **250 rows — 250 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 **250 rows — 250 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 **250 rows — 250 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 **251 rows — 251 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 **251 rows — 251 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 **251 rows — 251 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 **251 rows — 251 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 d080c6d8e..e7965e927 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,9 +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: 250 rows
-The last row is the one worth reading first. It is the honest index: 250 rows
-The last row is the one worth reading first. It is the honest index: 250 rows
+The last row is the one worth reading first. It is the honest index: 251 rows
+The last row is the one worth reading first. It is the honest index: 251 rows
+The last row is the one worth reading first. It is the honest index: 251 rows
+The last row is the one worth reading first. It is the honest index: 251 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 25aee7c16..2d305c8ba 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -258,22 +258,27 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| No route module keeps state in a module global, or serves invented data | `README.md` (real vs synthetic data); `docs/audit/REPOSITORY_REALITY.md` | `ci.yml :: Python — Lint & Type-check` (`check_python_route_state.py` — parses every route module under `services/*/app/api` with `ast` and fails on a module-level mutable a handler writes to, by rebinding, by a mutating method, by a subscript store or through a subscript load, and on a container named as sample data with no demo gate in the file. 12 self-test cases, five of them controls) + `ci.yml :: Python — Tests` (`services/api/tests/test_no_fabricated_shift_or_taxii_data.py`) | GATED | **Proven against the pre-fix tree**: 21 findings on the first run; 4 of the 6 behaviour cases fail at `48234dc5`. Two of the gate's own rules were wrong first and the corrections are the durable part: a shape heuristic produced four false positives out of four detections on real configuration tables, so the name is the signal; and the allowlist credited an entry on the name alone rather than on an actual suppression, so a fixed defect kept its excuse. **15 entries remain, ratcheted** — five are not defects (a log de-duplicator, two caches of static artefacts, global-by-design community content) and the rest name the plan item that gives them a table. One limit: the gate reads route modules, so a service that keeps shared state in a helper module its handlers import is out of scope |
| Platform data is not carried in the clear between services | `apps/docs/docs/operations/security.md`; `README.md` (architecture) | `ci.yml :: Python — Lint & Type-check` (`check_kafka_transport.py` — all 13 client construction sites across Python, Go and TypeScript pass a resolved transport, checked through the AST so a comment cannot satisfy it, **and** the resolver is called and required to refuse production cleartext, allow development plaintext, and reject a typo rather than defaulting; plus `sync_vendored_kafka_security.py --check`) + `ci.yml :: Python — Tests` (`services/api/tests/test_transport_security_defaults.py`) | GATED | **Proven against the pre-fix tree**: 13 clients unwired, 10 of 13 cases fail at `48234dc5`. The two-direction check is the point — checking call sites alone would pass a tree where every site calls a resolver that always answers PLAINTEXT. The sync gate also re-derives Kafka users from the tree, so an eighth service that never takes a copy fails rather than running plaintext. Two limits: `sslmode` is **reported at boot, not enforced** (every service builds its own engine and the collector is the one place they all pass through), and the compose DSN keeps `sslmode=disable` deliberately because the bundled Postgres serves no certificate |
| No integration ships a working credential nobody chose | `apps/docs/docs/operations/security.md` (secrets) | `ci.yml :: Python — Tests` (`services/purple-team/tests/test_caldera_key_has_no_default.py`, 4 cases: the published literal is absent from code, the setting defaults to empty, building a client without a key raises and names the variable, and a configured key still builds one) | GATED | **Proven against the pre-fix tree**: 3 of 4 fail at `48234dc5`. `ADMIN123` is Caldera's own published first-run credential, so an unconfigured deployment authenticated with it against any Caldera nobody had rotated. The fourth case runs the other way so this cannot pass on a build with no client at all |
+| 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 |
## Summary
-- GATED: 250
+- GATED: 251
## Summary
-- GATED: 250
+- GATED: 251
## Summary
-- GATED: 250
+- GATED: 251
## Summary
-- GATED: 250
+- GATED: 251
+
+## Summary
+
+- GATED: 251
- 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_route_authz.py b/scripts/check_route_authz.py
index 110d832fe..17ada3b60 100644
--- a/scripts/check_route_authz.py
+++ b/scripts/check_route_authz.py
@@ -90,6 +90,21 @@ AUTHZ_CALLS = frozenset(
"require_permission_db",
"has_permission",
"has_permission_db",
+ # Organisation-role decisions. `_admin_scope` resolves the caller's
+ # role inside an MSSP organisation and raises 403 unless they
+ # administer it, which is an authorization decision by any
+ # definition — it just is not a tenant permission, because an MSSP
+ # portfolio is not a tenant and `ORG_ROLES` is a separate, ordered
+ # ladder.
+ #
+ # Added rather than worked around. Four routes that manage portfolio
+ # membership and cross-tenant grants were counted as unauthorized
+ # while being correctly guarded, and the only way to clear them
+ # without this would have been to bolt a redundant tenant permission
+ # onto a surface that is not tenant-scoped — a worse design adopted
+ # to satisfy a gate, which is how gates start being gamed.
+ "_admin_scope",
+ "_owner_scope",
}
)
@@ -141,7 +156,60 @@ AUTHZ_CALLS = frozenset(
#: interchangeable with a tenant role. This gate reads `require_permission`
#: only, so it cannot see them; `test_mssp_route_permissions.py` asserts they
#: still resolve that scope.
-MAX_UNAUTHORIZED = 26
+MAX_UNAUTHORIZED = 21
+
+#: Modules whose state-changing routes are authorized *by identity*, with the
+#: reason. A route where the caller acts on their own resource is not an
+#: unauthorized route — asking for a permission there would be theatre, since
+#: the only principal who could hold it is the one already identified.
+#:
+#: Declared per module rather than counted, because "20 remaining" tells a
+#: reviewer nothing and this tells them exactly what is excused and why. The
+#: numeric ceiling stays as a backstop: a new identity-only route in an
+#: already-listed module would not be caught by the list alone.
+#:
+#: Checked in both directions — a module that stops having identity-only
+#: routes must lose its entry, or the list becomes a place excuses go to
+#: outlive the thing they excused.
+IDENTITY_IS_AUTHORIZATION: dict[str, str] = {
+ "scim.py": (
+ "SCIM authenticates with its own bearer token and resolves a "
+ "`SCIMPrincipal`, not a tenant role. There is no permission to check: "
+ "the token *is* the grant, and it is scoped to one organisation at "
+ "mint time."
+ ),
+ "passkeys.py": (
+ "A registration or authentication ceremony for the caller's own "
+ "credential. A permission would have to be held by the person "
+ "enrolling their own key, which is everyone."
+ ),
+ "push.py": (
+ "Web-push subscriptions for the caller's own browser. The row is "
+ "keyed on the authenticated user; there is no other principal's "
+ "subscription to reach."
+ ),
+ "saved_views.py": (
+ "A user's own saved filters on list pages. Scoped to the "
+ "authenticated user id in the query, so identity is both the "
+ "authentication and the scope."
+ ),
+ "community.py": (
+ "`POST /plugins/{id}/rate`. Every authenticated principal is a "
+ "legitimate rater, the vocabulary has no permission for expressing "
+ "an opinion, and requiring an administrative one would mean only "
+ "administrators may rate. The real integrity question is "
+ "one-vote-per-user, which the in-memory counter cannot express — "
+ "storage and product, not authorization. Pinned by "
+ "`test_rating_is_deliberately_not_gated`."
+ ),
+ "auth.py": ("Sign-in itself. A permission check before authentication has no principal to check against."),
+ "oncall.py": (
+ "`PUT /oncall/me` sets the caller's own availability. Setting somebody else's is a different route and does take a permission."
+ ),
+ "realtime.py": (
+ "Mints a short-lived WebSocket ticket for the caller's own socket, carrying the claims they already hold. It confers nothing new."
+ ),
+}
def _authorizing_names(tree: ast.Module) -> set[str]:
@@ -201,6 +269,15 @@ def _calls_authz(node: ast.AST) -> list[str]:
name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)
if name in AUTHZ_CALLS:
found.append(name)
+ # `Depends(_admin_scope)` passes the dependency by name, not by
+ # calling it. A matcher that only looked for a Call missed every
+ # organisation-role decision in `mssp.py`, because those are
+ # dependencies rather than factories — `require_permission("x")`
+ # returns a dependency, `_admin_scope` *is* one.
+ if name == "Depends":
+ for argument in sub.args:
+ if isinstance(argument, ast.Name) and argument.id in AUTHZ_CALLS:
+ found.append(argument.id)
return found
@@ -418,6 +495,29 @@ def main(argv: list[str] | None = None) -> int:
print(f" {line}")
return 1
+ # Every identity-only route must sit in a module with a declared
+ # reason. A bare count says how much is excused; this says what, which
+ # is the question a reviewer actually has.
+ undeclared = sorted({r["module"] for r in ungated if Path(r["module"]).name not in IDENTITY_IS_AUTHORIZATION})
+ if undeclared:
+ print(f"\nFAIL: {len(undeclared)} module(s) have identity-only state-changing routes")
+ print("and no declared reason. Either authorize them, or add the module to")
+ print(f"IDENTITY_IS_AUTHORIZATION in {Path(__file__).name} with why identity suffices.")
+ for module in undeclared:
+ print(f" {module}")
+ return 1
+
+ # And the other direction: a module that no longer has any is an excuse
+ # outliving the thing it excused.
+ present = {Path(r["module"]).name for r in ungated}
+ stale = sorted(set(IDENTITY_IS_AUTHORIZATION) - present)
+ if stale:
+ print(f"\nFAIL: {len(stale)} declared exemption(s) no longer describe any route.")
+ print("Remove them; the list may only shrink.")
+ for name in stale:
+ print(f" {name}")
+ return 1
+
# Reverse: a ceiling that no longer describes the tree is stale, and a
# stale ceiling is how a list of exemptions turns into a list of excuses.
if len(ungated) < args.max_unauthorized:
diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.py
index a5eddba84..9ef069f40 100644
--- a/services/api/app/api/v1/endpoints/knowledge_base.py
+++ b/services/api/app/api/v1/endpoints/knowledge_base.py
@@ -272,7 +272,15 @@ async def delete_document(
@router.post("/query", response_model=QueryResponse, summary="Search knowledge base + optional LLM synthesis")
-async def query_kb(body: QueryRequest, db: DBSession, user: AuthUser) -> QueryResponse:
+async def query_kb(
+ body: QueryRequest,
+ db: DBSession,
+ # A POST that reads: the question is a body rather than a query string,
+ # which is why this was counted as a state-changing route with no
+ # authorization decision. It searches the tenant's knowledge base and
+ # can spend an LLM call, so bare identity was the wrong bar.
+ user: Annotated[AuthUser, Depends(require_permission("knowledge_base:read"))],
+) -> QueryResponse:
wheres = ["to_tsvector('english', content) @@ plainto_tsquery('english', :q)", "tenant_id = :tenant_id"]
params: dict[str, Any] = {"q": body.question, "tenant_id": user.tenant_id, "limit": body.top_k}
if body.doc_kinds:
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index c2a3dca60..b5e7f7bcc 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -70,6 +70,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
# bound to the decision.
"actions:read",
"actions:execute",
+ # POST /knowledge-base/query is a read expressed as a POST (the
+ # question is a body), so it was counted as a state-changing
+ # route with no authorization decision. It searches this
+ # tenant's own knowledge base, so every role that can read an
+ # alert can read it.
+ "knowledge_base:read",
],
"soc_lead": [
"alerts:read",
@@ -94,6 +100,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"lake:read_schema",
"actions:read",
"actions:execute",
+ # POST /knowledge-base/query is a read expressed as a POST (the
+ # question is a body), so it was counted as a state-changing
+ # route with no authorization decision. It searches this
+ # tenant's own knowledge base, so every role that can read an
+ # alert can read it.
+ "knowledge_base:read",
],
"soc_analyst": [
"alerts:read",
@@ -114,6 +126,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
# vendor, so previewing a response is within the same envelope.
"actions:read",
"actions:execute",
+ # POST /knowledge-base/query is a read expressed as a POST (the
+ # question is a body), so it was counted as a state-changing
+ # route with no authorization decision. It searches this
+ # tenant's own knowledge base, so every role that can read an
+ # alert can read it.
+ "knowledge_base:read",
],
"threat_hunter": [
"alerts:read",
@@ -132,6 +150,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
# Read the registry to know what response is available for a finding;
# hunters hand off rather than respond, so no execute.
"actions:read",
+ # POST /knowledge-base/query is a read expressed as a POST (the
+ # question is a body), so it was counted as a state-changing
+ # route with no authorization decision. It searches this
+ # tenant's own knowledge base, so every role that can read an
+ # alert can read it.
+ "knowledge_base:read",
],
"viewer": [
"alerts:read",
@@ -139,6 +163,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"reports:read",
"threat_intel:read",
"actions:read",
+ # POST /knowledge-base/query is a read expressed as a POST (the
+ # question is a body), so it was counted as a state-changing
+ # route with no authorization decision. It searches this
+ # tenant's own knowledge base, so every role that can read an
+ # alert can read it.
+ "knowledge_base:read",
],
"api_service": [
"alerts:read",
diff --git a/services/api/tests/test_platform_route_permissions.py b/services/api/tests/test_platform_route_permissions.py
index 5a4ac08b5..2b3eb2c19 100644
--- a/services/api/tests/test_platform_route_permissions.py
+++ b/services/api/tests/test_platform_route_permissions.py
@@ -287,23 +287,37 @@ class TestWiring:
]
assert not unguarded, f"{module.__name__} has state-changing routes with no permission: {unguarded}"
- def test_kb_query_is_deliberately_not_gated(self) -> None:
- """The one route in this change left alone, pinned so it stays a decision.
+ def test_kb_query_governs_reading_the_library(self) -> None:
+ """The entitlement this route's previous pin asked somebody to name.
- The vocabulary has no knowledge-base permission: every candidate is
- either held by every role including machine keys (`cases:read`,
+ That pin refused to pick one and said why: every existing candidate
+ was either held by every role including machine keys (`cases:read`,
`reports:read`) or restricted to tenant administrators
(`settings:read`), which would take the runbooks away from the
- analysts who need them mid-incident. Picking one on the strength of
- its role list rather than what the route does would be
- reverse-engineering a permission from the answer.
-
- If somebody gates it, this fails and they write down which entitlement
- governs reading the library — and whether LLM synthesis needs a
- stronger one than retrieval. The rest of `knowledge_base.py` is gated,
- so a *new* ungated route there still fails the check below.
+ analysts who need them mid-incident. Choosing on the strength of a
+ role list rather than on what the route does would have been
+ reverse-engineering a permission from the answer — so it asked for a
+ new one to be written down instead.
+
+ `knowledge_base:read` is that permission. It is held by every role
+ that can read an alert, including `viewer`, because reading a runbook
+ during an incident is not a privileged act — and it is *not* held by
+ `api_service`, so a machine key scoped to alert ingestion cannot
+ exfiltrate the library.
+
+ The open half of the original question stands: retrieval and LLM
+ synthesis share one entitlement here. Splitting them needs a view on
+ what spending a model call on tenant content costs, which is parity
+ plan work, not an authorization decision.
"""
- assert _permissions_on(_route_for(knowledge_base, "query_kb")) == []
+ assert _permissions_on(_route_for(knowledge_base, "query_kb")) == ["knowledge_base:read"]
+
+ def test_the_library_is_not_readable_by_a_machine_key_role(self) -> None:
+ """The other direction, so the grant is not simply universal."""
+ from app.core.security import ROLE_PERMISSIONS
+
+ assert "knowledge_base:read" not in ROLE_PERMISSIONS["api_service"]
+ assert "knowledge_base:read" in ROLE_PERMISSIONS["viewer"]
def test_the_rest_of_the_knowledge_base_is_gated(self) -> None:
unguarded = {
@@ -311,4 +325,4 @@ class TestWiring:
for r in knowledge_base.router.routes
if r.methods & {"POST", "PUT", "PATCH", "DELETE"} and not _permissions_on(r)
}
- assert unguarded == {"query_kb"}, f"unexpected ungated knowledge-base routes: {unguarded - {'query_kb'}}"
+ assert unguarded == set(), f"unexpected ungated knowledge-base routes: {unguarded}"