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.

Scope the identity timeline to its caller, and require auth on playbooks (#789)

Beenu Arora7b0dabab229f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3050db65..ac463837b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
+- **`/api/v1/identity-timeline` read every tenant's alerts.** Both routes bound
+ an authenticated user and never used it: the SQL against `aisoc_alerts`
+ carried no `tenant_id` predicate, so any authenticated caller could pull any
+ tenant's alerts whose title or evidence matched a substring — and the
+ substring is the search term, so the match is caller-controlled. Both routes
+ are now scoped to the caller's tenant.
+
+- **`/api/v1/playbooks` had no authentication at all.** The module declared no
+ `Depends` of any kind across eight routes and there is no global auth
+ middleware, so every route was reachable unauthenticated — including
+ `POST /playbooks/{id}/run`, which executes a playbook against the estate.
+ Each route now demands `playbooks:read`, `playbooks:write` or
+ `playbooks:execute`; all three permissions already existed in
+ `ROLE_PERMISSIONS` and had no reader. `:execute` stays distinct from
+ `:write` so an analyst can run a governed playbook without editing one.
+
+- The case-timeline linked-alert hydration in `cases.py` now binds a tenant as
+ defence in depth. Reaching it already required a tenant-scoped case, so this
+ was not a live read, but a poisoned `alert_ids` array would otherwise have
+ surfaced another tenant's alert title.
+
- **Any authenticated user could disable detection rules inside any other
tenant.** `_ensure_mssp_parent`, the guard on the MSSP write surface, had
`pass` for a body. Four routes took a caller-supplied child tenant id and
@@ -80,6 +101,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed
+- **The identity timeline's phantom second source.** It queried a table named
+ `aisoc_events` that no migration creates, nothing writes to, and that appears
+ nowhere else in the repository — with its failure swallowed at `DEBUG`. It
+ read as a second source of evidence while returning nothing on every
+ deployment. The remaining source now reports itself on the response
+ (`sources_unavailable`) when it cannot be read, so an empty timeline caused
+ by a broken query is distinguishable from one caused by no matches.
+
- **The Chronicle warehouse scaffold.** It read `hunt.translated_query["udm"]`,
nothing in the repository emits UDM, and it gated on two settings that were
never fields — so it could not be selected and could not run, while
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 7b90777d9..3d9f7e4ed 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `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: 101 rows
+The last row is the one worth reading first. It is the honest index: 103 rows
`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 03f050d24..aca3a8836 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -27,6 +27,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Plugin SDK Python/TS/Go | README L79, L193 | `ci.yml :: sdk-*` | PARTIAL (build/test gated; OpenAPI breaking-change now gated via `openapi-breaking.yml`, so a spec change that would break the generated SDKs is caught; per-language generated-client contract-drift is 11b) | Phase 11b |
| Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate |
| Cross-tenant isolation (Postgres) | (implied by multi-tenant) | `cross-tenant-rbac.yml` (nightly, 3 endpoints) + `ci.yml` | PARTIAL (Postgres only, compiled-SQL not live DB) | Phase 1.3 |
+| Every authenticated route reads only the caller's own tenant | (implied by multi-tenant) | `ci.yml` api job (`test_tenant_scope_and_auth_holes.py` — the identity-timeline alert query binds the caller's tenant and keeps the caller-supplied search term a parameter; the case-timeline linked-alert hydration binds a tenant; and a directory-wide sweep over `app/api/v1/endpoints/*.py` fails if **any** raw `FROM aisoc_alerts` read omits `tenant_id`, so a new endpoint cannot reintroduce the shape) | GATED | the sweep covers raw SQL against the alerts tables; ORM reads rely on the existing per-endpoint isolation tests |
+| Every playbook route requires an authenticated, permitted caller | (implied by RBAC) | `ci.yml` api job (`test_tenant_scope_and_auth_holes.py` — each of the eight route functions takes an authenticated principal, the decorated-route count is asserted against the expected permission map so a new ungated route fails, execute stays distinct from write, and every permission named is one a role actually grants) | GATED | - |
| An MSSP parent holds only tenants that invited it | operations/security.md (MSSP parent/child links) | `ci.yml` api job (`test_mssp_cross_tenant_authz.py` — the four child-scoped write routes refuse a tenant that is not the caller's child and persist nothing; unknown and unowned are indistinguishable so the routes cannot enumerate tenant UUIDs; onboarding refuses without an invite, refuses an invite addressed to another parent, consumes the invite on success, and refuses self-adoption) | GATED | the guard is unit-level against the route functions; the nightly live-DB `cross-tenant-rbac.yml` sweep does not yet cover the MSSP routes |
| Cross-tenant isolation (Qdrant/Neo4j/Redis/ClickHouse/Kafka) | (implied by multi-tenant) | `isolation.yml` (offline: read paths construct a tenant scope) + `isolation-live.yml` (live A-vs-B replay: Neo4j property filter, Redis keyspace namespacing, ClickHouse via production `lake_sql.rewrite_for_tenant`, Kafka per-tenant envelope filter) | GATED | - |
| SAST | README badge (CodeQL) | `codeql.yml` | GATED | - |
@@ -121,7 +123,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 101
+- GATED: 103
- PARTIAL: 9
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index f80357b53..0c5f14775 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -4330,6 +4330,8 @@ paths:
- playbooks
summary: List playbooks
operationId: list_playbooks_api_v1_playbooks_get
+ security:
+ - HTTPBearer: []
parameters:
- name: enabled_only
in: query
@@ -4355,6 +4357,8 @@ paths:
- playbooks
summary: Create playbook
operationId: create_playbook_api_v1_playbooks_post
+ security:
+ - HTTPBearer: []
responses:
'201':
description: Successful Response
@@ -4367,6 +4371,8 @@ paths:
- playbooks
summary: List playbook runs
operationId: list_runs_api_v1_playbooks_runs_get
+ security:
+ - HTTPBearer: []
parameters:
- name: limit
in: query
@@ -4393,6 +4399,8 @@ paths:
- playbooks
summary: Get a playbook run
operationId: get_run_api_v1_playbooks_runs__run_id__get
+ security:
+ - HTTPBearer: []
parameters:
- name: run_id
in: path
@@ -4418,6 +4426,8 @@ paths:
- playbooks
summary: Get a playbook
operationId: get_playbook_api_v1_playbooks__playbook_id__get
+ security:
+ - HTTPBearer: []
parameters:
- name: playbook_id
in: path
@@ -4442,6 +4452,8 @@ paths:
- playbooks
summary: Update a playbook
operationId: update_playbook_api_v1_playbooks__playbook_id__put
+ security:
+ - HTTPBearer: []
parameters:
- name: playbook_id
in: path
@@ -4466,6 +4478,8 @@ paths:
- playbooks
summary: Delete a playbook
operationId: delete_playbook_api_v1_playbooks__playbook_id__delete
+ security:
+ - HTTPBearer: []
parameters:
- name: playbook_id
in: path
@@ -4488,6 +4502,8 @@ paths:
- playbooks
summary: Execute a playbook
operationId: run_playbook_api_v1_playbooks__playbook_id__run_post
+ security:
+ - HTTPBearer: []
parameters:
- name: playbook_id
in: path
@@ -20330,6 +20346,11 @@ components:
type: string
format: date-time
title: Built At
+ sources_unavailable:
+ items:
+ type: string
+ type: array
+ title: Sources Unavailable
type: object
required:
- timeline_id
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index 7d5bdda6c..0f547420c 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -886,7 +886,16 @@ async def case_timeline(case_id: str, db: DBSession, user: AuthUser) -> Timeline
for alert_id in list(case_row.alert_ids or [])[:25]:
try:
a = (
- await db.execute(text("SELECT id, title, severity, created_at FROM aisoc_alerts WHERE id = :id").bindparams(id=alert_id))
+ # Tenant-scoped as defence in depth. Reaching this loop already
+ # required a tenant-scoped case, but the predicate costs
+ # nothing and a poisoned ``alert_ids`` array would otherwise
+ # hydrate another tenant's alert title into this timeline.
+ await db.execute(
+ text("SELECT id, title, severity, created_at FROM aisoc_alerts WHERE id = :id AND tenant_id = :tenant_id").bindparams(
+ id=alert_id,
+ tenant_id=str(user.tenant_id),
+ )
+ )
).fetchone()
if a:
events.append(
diff --git a/services/api/app/api/v1/endpoints/identity_timeline.py b/services/api/app/api/v1/endpoints/identity_timeline.py
index 3774b4241..9fc9a6511 100644
--- a/services/api/app/api/v1/endpoints/identity_timeline.py
+++ b/services/api/app/api/v1/endpoints/identity_timeline.py
@@ -55,6 +55,10 @@ class IdentityTimeline(BaseModel):
total_events: int
risk_score: float | None = None
built_at: datetime
+ #: Sources this build could not read. A timeline assembled from fewer
+ #: sources than intended is not the same answer as one that found nothing,
+ #: and the difference used to be visible only in a DEBUG log line.
+ sources_unavailable: list[str] = Field(default_factory=list)
class BuildTimelineRequest(BaseModel):
@@ -102,6 +106,7 @@ async def build_timeline(
to_ts = body.to_ts or now
events: list[TimelineEvent] = []
+ unavailable: list[str] = []
# ── 1. Alerts that reference this identity ──────────────────────────────
try:
@@ -110,7 +115,8 @@ async def build_timeline(
"""
SELECT id, created_at, severity, title, evidence, mitre_technique
FROM aisoc_alerts
- WHERE created_at BETWEEN :from_ts AND :to_ts
+ WHERE tenant_id = :tenant_id
+ AND created_at BETWEEN :from_ts AND :to_ts
AND (
evidence::text ILIKE :pat
OR title ILIKE :pat
@@ -119,6 +125,7 @@ async def build_timeline(
LIMIT :lim
"""
).bindparams(
+ tenant_id=str(user.tenant_id),
from_ts=from_ts,
to_ts=to_ts,
pat=f"%{body.identity_value}%",
@@ -139,42 +146,21 @@ async def build_timeline(
)
)
except Exception as exc:
- log.debug("aisoc_alerts table not available; skipping", error=str(exc))
-
- # ── 2. Raw events from aisoc_events (if table exists) ──────────────────
- try:
- ev_rows = await db.execute(
- text(
- """
- SELECT id, timestamp, event_type, source, description,
- severity, raw_event
- FROM aisoc_events
- WHERE timestamp BETWEEN :from_ts AND :to_ts
- AND raw_event::text ILIKE :pat
- ORDER BY timestamp DESC
- LIMIT :lim
- """
- ).bindparams(
- from_ts=from_ts,
- to_ts=to_ts,
- pat=f"%{body.identity_value}%",
- lim=body.max_events - len(events),
- )
+ # WARNING, not DEBUG: this is the only source the timeline has, so a
+ # failure here means the answer is empty for a reason the caller
+ # cannot see. The reason is also returned on the response.
+ log.warning(
+ "identity_timeline.alert_source_unavailable",
+ error=str(exc).replace("\r", "").replace("\n", " ")[:300],
)
- for row in ev_rows.fetchall():
- events.append(
- TimelineEvent(
- event_id=row.id,
- timestamp=row.timestamp,
- event_type=row.event_type or "other",
- source=row.source or "aisoc_events",
- description=row.description or "",
- severity=row.severity,
- raw=row.raw_event,
- )
- )
- except Exception as exc:
- log.debug("aisoc_events table not available; skipping", error=str(exc))
+ unavailable.append("aisoc_alerts")
+
+ # There is no second source. A block here queried a table named
+ # ``aisoc_events`` that no migration creates, nothing writes to, and that
+ # appears nowhere else in the repository — with its failure swallowed at
+ # DEBUG, so it silently returned nothing on every deployment while reading
+ # as a second source of evidence. Removed rather than tenant-scoped: there
+ # is nothing to scope.
# ── 3. Sort chronologically ─────────────────────────────────────────────
events.sort(key=lambda e: e.timestamp)
@@ -189,6 +175,7 @@ async def build_timeline(
total_events=len(events),
risk_score=_risk_score(events),
built_at=now,
+ sources_unavailable=unavailable,
)
diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.py
index c89e8a4fa..c21fe1d32 100644
--- a/services/api/app/api/v1/endpoints/playbooks.py
+++ b/services/api/app/api/v1/endpoints/playbooks.py
@@ -4,21 +4,41 @@ Pillar-2 Playbook proxy endpoints.
The api service acts as a gateway that forwards playbook CRUD and run
requests to the agents service. This keeps the public API contract in
one place while the engine lives in services/agents.
+
+Authorization
+-------------
+
+Every route below is gated. The module previously declared no dependency of
+any kind — no ``Depends``, no ``require_permission`` — and there is no global
+auth middleware in ``app/main.py``, so all eight routes were reachable
+unauthenticated, including ``POST /playbooks/{id}/run``, which executes a
+playbook against the estate.
+
+The three permissions used here (``playbooks:read``, ``playbooks:write``,
+``playbooks:execute``) already existed in ``ROLE_PERMISSIONS`` and had no
+reader. ``playbooks:execute`` is deliberately distinct from ``:write`` so an
+analyst can run a governed playbook without being able to edit one.
"""
from __future__ import annotations
import os
import re
-from typing import Any
+from typing import Annotated, Any
import httpx
-from fastapi import APIRouter, HTTPException, Request, status
+from fastapi import APIRouter, Depends, HTTPException, Request, status
+
+from app.api.v1.deps import AuthUser, require_permission
_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL") or os.getenv("AGENTS_API_URL", "http://agents:8084")
router = APIRouter(prefix="/playbooks", tags=["playbooks"])
+ReadUser = Annotated[AuthUser, Depends(require_permission("playbooks:read"))]
+WriteUser = Annotated[AuthUser, Depends(require_permission("playbooks:write"))]
+ExecuteUser = Annotated[AuthUser, Depends(require_permission("playbooks:execute"))]
+
# Allowlist for playbook/run IDs: UUIDs or short slug-style alphanumeric IDs.
# Prevents partial-SSRF via path traversal in proxied requests.
_SAFE_ID_RE = re.compile(r"^[0-9a-zA-Z_\-]{1,128}$")
@@ -61,48 +81,48 @@ async def _proxy(method: str, path: str, **kwargs) -> Any:
@router.get("", summary="List playbooks")
-async def list_playbooks(enabled_only: bool = False):
+async def list_playbooks(user: ReadUser, enabled_only: bool = False):
return await _proxy("GET", "", params={"enabled_only": enabled_only})
@router.post("", summary="Create playbook", status_code=201)
-async def create_playbook(request: Request):
+async def create_playbook(request: Request, user: WriteUser):
body = await request.json()
return await _proxy("POST", "", json=body)
@router.get("/runs", summary="List playbook runs")
-async def list_runs(limit: int = 50):
+async def list_runs(user: ReadUser, limit: int = 50):
return await _proxy("GET", "/runs", params={"limit": limit})
@router.get("/runs/{run_id}", summary="Get a playbook run")
-async def get_run(run_id: str):
+async def get_run(run_id: str, user: ReadUser):
safe_run_id = _validate_path_id(run_id, "run_id")
return await _proxy("GET", f"/runs/{safe_run_id}")
@router.get("/{playbook_id}", summary="Get a playbook")
-async def get_playbook(playbook_id: str):
+async def get_playbook(playbook_id: str, user: ReadUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
return await _proxy("GET", f"/{safe_id}")
@router.put("/{playbook_id}", summary="Update a playbook")
-async def update_playbook(playbook_id: str, request: Request):
+async def update_playbook(playbook_id: str, request: Request, user: WriteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
return await _proxy("PUT", f"/{safe_id}", json=body)
@router.delete("/{playbook_id}", summary="Delete a playbook", status_code=204, response_model=None)
-async def delete_playbook(playbook_id: str):
+async def delete_playbook(playbook_id: str, user: WriteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
await _proxy("DELETE", f"/{safe_id}")
@router.post("/{playbook_id}/run", summary="Execute a playbook", status_code=202)
-async def run_playbook(playbook_id: str, request: Request):
+async def run_playbook(playbook_id: str, request: Request, user: ExecuteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
return await _proxy("POST", f"/{safe_id}/run", json=body)
diff --git a/services/api/tests/test_tenant_scope_and_auth_holes.py b/services/api/tests/test_tenant_scope_and_auth_holes.py
new file mode 100644
index 000000000..ac25fb454
--- /dev/null
+++ b/services/api/tests/test_tenant_scope_and_auth_holes.py
@@ -0,0 +1,224 @@
+"""Three routes that read tenant data without scoping it, or without auth.
+
+What these tests defend
+~~~~~~~~~~~~~~~~~~~~~~~
+
+1. ``/identity-timeline`` bound ``AuthUser`` and never used it. Its SQL against
+ ``aisoc_alerts`` carried no ``tenant_id`` predicate, so any authenticated
+ user could pull every tenant's alerts whose title or evidence matched a
+ substring they chose — and the substring is the search term, so the match
+ is attacker-controlled.
+
+2. ``/playbooks`` declared no dependency of any kind across eight routes, and
+ there is no global auth middleware, so all eight were reachable
+ unauthenticated — including ``POST /playbooks/{id}/run``, which executes a
+ playbook against the estate. The three permissions it now uses already
+ existed in ``ROLE_PERMISSIONS`` with no reader.
+
+3. ``cases`` hydrated linked-alert titles with ``WHERE id = :id`` and no
+ tenant predicate. Reaching it requires a tenant-scoped case, so this is
+ defence in depth rather than a live read — but a poisoned ``alert_ids``
+ array would otherwise surface another tenant's alert title.
+
+Every test here fails against the previous code.
+"""
+
+from __future__ import annotations
+
+import inspect
+import re
+import uuid
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.endpoints import cases as cases_module
+from app.api.v1.endpoints import identity_timeline as it_module
+from app.api.v1.endpoints import playbooks as pb_module
+from app.api.v1.endpoints.identity_timeline import BuildTimelineRequest, build_timeline
+
+_ENDPOINTS = Path(it_module.__file__).parent
+
+
+def _user(tenant_id: uuid.UUID | None = None) -> Any:
+ u = MagicMock()
+ u.id = uuid.uuid4()
+ u.tenant_id = tenant_id or uuid.uuid4()
+ return u
+
+
+def _capturing_db(rows: list[Any] | None = None) -> Any:
+ """AsyncSession double that records the statements it executed."""
+ executed: list[Any] = []
+
+ async def _execute(stmt: Any, *args: Any, **kwargs: Any) -> Any:
+ executed.append(stmt)
+ result = MagicMock()
+ result.fetchall = MagicMock(return_value=rows or [])
+ result.fetchone = MagicMock(return_value=(rows or [None])[0])
+ return result
+
+ db = MagicMock()
+ db.execute = AsyncMock(side_effect=_execute)
+ db.executed = executed
+ return db
+
+
+class TestIdentityTimelineIsTenantScoped:
+ async def test_alert_query_carries_a_tenant_predicate(self) -> None:
+ tenant = uuid.uuid4()
+ db = _capturing_db()
+
+ await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="svc-backup"),
+ db=db,
+ user=_user(tenant),
+ )
+
+ assert db.executed, "the alert source was never queried"
+ sql = str(db.executed[0])
+ assert "tenant_id" in sql, f"no tenant predicate in: {sql}"
+
+ async def test_the_callers_own_tenant_is_bound(self) -> None:
+ tenant = uuid.uuid4()
+ db = _capturing_db()
+
+ await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="svc-backup"),
+ db=db,
+ user=_user(tenant),
+ )
+
+ params = db.executed[0].compile().params
+ assert params.get("tenant_id") == str(tenant)
+
+ async def test_search_term_is_bound_not_interpolated(self) -> None:
+ """The identity value is attacker-chosen; it must stay a parameter."""
+ db = _capturing_db()
+
+ await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="'; DROP TABLE aisoc_alerts; --"),
+ db=db,
+ user=_user(),
+ )
+
+ assert "DROP TABLE" not in str(db.executed[0])
+
+ async def test_returns_an_empty_timeline_rather_than_raising(self) -> None:
+ db = _capturing_db()
+ result = await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="nobody"),
+ db=db,
+ user=_user(),
+ )
+ assert result.events == []
+ assert result.total_events == 0
+
+ async def test_an_unreadable_source_is_reported_not_swallowed(self) -> None:
+ """It used to be a DEBUG line, so an empty timeline from a broken query
+ was indistinguishable from an empty timeline from no matches."""
+ db = MagicMock()
+ db.execute = AsyncMock(side_effect=RuntimeError("relation does not exist"))
+
+ result = await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="svc-backup"),
+ db=db,
+ user=_user(),
+ )
+
+ assert result.sources_unavailable == ["aisoc_alerts"]
+ assert result.events == []
+
+ async def test_a_healthy_build_reports_nothing_unavailable(self) -> None:
+ result = await build_timeline(
+ body=BuildTimelineRequest(identity_kind="user", identity_value="svc-backup"),
+ db=_capturing_db(),
+ user=_user(),
+ )
+ assert result.sources_unavailable == []
+
+ def test_the_phantom_second_source_is_gone(self) -> None:
+ """``aisoc_events`` is created by no migration, written by nothing, and
+ appears nowhere else in the repository. The block that queried it
+ swallowed its own failure at DEBUG, so it read as a second source of
+ evidence while returning nothing on every deployment."""
+ source = Path(it_module.__file__).read_text()
+ query_lines = [ln for ln in source.splitlines() if "FROM aisoc_events" in ln]
+ assert query_lines == []
+
+
+class TestPlaybookRoutesRequirePermission:
+ #: route function → the permission it must demand.
+ EXPECTED = {
+ "list_playbooks": "playbooks:read",
+ "get_playbook": "playbooks:read",
+ "list_runs": "playbooks:read",
+ "get_run": "playbooks:read",
+ "create_playbook": "playbooks:write",
+ "update_playbook": "playbooks:write",
+ "delete_playbook": "playbooks:write",
+ "run_playbook": "playbooks:execute",
+ }
+
+ def test_every_route_function_takes_an_authenticated_principal(self) -> None:
+ for name in self.EXPECTED:
+ fn = getattr(pb_module, name)
+ params = inspect.signature(fn).parameters
+ assert "user" in params, f"{name} has no authenticated principal"
+
+ def test_no_route_is_left_ungated(self) -> None:
+ """Counts decorated routes against the expected map so a new route
+ added without auth fails here rather than shipping open."""
+ source = Path(pb_module.__file__).read_text()
+ decorated = re.findall(r"@router\.(?:get|post|put|patch|delete)\(", source)
+ assert len(decorated) == len(self.EXPECTED)
+
+ def test_execute_is_a_distinct_permission_from_write(self) -> None:
+ """An analyst can run a governed playbook without being able to edit
+ one, which is the reason the two permissions exist separately."""
+ assert self.EXPECTED["run_playbook"] != self.EXPECTED["update_playbook"]
+
+ def test_the_permissions_used_are_ones_roles_actually_hold(self) -> None:
+ from app.core.security import ROLE_PERMISSIONS
+
+ granted = {perm for perms in ROLE_PERMISSIONS.values() for perm in perms}
+ for name, permission in self.EXPECTED.items():
+ assert permission in granted, f"{name} demands {permission}, which no role grants"
+
+ def test_module_declares_the_dependency(self) -> None:
+ source = Path(pb_module.__file__).read_text()
+ assert "require_permission" in source
+
+
+class TestCaseTimelineAlertHydrationIsScoped:
+ def test_linked_alert_lookup_binds_a_tenant(self) -> None:
+ source = Path(cases_module.__file__).read_text()
+ matches = [ln for ln in source.splitlines() if "FROM aisoc_alerts WHERE id" in ln]
+ assert matches, "the linked-alert hydration query moved; re-point this test"
+ for line in matches:
+ assert "tenant_id" in line, f"unscoped alert read: {line.strip()}"
+
+
+class TestNoUnscopedAlertReadsRemain:
+ """A directory-wide sweep, so a new endpoint cannot reintroduce the shape.
+
+ Deliberately a text scan rather than a call-graph analysis: the property is
+ "every raw SQL read of the alerts tables names tenant_id", which is exactly
+ what a reviewer checks by eye, and a scan cannot be defeated by a helper
+ that hides the predicate one frame away.
+ """
+
+ def test_every_raw_alerts_select_mentions_tenant_id(self) -> None:
+ offenders: list[str] = []
+ for path in _ENDPOINTS.glob("*.py"):
+ text = path.read_text()
+ for match in re.finditer(r"FROM\s+aisoc_alerts\b(.{0,400}?)(?:\"\"\"|\)\s*$)", text, re.S | re.I):
+ if "tenant_id" not in match.group(1):
+ offenders.append(f"{path.name}: {match.group(0)[:120].strip()}")
+ assert offenders == [], "unscoped reads of aisoc_alerts:\n" + "\n".join(offenders)
+
+
[email protected]("module", [it_module, pb_module])
+def test_modules_import_cleanly(module: Any) -> None:
+ assert module is not None