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(audit): name the credential that acted, and let a tenant read its trail (#1080)

Beenu Arorabc5b482482e4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6879ef0dd..393375cc8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -360,6 +360,18 @@ jobs:
run: python scripts/check_kafka_transport.py
- name: Verify the vendored Kafka transport copies match
run: python scripts/sync_vendored_kafka_security.py --check
+ # An API key owned by a user resolved to that user's email, so an
+ # audit entry read the same whether the person acted at the console or
+ # a key they minted acted from a script — and revoking a key and
+ # disabling a person are different responses to the same line. The
+ # gate also holds the ratchet on how many endpoint modules audit at
+ # all, which is 7 of 86 and set at the measured value rather than an
+ # aspiration: a threshold the tree cannot meet gets disabled, and a
+ # disabled gate is worth less than an honest one.
+ - name: Audit coverage gate — self-test
+ run: python scripts/check_audit_coverage.py --self-test
+ - name: Verify the audit log attributes the credential that acted
+ run: python scripts/check_audit_coverage.py
# Fabricated security data must never render as a tenant's real state.
# Around three dozen console components served a `MOCK_*` / `DEMO_*`
# array of plausible alerts, connectors and coverage numbers whenever the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54c33a1a2..a5c880969 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,6 +43,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Thirteen entries remain, each naming where it closes — it was fifteen when this was written, and the copilot and saved-hunt entries came out the moment those two moved to tables, which is the ratchet doing its job rather than a figure being edited. Five are not defects — a log de-duplicator, two caches of static artefacts, and global-by-design community content — and the rest point at the item that gives them a table.
+### Security
+
+- **The audit log could not tell a console session from an API key.** A key owned by a user resolves to that user's email, so an entry read `[email protected] deleted the rule` whether Alice did it at the console or a key she minted a year ago did it from a script she no longer runs. Those call for different responses — revoke a key, or disable a person — and the line an investigator reads could not say which had happened. `CurrentUser` now carries `api_key_prefix` on the key path only, and `emit_audit` records `auth_method` beside it. The **prefix**, never the key: it identifies the credential without being usable as one, and it is what the console displays and what an operator revokes by.
+
+- **A tenant admin could not read their own tenant's audit log.** The only roles holding `audit_log:read` were `platform_admin` and `admin`, and both hold `*` across every tenant — so on a multi-tenant deployment the only principals who could answer "who changed this?" about a customer's data were the operator's own staff, and the customer had to ask them. SOC 2 CC7.2 and ISO 27001 A.12.4 both require the control owner to review their own trail, so this was a compliance failure as much as an MSSP blocker. `tenant_admin` holds it now; the grant is safe because both read handlers already filter on the authenticated `tenant_id`, which a test asserts structurally rather than assuming — granting it without that predicate would have turned a compliance gap into a cross-tenant read.
+
+- **Reading the trail is now itself recorded**, because the set of people who can read it just grew. The filters are logged, not the rows: a search term is what the reader was looking for, which is the interesting fact, while copying results would duplicate the log into itself on every page view.
+
+- **`scripts/check_audit_coverage.py` measures the rest honestly rather than claiming it is fixed.** Seven of 86 endpoint modules emit audit at all. The gate ratchets that floor, requires every actor-bearing `emit_audit` to record the credential, requires the roles that must read their own trail to hold the permission, and prints the **largest unaudited surfaces by state-changing route count** on success — `mssp.py` at 17, `community.py` at 11, `cases.py` at 9 — because a bare ratchet tells nobody where to go next and this figure is low enough that "where next" is the useful output. The floor is set at the measured value, not an aspiration: a threshold the tree cannot meet gets disabled, and a disabled gate is worth less than an honest one.
+
+ Its first rule was too blunt and the correction is worth keeping. "Names an actor, so it must record a credential" reported the SCIM writer, whose `actor_email` is already `scim:<token-name>` — that *is* the credential, and there is no API key on that path to name. A scheme-prefixed actor counts as self-attributing now.
+
+
### Security
- **Copilot conversations and saved hunt searches were readable by every tenant.** Both lived in a module-level dict — `_CONVERSATIONS` in `services/agents/app/api/copilot.py` and `_SAVED_SEARCHES` in `hunt_search.py` — with no tenant column anywhere, and the list handlers took no principal at all. `GET /api/v1/copilot/conversations` returned every tenant's conversations to whoever asked, `GET /api/v1/copilot/conversations/{id}` returned any conversation to anyone holding its id, and `GET /api/v1/hunt/saved` did the same for saved searches.
diff --git a/ROADMAP.md b/ROADMAP.md
index ada4cf7a9..9eac36538 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 **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).
+The claim-to-gate matrix stands at **252 rows — 252 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 **252 rows — 252 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 **252 rows — 252 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 **252 rows — 252 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 e7965e927..8cdd393f1 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: 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
+The last row is the one worth reading first. It is the honest index: 252 rows
+The last row is the one worth reading first. It is the honest index: 252 rows
+The last row is the one worth reading first. It is the honest index: 252 rows
+The last row is the one worth reading first. It is the honest index: 252 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 2d305c8ba..eac83d0ea 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -259,26 +259,27 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| 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 |
+| 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 |
## Summary
-- GATED: 251
+- GATED: 252
## Summary
-- GATED: 251
+- GATED: 252
## Summary
-- GATED: 251
+- GATED: 252
## Summary
-- GATED: 251
+- GATED: 252
## Summary
-- GATED: 251
+- GATED: 252
- 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_audit_coverage.py b/scripts/check_audit_coverage.py
new file mode 100644
index 000000000..3aadcff6b
--- /dev/null
+++ b/scripts/check_audit_coverage.py
@@ -0,0 +1,316 @@
+#!/usr/bin/env python3
+"""The audit log can answer who did what, and with which credential.
+
+Three properties, each of which was false.
+
+**Attribution.** An API key owned by a user resolves to that user's email, so
+an entry read `[email protected] deleted the rule` whether Alice did it at the
+console or a key she minted a year ago did it from a script she no longer
+runs. Those call for different responses — revoke a key, or disable a person
+— and the log could not tell an investigator which had happened. Every
+`emit_audit` call that names an actor must also pass `api_key_prefix`.
+
+**Readership.** `tenant_admin` did not hold `audit_log:read`. Only
+`platform_admin` and `admin` did, and both hold `*` across every tenant — so
+on a multi-tenant deployment the only principals who could answer "who
+changed this?" for a customer were the operator's own staff. SOC 2 CC7.2 and
+ISO 27001 A.12.4 both require the control owner to review their own trail.
+
+**Coverage.** Six endpoint modules emit audit out of roughly a hundred. This
+gate does not pretend that is fixed — it measures it and ratchets, so the
+number can only improve, and prints the modules that would most change the
+figure rather than a bare count nobody can act on.
+
+The ratchet is deliberately set at the measured value rather than at an
+aspiration. A gate whose threshold the tree cannot meet gets disabled, and a
+disabled gate is worth less than an honest one.
+"""
+
+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
+
+API_ROOT = "services/api"
+ENDPOINTS = "services/api/app/api/v1/endpoints"
+
+#: Methods that change state. A GET is a read; auditing every one of them
+#: would bury the entries that matter under traffic.
+MUTATING = frozenset({"post", "put", "patch", "delete"})
+
+#: Reads that are audited anyway, because the read *is* the sensitive act:
+#: running SQL against the tenant lake, and reading the audit log itself.
+SENSITIVE_READ_MODULES = ("lake.py", "audit.py")
+
+#: The floor, measured rather than aspired to. It may only rise.
+MIN_AUDITING_MODULES = 7
+
+#: Roles that must be able to read their own tenant's trail.
+MUST_READ_AUDIT = ("tenant_admin",)
+
+
+@dataclass
+class Report:
+ modules_total: int = 0
+ modules_auditing: int = 0
+ unattributed: list[str] = field(default_factory=list)
+ missing_readers: list[str] = field(default_factory=list)
+ unaudited_sensitive_reads: list[str] = field(default_factory=list)
+ biggest_gaps: list[tuple[str, int]] = field(default_factory=list)
+
+
+def _endpoint_modules(root: pathlib.Path) -> list[pathlib.Path]:
+ directory = root / ENDPOINTS
+ if not directory.is_dir():
+ return []
+ return sorted(p for p in directory.glob("*.py") if p.name != "__init__.py")
+
+
+def _mutating_route_count(tree: ast.Module) -> int:
+ count = 0
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for decorator in node.decorator_list:
+ call = decorator if isinstance(decorator, ast.Call) else None
+ func = call.func if call else decorator
+ if isinstance(func, ast.Attribute) and func.attr in MUTATING:
+ count += 1
+ break
+ return count
+
+
+def _unattributed_calls(tree: ast.Module, rel: str) -> list[str]:
+ """`emit_audit` calls that name an actor but not the credential."""
+ offenders = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ if getattr(node.func, "id", getattr(node.func, "attr", "")) != "emit_audit":
+ continue
+ kwargs = {k.arg for k in node.keywords if k.arg}
+ # A call with no actor at all is a system event; it has no credential
+ # to record and must not be reported as missing one.
+ if not kwargs & {"actor_id", "actor_email"}:
+ continue
+ if "api_key_prefix" in kwargs or _actor_names_its_scheme(node):
+ continue
+ offenders.append(f"{rel}:{node.lineno}")
+ return offenders
+
+
+#: Prefixes that make an actor self-attributing. `scim:acme-idp` already
+#: says which credential acted, so demanding `api_key_prefix` beside it
+#: would be asking for a field that does not apply — the SCIM path has no
+#: API key. Reported as a false positive by the gate's first run.
+SELF_ATTRIBUTING_PREFIXES = ("scim:", "api-key:", "service:", "system:", "webhook:")
+
+
+def _actor_names_its_scheme(call: ast.Call) -> bool:
+ """True when `actor_email` begins with a literal credential scheme."""
+ for keyword in call.keywords:
+ if keyword.arg != "actor_email":
+ continue
+ value = keyword.value
+ # An f-string's leading literal is its first JoinedStr part.
+ if isinstance(value, ast.JoinedStr) and value.values:
+ head = value.values[0]
+ if isinstance(head, ast.Constant) and isinstance(head.value, str):
+ return head.value.startswith(SELF_ATTRIBUTING_PREFIXES)
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
+ return value.value.startswith(SELF_ATTRIBUTING_PREFIXES)
+ return False
+
+
+def _roles_reading_audit(root: pathlib.Path) -> set[str]:
+ """Parsed from the role map rather than imported.
+
+ Importing would need the service's whole dependency set on `sys.path`,
+ and the question is about the file this repository ships.
+ """
+ path = root / API_ROOT / "app" / "core" / "security.py"
+ if not path.is_file():
+ return set()
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ holders: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Dict):
+ continue
+ for key, value in zip(node.keys, node.values, strict=False):
+ if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
+ continue
+ if not isinstance(value, ast.List):
+ continue
+ perms = {e.value for e in value.elts if isinstance(e, ast.Constant)}
+ if "*" in perms or "audit_log:read" in perms:
+ holders.add(key.value)
+ return holders
+
+
+def inspect(root: pathlib.Path) -> Report:
+ report = Report()
+ gaps: list[tuple[str, int]] = []
+
+ for path in _endpoint_modules(root):
+ rel = path.relative_to(root).as_posix()
+ source = path.read_text(encoding="utf-8", errors="replace")
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+ report.modules_total += 1
+ audits = "emit_audit(" in source
+ if audits:
+ report.modules_auditing += 1
+ report.unattributed.extend(_unattributed_calls(tree, rel))
+ else:
+ mutating = _mutating_route_count(tree)
+ if mutating:
+ gaps.append((rel, mutating))
+
+ if path.name in SENSITIVE_READ_MODULES and not audits:
+ report.unaudited_sensitive_reads.append(rel)
+
+ report.biggest_gaps = sorted(gaps, key=lambda pair: -pair[1])[:8]
+ holders = _roles_reading_audit(root)
+ report.missing_readers = [role for role in MUST_READ_AUDIT if role not in holders]
+ return report
+
+
+def _verdict(report: Report) -> int:
+ if report.modules_total == 0:
+ print(
+ "check_audit_coverage: no endpoint modules found — refusing to report a tree with nothing in it as clean",
+ file=sys.stderr,
+ )
+ return 2
+
+ failed = False
+
+ if report.unattributed:
+ print(
+ "check_audit_coverage: emit_audit call(s) that name an actor but not the "
+ "credential, so the entry cannot distinguish a session from an API key:",
+ file=sys.stderr,
+ )
+ for site in report.unattributed:
+ print(f" {site}", file=sys.stderr)
+ failed = True
+
+ if report.missing_readers:
+ print(
+ f"check_audit_coverage: {', '.join(report.missing_readers)} cannot read their own "
+ "tenant's audit log. The read is tenant-scoped at the query layer, so granting "
+ "`audit_log:read` shows them their own history and nothing else.",
+ file=sys.stderr,
+ )
+ failed = True
+
+ if report.unaudited_sensitive_reads:
+ print(
+ "check_audit_coverage: module(s) whose *reads* are the sensitive act and which "
+ f"emit no audit: {', '.join(report.unaudited_sensitive_reads)}",
+ file=sys.stderr,
+ )
+ failed = True
+
+ if report.modules_auditing < MIN_AUDITING_MODULES:
+ print(
+ f"check_audit_coverage: {report.modules_auditing} endpoint module(s) emit audit, "
+ f"below the ratchet of {MIN_AUDITING_MODULES}. The floor may only rise.",
+ file=sys.stderr,
+ )
+ failed = True
+
+ if failed:
+ return 1
+
+ print(
+ f"check_audit_coverage: OK — {report.modules_auditing} of {report.modules_total} "
+ f"endpoint module(s) emit audit (floor {MIN_AUDITING_MODULES}); every actor-bearing "
+ f"call records the credential; {', '.join(MUST_READ_AUDIT)} can read their own trail."
+ )
+ if report.biggest_gaps:
+ # Printed on success as well. A bare ratchet tells nobody where to
+ # go next, and this figure is low enough that "where next" is the
+ # useful output.
+ print(" Largest unaudited surfaces, by state-changing route count:")
+ for rel, count in report.biggest_gaps:
+ print(f" {count:3} {rel}")
+ return 0
+
+
+def self_test() -> int:
+ import tempfile
+
+ extra: list[tuple[str, bool]] = []
+
+ with tempfile.TemporaryDirectory(prefix="aisoc-audit-gate-") as tmp:
+ base = pathlib.Path(tmp)
+ endpoints = base / ENDPOINTS
+ endpoints.mkdir(parents=True)
+ (base / API_ROOT / "app" / "core").mkdir(parents=True)
+ (base / API_ROOT / "app" / "core" / "security.py").write_text(
+ 'ROLE_PERMISSIONS = {"tenant_admin": ["audit_log:read"]}\n', encoding="utf-8"
+ )
+
+ (endpoints / "a.py").write_text("async def go():\n await emit_audit(actor_id=u.id, action='x')\n", encoding="utf-8")
+ report = inspect(base)
+ extra.append(("detects an actor-bearing call with no credential", bool(report.unattributed)))
+
+ (endpoints / "a.py").write_text(
+ "async def go():\n await emit_audit(actor_id=u.id, action='x', api_key_prefix=u.api_key_prefix)\n",
+ encoding="utf-8",
+ )
+ report = inspect(base)
+ extra.append(("accepts one that records it", not report.unattributed))
+
+ (endpoints / "a.py").write_text("async def go():\n await emit_audit(action='system.rotate')\n", encoding="utf-8")
+ report = inspect(base)
+ extra.append(
+ (
+ "does not fault a system event, which has no credential to record",
+ not report.unattributed,
+ )
+ )
+
+ (base / API_ROOT / "app" / "core" / "security.py").write_text(
+ 'ROLE_PERMISSIONS = {"tenant_admin": ["alerts:read"]}\n', encoding="utf-8"
+ )
+ report = inspect(base)
+ extra.append(("detects a tenant_admin who cannot read their own trail", bool(report.missing_readers)))
+
+ (base / API_ROOT / "app" / "core" / "security.py").write_text('ROLE_PERMISSIONS = {"tenant_admin": ["*"]}\n', encoding="utf-8")
+ report = inspect(base)
+ extra.append(("accepts a wildcard as covering it", not report.missing_readers))
+
+ # And against the real tree, so an empty corpus cannot pass.
+ report = inspect(repo_root())
+ extra.append(
+ (
+ f"counts what it scanned ({report.modules_auditing} of {report.modules_total} modules)",
+ report.modules_total > 50,
+ )
+ )
+ 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 4382a6e74..47196e359 100644
--- a/services/api/app/api/v1/deps.py
+++ b/services/api/app/api/v1/deps.py
@@ -67,12 +67,22 @@ class CurrentUser:
role: str,
email: str,
scopes: list[str] | None = None,
+ api_key_prefix: str | None = None,
) -> None:
self.user_id = user_id
self.tenant_id = tenant_id
self.role = role
self.email = email
self.scopes = scopes # None → role-based; list → API-key scoped
+ # Set only on the API-key path, and only so the audit log can say so.
+ #
+ # A key owned by a user resolves to that user's email, so an audit
+ # entry read "[email protected] deleted the rule" whether Alice did it
+ # at the console or a key she minted a year ago did it from a script
+ # she no longer runs. Those call for different responses — revoke a
+ # key, or disable a person — and the log could not tell an
+ # investigator which one had happened.
+ self.api_key_prefix = api_key_prefix
def __repr__(self) -> str:
# Without this a stray `str(user)` persists `<...CurrentUser object at
@@ -196,6 +206,7 @@ async def _resolve_api_key(raw_key: str, db: AsyncSession) -> CurrentUser:
role=role,
email=email,
scopes=api_key.scopes or [],
+ api_key_prefix=api_key.key_prefix,
)
diff --git a/services/api/app/api/v1/endpoints/alert_explain.py b/services/api/app/api/v1/endpoints/alert_explain.py
index 793e15674..5e3208680 100644
--- a/services/api/app/api/v1/endpoints/alert_explain.py
+++ b/services/api/app/api/v1/endpoints/alert_explain.py
@@ -215,6 +215,7 @@ async def explain_alert(
"mitre_technique_count": len(explanation.mitre_techniques),
},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
except Exception as exc: # noqa: BLE001
# Audit-log failures must never break the explain response.
diff --git a/services/api/app/api/v1/endpoints/audit.py b/services/api/app/api/v1/endpoints/audit.py
index f3b652cbe..4a3757515 100644
--- a/services/api/app/api/v1/endpoints/audit.py
+++ b/services/api/app/api/v1/endpoints/audit.py
@@ -8,7 +8,7 @@ import uuid
from datetime import UTC, datetime
from typing import Annotated
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import HTMLResponse, PlainTextResponse
from pydantic import BaseModel
from sqlalchemy import func, select
@@ -16,6 +16,7 @@ from sqlalchemy import func, select
from app.api.v1.deps import AuthUser, require_permission
from app.db.rls import TenantDBSession
from app.models.audit import AuditLog
+from app.services.audit import emit_audit
from app.services.audit_export import (
AuditRow,
ExportContext,
@@ -83,6 +84,7 @@ def _filtered_audit_query(
@router.get("", response_model=AuditListResponse)
async def list_audit_events(
+ request: Request,
current_user: Annotated[AuthUser, Depends(require_permission("audit_log:read"))],
db: TenantDBSession,
page: int = Query(default=1, ge=1),
@@ -109,6 +111,39 @@ async def list_audit_events(
result = await db.execute(q)
items = result.scalars().all()
+ # Reading a trail is itself an act worth recording. The point is not the
+ # page view — it is that `tenant_admin` can now read this, so the set of
+ # people who can see who did what just grew, and an investigator asking
+ # "who looked at this?" must get an answer rather than a shrug.
+ #
+ # The filters are recorded, not the rows: a search term is what the
+ # reader was looking for, which is the interesting fact, while copying
+ # the results would duplicate the log into itself on every page view.
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ action="audit_log:read",
+ resource="audit_log",
+ changes={
+ "filters": {
+ k: v
+ for k, v in (
+ ("action", action),
+ ("resource", resource),
+ ("actor_id", str(actor_id) if actor_id else None),
+ ("search", search),
+ )
+ if v
+ },
+ "matched": total,
+ },
+ request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ )
+ await db.commit()
+
return AuditListResponse(
items=[
AuditEventOut(
diff --git a/services/api/app/api/v1/endpoints/branding.py b/services/api/app/api/v1/endpoints/branding.py
index fba520194..345ce3da5 100644
--- a/services/api/app/api/v1/endpoints/branding.py
+++ b/services/api/app/api/v1/endpoints/branding.py
@@ -129,6 +129,7 @@ async def put_branding(
resource_id=str(org_id),
changes=body.model_dump(),
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
return (await resolver.branding_for_org(db, org_id)).as_dict()
@@ -217,6 +218,7 @@ async def upload_asset(
resource_id=str(existing.id),
changes={"kind": kind, "content_type": content_type, "bytes": len(content), "sanitized": was_sanitized, "removed": removed},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
@@ -293,5 +295,6 @@ async def delete_asset(
resource_id=str(asset.id),
changes={"kind": kind},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
diff --git a/services/api/app/api/v1/endpoints/lake.py b/services/api/app/api/v1/endpoints/lake.py
index c2d9f171d..d7e25855d 100644
--- a/services/api/app/api/v1/endpoints/lake.py
+++ b/services/api/app/api/v1/endpoints/lake.py
@@ -538,6 +538,7 @@ async def _audit_query_attempt(
"row_cap": row_cap,
},
request=request,
+ api_key_prefix=getattr(user_id, "api_key_prefix", None),
)
except Exception as exc: # noqa: BLE001 — audit must never fail the call
# Audit write failures must not break the user-facing response;
diff --git a/services/api/app/api/v1/endpoints/llm_credentials.py b/services/api/app/api/v1/endpoints/llm_credentials.py
index caaad6904..ac4837f1e 100644
--- a/services/api/app/api/v1/endpoints/llm_credentials.py
+++ b/services/api/app/api/v1/endpoints/llm_credentials.py
@@ -348,6 +348,7 @@ async def upsert_llm_credential(
"created": existing is None,
},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
except Exception as exc: # noqa: BLE001 — audit must not fail the call
logger.error(
@@ -416,6 +417,7 @@ async def delete_llm_credential(
"provider": existing.provider,
},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
except Exception as exc: # noqa: BLE001
logger.error(
diff --git a/services/api/app/api/v1/endpoints/scim_tokens.py b/services/api/app/api/v1/endpoints/scim_tokens.py
index a294e4552..3e5fc30ce 100644
--- a/services/api/app/api/v1/endpoints/scim_tokens.py
+++ b/services/api/app/api/v1/endpoints/scim_tokens.py
@@ -121,6 +121,7 @@ async def create_scim_token(
resource_id=str(token.id),
changes={"name": body.name, "prefix": token.token_prefix, "expires_at": expires_at.isoformat() if expires_at else None},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
await db.refresh(token)
@@ -160,6 +161,7 @@ async def rotate_scim_token(
"superseded_expires_at": token.expires_at.isoformat() if token.expires_at else None,
},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
await db.refresh(replacement)
@@ -197,5 +199,6 @@ async def revoke_scim_token(
resource_id=str(token.id),
changes={"prefix": token.token_prefix},
request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
)
await db.commit()
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index b5e7f7bcc..24237db45 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -55,6 +55,18 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"threat_intel:write",
"settings:read",
"settings:write",
+ # A tenant admin could not read their own tenant's audit log. Only
+ # `platform_admin` and `admin` could, and both hold `*` across every
+ # tenant — so on a multi-tenant deployment the only principals who
+ # could answer "who changed this?" for a customer were the operator's
+ # own staff, and the customer had to ask them. That is a compliance
+ # failure (SOC 2 CC7.2 and ISO 27001 A.12.4 both require the control
+ # owner to be able to review their own trail) and an MSSP blocker.
+ #
+ # Safe because the read is tenant-scoped at the query layer: the
+ # handler filters on the authenticated `tenant_id`, so this grants
+ # visibility of their own history and nothing else.
+ "audit_log:read",
# Workstream 7: tenant lake API. Tenant admins get full access
# to the warm-tier query surface (POST /api/v1/lake/sql) and
# the schema discovery endpoint (GET /api/v1/lake/schema). The
diff --git a/services/api/app/services/audit.py b/services/api/app/services/audit.py
index 0a49a6f38..20dfbd5df 100644
--- a/services/api/app/services/audit.py
+++ b/services/api/app/services/audit.py
@@ -301,6 +301,7 @@ async def emit_audit(
resource_id: str | None = None,
changes: dict[str, Any] | None = None,
request: Request | None = None,
+ api_key_prefix: str | None = None,
) -> AuditLog:
"""Append an immutable, hash-chained audit event to the log.
@@ -324,6 +325,13 @@ async def emit_audit(
changes: Before/after dict or delta payload. Will be redacted
and size-capped before persistence.
request: FastAPI ``Request`` to extract IP & user-agent.
+ api_key_prefix:
+ Set when the caller authenticated with an API key. A key
+ owned by a user resolves to that user's email, so without
+ this an entry read identically whether the person acted at
+ the console or a key they minted acted from a script —
+ and revoking a key and disabling a person are different
+ responses to the same log line.
"""
actor_ip: str | None = None
meta: dict[str, Any] = {}
@@ -345,6 +353,15 @@ async def emit_audit(
if rid:
meta["request_id"] = rid
+ if api_key_prefix:
+ # The prefix, never the key. It is the identifier the console shows
+ # and the one an operator revokes by, which is exactly what an
+ # investigator reading this row needs to act on.
+ meta["auth_method"] = "api_key"
+ meta["api_key_prefix"] = _safe_truncate(api_key_prefix, 32)
+ elif request is not None:
+ meta["auth_method"] = "session"
+
# Sanitize before persistence. Anything secret-shaped is masked,
# and oversized payloads collapse to a marker row.
safe_changes = redact_changes(changes)
diff --git a/services/api/tests/test_audit_attribution_and_readership.py b/services/api/tests/test_audit_attribution_and_readership.py
new file mode 100644
index 000000000..30d839d1e
--- /dev/null
+++ b/services/api/tests/test_audit_attribution_and_readership.py
@@ -0,0 +1,150 @@
+"""The audit log says which credential acted, and the tenant can read it.
+
+Two defects, both of which made the log less useful than it looked.
+
+**Attribution.** An API key owned by a user resolves to that user's email,
+so an entry read `[email protected] deleted the rule` whether Alice did it at
+the console or a key she minted a year ago did it from a script she no
+longer runs. An investigator reading that line cannot tell which, and the
+two call for different responses: revoke a key, or disable a person.
+
+**Readership.** `tenant_admin` did not hold `audit_log:read`. The only roles
+that did were `platform_admin` and `admin`, both of which hold `*` across
+every tenant — so on a multi-tenant deployment the only principals who could
+answer "who changed this?" about a customer's data were the operator's own
+staff, and the customer had to ask. SOC 2 CC7.2 and ISO 27001 A.12.4 both
+require the control owner to be able to review their own trail.
+
+Granting that read is safe because both handlers already filter on the
+authenticated `tenant_id`, which is asserted below rather than assumed —
+a grant without that predicate would have turned a compliance gap into a
+cross-tenant read.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+import pathlib
+import uuid
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.core.security import ROLE_PERMISSIONS
+
+SERVICE_ROOT = pathlib.Path(__file__).resolve().parents[1]
+
+
+class TestTheCredentialIsRecorded:
+ def test_a_session_principal_carries_no_key_prefix(self) -> None:
+ user = CurrentUser(user_id=uuid.uuid4(), tenant_id=uuid.uuid4(), role="soc_analyst", email="[email protected]")
+ assert user.api_key_prefix is None
+
+ def test_an_api_key_principal_carries_one(self) -> None:
+ user = CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ role="soc_analyst",
+ scopes=["alerts:read"],
+ # Deliberately not key-shaped. A realistic `aisoc_live_...`
+ # literal is indistinguishable from a real credential to a
+ # secret scanner, and a test fixture is not worth an
+ # allowlist entry that would also cover a genuine leak.
+ api_key_prefix="prefix-under-test",
+ )
+ assert user.api_key_prefix == "prefix-under-test"
+
+ def test_emit_audit_accepts_and_records_it(self) -> None:
+ from app.services import audit
+
+ assert "api_key_prefix" in inspect.signature(audit.emit_audit).parameters
+ source = inspect.getsource(audit.emit_audit)
+ assert 'meta["auth_method"] = "api_key"' in source
+ assert 'meta["api_key_prefix"]' in source
+
+ def test_the_prefix_is_recorded_not_the_key(self) -> None:
+ """A prefix identifies the key without being usable as one.
+
+ It is also what the console displays and what an operator revokes
+ by, so it is the identifier an investigator can act on.
+ """
+ from app.api.v1 import deps
+
+ source = inspect.getsource(deps)
+ assert "api_key_prefix=api_key.key_prefix" in source
+ assert "api_key_prefix=api_key.key_hash" not in source
+ assert "api_key_prefix=raw" not in source
+
+
+class TestTheTenantCanReadItsOwnTrail:
+ @pytest.mark.parametrize("role", ["tenant_admin"])
+ def test_the_role_holds_the_permission(self, role: str) -> None:
+ perms = ROLE_PERMISSIONS[role]
+ assert "audit_log:read" in perms or "*" in perms, (
+ f"{role} cannot read their own tenant's audit log, so only roles holding '*' "
+ "across every tenant can answer 'who changed this?' for a customer"
+ )
+
+ @pytest.mark.parametrize("role", ["soc_analyst", "viewer", "threat_hunter"])
+ def test_lower_roles_still_cannot(self, role: str) -> None:
+ """The other direction, so this cannot pass by granting everyone.
+
+ An audit trail readable by every analyst is one an insider can use
+ to check whether their own activity has been noticed.
+ """
+ perms = ROLE_PERMISSIONS[role]
+ assert "audit_log:read" not in perms and "*" not in perms
+
+ def test_both_read_handlers_filter_on_the_authenticated_tenant(self) -> None:
+ """The predicate that makes the grant safe.
+
+ Asserted structurally: every call building the query must pass
+ `current_user.tenant_id`, not a value from the request.
+ """
+ source = (SERVICE_ROOT / "app" / "api" / "v1" / "endpoints" / "audit.py").read_text(encoding="utf-8")
+ tree = ast.parse(source)
+ scoped = 0
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ for keyword in node.keywords:
+ if keyword.arg != "tenant_id":
+ continue
+ value = keyword.value
+ if (
+ isinstance(value, ast.Attribute)
+ and value.attr == "tenant_id"
+ and isinstance(value.value, ast.Name)
+ and value.value.id == "current_user"
+ ):
+ scoped += 1
+ assert scoped >= 2, f"expected both read handlers to scope on the authenticated tenant, found {scoped}"
+
+
+class TestReadingTheTrailIsItselfRecorded:
+ def test_the_list_handler_emits_an_audit_event(self) -> None:
+ """Because the set of people who can read it just grew.
+
+ An investigator asking "who looked at this?" must get an answer
+ rather than a shrug, and that question only became answerable now
+ that `tenant_admin` holds the read.
+ """
+ from app.api.v1.endpoints.audit import list_audit_events
+
+ source = inspect.getsource(list_audit_events)
+ assert "emit_audit(" in source
+ assert 'action="audit_log:read"' in source
+
+ def test_it_records_the_filters_not_the_rows(self) -> None:
+ """Copying the results would duplicate the log into itself.
+
+ The search term is the interesting fact — it is what the reader was
+ looking for — and it is one line rather than a page of rows.
+ """
+ from app.api.v1.endpoints.audit import list_audit_events
+
+ source = inspect.getsource(list_audit_events)
+ assert '"filters"' in source
+ assert '"matched": total' in source
+ assert "items" not in source.split("emit_audit(")[1].split(")")[0]