Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
security(api): authorize the hunt surface and the detection drafting routes (#1054)
Beenu Arora51a17fc50f0c
diff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.pyindex a8116933d..465628ae1 100644--- a/scripts/check_route_authz.py+++ b/scripts/check_route_authz.py@@ -98,7 +98,11 @@ AUTHZ_CALLS = frozenset(#: the three write routes in `remediation.py`, then 90 once the MSSP write#: surface took a permission (rule packs and overrides `rules:write`,#: delegations `users:write`, adoption and organisation founding-#: `settings:write`, provider notes `cases:write`).+#: `settings:write`, provider notes `cases:write`), then 77 once the hunt+#: surface took `lake:query` (a hunt is a stored query; authoring and running+#: it are one entitlement) and the three detection-drafting routes took+#: `rules:read` (they persist nothing, so the floor is entitlement to read+#: detection logic; promoting a draft is separately `rules:write`).#:#: Four routes under `/mssp/organizations` remain in this count and are not#: debt: they authorize through `_admin_scope`, an organisation owner/admin@@ -106,7 +110,7 @@ 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 = 90+MAX_UNAUTHORIZED = 77def _authorizing_names(tree: ast.Module) -> set[str]:diff --git a/services/api/app/api/v1/endpoints/detection_loop.py b/services/api/app/api/v1/endpoints/detection_loop.pyindex 0ca293d53..b1533fd7b 100644--- a/services/api/app/api/v1/endpoints/detection_loop.py+++ b/services/api/app/api/v1/endpoints/detection_loop.py@@ -14,6 +14,16 @@ Endpoints* ``POST /detection-loop/suggest`` Trigger FP → Sigma draft.* ``GET /detection-loop/suggestions`` List LLM-drafted suggestions.* ``GET /detection-loop/suggestions/{id}`` Detail of one suggestion.++Authorization+-------------+``POST /suggest`` requires ``rules:read``. The route reads the triggering+rule's body out of ``aisoc_detection_rules`` and returns a draft of it, so+the floor is that the caller may read detection content — which a ``viewer``+may not, and which is what made this route a small disclosure of the+tenant's detection logic as well as an ungated LLM spend. The draft is+persisted as a proposal by the DAC lifecycle, which is gated on+``rules:write``; drafting needs the read, promoting needs the write."""from __future__ import annotations@@ -23,13 +33,13 @@ import loggingimport textwrapimport uuidfrom datetime import UTC, datetime-from typing import Any+from typing import Annotated, Any-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel, Fieldfrom sqlalchemy import text-from app.api.v1.deps import AuthUser+from app.api.v1.deps import AuthUser, require_permissionfrom app.core.config import settingsfrom app.db.rls import TenantDBSessionfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_request@@ -180,7 +190,7 @@ _SUGGESTIONS: dict[uuid.UUID, dict[str, Any]] = {}async def suggest_fp_fix(body: SuggestRequest,db: TenantDBSession,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("rules:read"))],) -> SuggestionResponse:"""Retrieve the triggering rule + alert evidence, then draft a Sigma improvement.diff --git a/services/api/app/api/v1/endpoints/graph.py b/services/api/app/api/v1/endpoints/graph.pyindex fbf352f2f..3fc30e581 100644--- a/services/api/app/api/v1/endpoints/graph.py+++ b/services/api/app/api/v1/endpoints/graph.py@@ -668,13 +668,18 @@ async def list_investigation_tools(}+# `lake:query` because that is literally what a pivot is: `dispatch` runs a+# typed primitive against the tenant's event lake and returns rows from it.+# The tenant comes from the session, so this was never a cross-tenant read —+# it was a `viewer`, a role deliberately given no lake access at all, reading+# raw events through a route that only checked for a session.@router.post("/investigate/query",summary="Run one typed investigation primitive against the event lake",)async def run_investigation_tool(request: InvestigationToolRequest,- current_user: CurrentUser = Depends(get_current_user),+ current_user: Annotated[CurrentUser, Depends(require_permission("lake:query"))],) -> dict[str, Any]:"""Execute one pivot. Tenant comes from the session, never the request."""result = await dispatch(request.tool, str(current_user.tenant_id), request.args)diff --git a/services/api/app/api/v1/endpoints/hunts.py b/services/api/app/api/v1/endpoints/hunts.pyindex 0deb48459..4bbe01b06 100644--- a/services/api/app/api/v1/endpoints/hunts.py+++ b/services/api/app/api/v1/endpoints/hunts.py@@ -20,6 +20,22 @@ remain visible only to the tenant that created them once they are owned.Legacy rows created before migration 043 with ``tenant_id IS NULL`` aresilently treated as orphans — they are *not* returned to anyone, ensuring nocross-tenant data leakage during the rollout window.++Authorization+-------------+Writes require ``lake:query``. A hunt is a stored query over telemetry —+``run_hunt`` executes it against Elasticsearch — so authoring one and running+one are the same entitlement, and storing a query you may not run is+meaningless. ``lake:query`` is held by ``tenant_admin``, ``soc_lead``,+``soc_analyst`` and ``threat_hunter``, and withheld from ``viewer`` and+``api_service``.++``rules:write`` was the other candidate and is the wrong one. It is not held+by ``soc_analyst``, and the analyst is who this module is for — the summary+above says so. Gating the workbench on it would have taken the hunt surface+away from the role that uses it most, which is an outage rather than a fix.+Detection *content* authoring is gated on ``rules:*`` elsewhere; a hypothesis+is not a rule."""from __future__ import annotations@@ -29,14 +45,14 @@ import loggingimport osimport uuidfrom datetime import UTC, datetime-from typing import Any, Literal+from typing import Annotated, Any, Literalimport httpx-from fastapi import APIRouter, HTTPException, Query, status+from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom pydantic import BaseModel, Fieldfrom sqlalchemy import text-from app.api.v1.deps import AuthUser, DBSession+from app.api.v1.deps import AuthUser, DBSession, require_permissionfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_requestfrom app.services.model_aliases import chat_completions_url, resolve_api_key, resolve_model_alias@@ -247,7 +263,9 @@ async def list_hunts(@router.post("", response_model=HuntResponse, status_code=status.HTTP_201_CREATED, summary="Create hunt hypothesis")-async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) -> HuntResponse:+async def create_hunt(+ body: CreateHuntRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("lake:query"))]+) -> HuntResponse:mitre = body.mitre_technique or body.mitre_tactic# In air-gapped mode the LLM call is refused (AirgapViolation); fall back to# the deterministic query templates so hunt creation still succeeds offline@@ -307,7 +325,9 @@ async def get_hunt(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> HuntRes@router.patch("/{hunt_id}", response_model=HuntResponse, summary="Update hunt")-async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession, user: AuthUser) -> HuntResponse:+async def update_hunt(+ hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("lake:query"))]+) -> HuntResponse:sets = ["updated_at = :now"]params: dict[str, Any] = {"id": hunt_id,@@ -367,7 +387,9 @@ async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession@router.post("/{hunt_id}/run", response_model=HuntRunResponse, status_code=status.HTTP_200_OK, summary="Execute hunt query")-async def run_hunt(hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user: AuthUser) -> HuntRunResponse:+async def run_hunt(+ hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("lake:query"))]+) -> HuntRunResponse:hunt_row = (await db.execute(text("SELECT * FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=hunt_id, tenant_id=user.tenant_id)@@ -489,7 +511,9 @@ async def list_runs(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> list[H@router.post("/{hunt_id}/findings", response_model=HuntResponse, summary="Append findings")-async def add_findings(hunt_id: uuid.UUID, body: AddFindingsRequest, db: DBSession, user: AuthUser) -> HuntResponse:+async def add_findings(+ hunt_id: uuid.UUID, body: AddFindingsRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("lake:query"))]+) -> HuntResponse:existing = (await db.execute(text("SELECT findings FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(diff --git a/services/api/app/api/v1/endpoints/nl_detection.py b/services/api/app/api/v1/endpoints/nl_detection.pyindex 323e7acc9..d3ff4045c 100644--- a/services/api/app/api/v1/endpoints/nl_detection.py+++ b/services/api/app/api/v1/endpoints/nl_detection.py@@ -209,8 +209,15 @@ def _template_fallback(request: NLDetectionRequest) -> dict[str, str | None]:# ---------------------------------------------------------------------------+# `/translate` drafts and `/propose` persists, so they take the read and the+# write of the same resource. `rules:read` rather than `rules:write` on the+# drafting half because nothing is stored: rule text in, rule text out. It is+# still a real refusal — `viewer` holds neither, and the roles that may author+# detection content are exactly the roles that may draft it.@router.post("/translate", response_model=NLDetectionResponse)-async def translate_detection(payload: NLDetectionRequest, user: AuthUser) -> NLDetectionResponse:+async def translate_detection(+ payload: NLDetectionRequest, user: Annotated[AuthUser, Depends(require_permission("rules:read"))]+) -> NLDetectionResponse:"""Convert a plain-English threat description into multi-platform detection rules."""if not payload.description.strip():raise HTTPException(diff --git a/services/api/app/api/v1/endpoints/nl_query.py b/services/api/app/api/v1/endpoints/nl_query.pyindex 029b195f1..11dd78008 100644--- a/services/api/app/api/v1/endpoints/nl_query.py+++ b/services/api/app/api/v1/endpoints/nl_query.py@@ -18,6 +18,17 @@ Endpoints---------* ``POST /nl-query/translate`` Translate NL → ES|QL / SPL / KQL.* ``POST /nl-query/execute`` Translate + execute against Elasticsearch.++Authorization+-------------+Both require ``lake:query``. Execute obviously does. Translate does because+it is the first half of the same request — the console calls them in+sequence, the output is a query against the caller's own telemetry, and+there is no coherent entitlement that lets a principal compose a lake query+it may not run. ``lake:query`` covers every role that hunts and excludes+``viewer``, which is what was wrong: a read-only role could spend the+tenant's LLM budget translating and, on ``/execute``, read raw events the+lake permissions exist to keep from it."""from __future__ import annotations@@ -27,15 +38,15 @@ import sysimport uuidfrom datetime import UTC, datetimefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Literal+from typing import TYPE_CHECKING, Annotated, Any, Literalfrom urllib.parse import urlparseimport httpximport structlog-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel, Field-from app.api.v1.deps import AuthUser+from app.api.v1.deps import AuthUser, require_permissionfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.core.config import settingsfrom app.db.clickhouse import (@@ -438,7 +449,7 @@ async def _execute_against_lake()async def translate_query(body: NLQueryTranslateRequest,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("lake:query"))],) -> NLQueryTranslateResponse:translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)return NLQueryTranslateResponse(@@ -462,7 +473,7 @@ async def translate_query()async def execute_query(body: NLQueryExecuteRequest,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("lake:query"))],db: TenantDBSession,) -> NLQueryExecuteResponse:translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)diff --git a/services/api/app/api/v1/endpoints/saved_hunts.py b/services/api/app/api/v1/endpoints/saved_hunts.pyindex 6c799918a..673590936 100644--- a/services/api/app/api/v1/endpoints/saved_hunts.py+++ b/services/api/app/api/v1/endpoints/saved_hunts.py@@ -30,27 +30,37 @@ by side because they answer different jobs-to-be-done.Authorisation~~~~~~~~~~~~~-Saved hunts are *tenant-shared* (every analyst in the tenant sees every-saved hunt — like a shared knowledge base) and gated on authentication-only. Authoring permission inherits from the role; for now, anyone with-read access to the ``/hunt`` page can save and delete. A finer-``hunt:save`` / ``hunt:delete`` split is a deliberate v1.x follow-up if-multi-team tenants ask for it.+Saved hunts are *tenant-shared*: every analyst in the tenant sees every+saved hunt, like a shared knowledge base.++Reads are authentication-only for that reason. Writes are not, and used not+to be either — "anyone with read access to the ``/hunt`` page can save and+delete" was true of ``viewer``, a role with no write permission of any kind,+which could therefore delete another team's saved hunt out of a shared list.++Writing one requires ``lake:query``. A saved hunt *is* a stored query, and+the run route executes it against the lake, so being able to store one you+may not run is meaningless; the two are one entitlement. It is held by+``tenant_admin``, ``soc_lead``, ``soc_analyst`` and ``threat_hunter`` —+every role that hunts — and withheld from ``viewer`` and ``api_service``.+The ``hunt:save`` / ``hunt:delete`` split this docstring used to defer is+still deferred, and is now about which *team* may delete a shared row rather+than about whether a read-only role may."""from __future__ import annotationsimport uuidfrom datetime import UTC, datetime-from typing import Any, Literal+from typing import Annotated, Any, Literalimport structlog-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel, ConfigDict, Fieldfrom sqlalchemy import and_, delete, select, updatefrom sqlalchemy.exc import IntegrityError-from app.api.v1.deps import AuthUser+from app.api.v1.deps import AuthUser, require_permission# Defer import of the NL translator helpers — `nl_query.py` already does the# vendored-tree resolution dance at import time and we want the same module@@ -344,7 +354,7 @@ async def list_saved_hunts()async def create_saved_hunt(payload: CreateSavedHuntRequest,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("lake:query"))],db: TenantDBSession,) -> SavedHuntModel:"""Translate the NL question and persist the hunt."""@@ -418,7 +428,7 @@ async def get_saved_hunt()async def delete_saved_hunt(hunt_id: str,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("lake:query"))],db: TenantDBSession,) -> None:"""Delete a saved hunt owned by the caller's tenant."""@@ -450,7 +460,7 @@ async def delete_saved_hunt()async def run_saved_hunt(hunt_id: str,- user: AuthUser,+ user: Annotated[AuthUser, Depends(require_permission("lake:query"))],db: TenantDBSession,) -> RunSavedHuntResponse:"""Re-translate the saved NL question and stamp ``last_run_at``.diff --git a/services/api/app/api/v1/endpoints/translation.py b/services/api/app/api/v1/endpoints/translation.pyindex 3814f3046..3ab0e71cd 100644--- a/services/api/app/api/v1/endpoints/translation.py+++ b/services/api/app/api/v1/endpoints/translation.py@@ -9,6 +9,17 @@ Endpoints---------* ``POST /translation/translate`` Translate a rule from one format to multiple targets.* ``GET /translation/formats`` List supported source/target formats.++Authorization+-------------+``POST /translate`` requires ``rules:read`` — deliberately the read and not+the write. It persists nothing: a caller hands in rule text and gets rule+text back. What it does need is entitlement to the detection surface at all,+and ``rules:read`` is exactly that: held by ``tenant_admin``, ``soc_lead``+and ``threat_hunter``, withheld from ``viewer``. ``rules:write`` would be+stronger than the act and would diverge from the drafting routes in+``nl_detection.py`` and ``detection_loop.py``, which make the same+read-to-draft, write-to-persist distinction."""from __future__ import annotations@@ -16,12 +27,12 @@ from __future__ import annotationsimport jsonimport loggingimport os-from typing import Any, Literal+from typing import Annotated, Any, Literal-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel, Field-from app.api.v1.deps import AuthUser+from app.api.v1.deps import AuthUser, require_permissionfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_requestfrom app.services.model_aliases import chat_completions_url, resolve_api_key, resolve_model_alias@@ -248,7 +259,7 @@ def _fallback_templates(req: TranslateRequest) -> dict[str, Any]:status_code=status.HTTP_200_OK,summary="Translate a detection rule across formats",)-async def translate_rule(body: TranslateRequest, user: AuthUser) -> TranslateResponse:+async def translate_rule(body: TranslateRequest, user: Annotated[AuthUser, Depends(require_permission("rules:read"))]) -> TranslateResponse:if not body.target_formats:raise HTTPException(status_code=400, detail="At least one target_format is required.")diff --git a/services/api/tests/test_hunting_route_permissions.py b/services/api/tests/test_hunting_route_permissions.pynew file mode 100644index 000000000..57513280f--- /dev/null+++ b/services/api/tests/test_hunting_route_permissions.py@@ -0,0 +1,258 @@+"""The hunting and detection-drafting write routes authenticated and stopped.++Thirteen routes across seven modules resolved a session and checked no+entitlement. `saved_hunts.py` said so in its own docstring — "anyone with read+access to the `/hunt` page can save and delete" — which was true of `viewer`,+a role with no write permission of any kind, in a tenant where saved hunts are+a *shared* list.++Two permissions, and the split is the point rather than a detail.++`lake:query` for the hunt surface. A hunt is a stored query; `run_hunt` and+`run_saved_hunt` execute it, `/nl-query/execute` executes it, and+`/graph/investigate/query` runs a typed primitive against the event lake and+returns rows. Being able to store or compose a query you may not run is+meaningless, so authoring and running are one entitlement. Held by every role+that hunts — including `soc_analyst`, which is why `rules:write` was rejected+for this half.++`rules:read` for the three routes that draft detection content and persist+nothing. The floor there is entitlement to read detection logic at all, which+`viewer` does not have; promoting a draft is separately gated on+`rules:write`.++The tests assert in both directions and read the permission out of the+resolved dependency tree rather than the source, so+`Annotated[Any, require_permission("x")]` with no `Depends()` — the shape that+shipped on eleven routes and read as gated — reports nothing here.+"""++from __future__ import annotations++import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from app.api.v1.deps import CurrentUser, get_current_user+from app.api.v1.endpoints import detection_loop, graph, hunts, nl_detection, nl_query, saved_hunts, translation+from app.db.database import get_db+from fastapi import FastAPI+from fastapi.testclient import TestClient++TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")+HUNT = uuid.UUID("22222222-2222-2222-2222-222222222222")++#: (module, handler, permission, method, path, payload). One table drives the+#: refused case, the admitted case and the wiring assertion so the three+#: cannot disagree.+GATED: list[tuple[Any, str, str, str, str, dict[str, Any] | None]] = [+ (hunts, "create_hunt", "lake:query", "POST", "/api/v1/hunts", {"title": "t", "hypothesis": "h"}),+ (hunts, "update_hunt", "lake:query", "PATCH", f"/api/v1/hunts/{HUNT}", {"status": "completed"}),+ (hunts, "run_hunt", "lake:query", "POST", f"/api/v1/hunts/{HUNT}/run", {"platform": "esql"}),+ (hunts, "add_findings", "lake:query", "POST", f"/api/v1/hunts/{HUNT}/findings", {"findings": [{"note": "n"}]}),+ (saved_hunts, "create_saved_hunt", "lake:query", "POST", "/api/v1/saved-hunts", {"name": "n", "nl_query": "logins from iran"}),+ (saved_hunts, "delete_saved_hunt", "lake:query", "DELETE", f"/api/v1/saved-hunts/{HUNT}", None),+ (saved_hunts, "run_saved_hunt", "lake:query", "POST", f"/api/v1/saved-hunts/{HUNT}/run", None),+ (nl_query, "translate_query", "lake:query", "POST", "/api/v1/nl-query/translate", {"question": "failed logins today"}),+ (nl_query, "execute_query", "lake:query", "POST", "/api/v1/nl-query/execute", {"question": "failed logins today"}),+ (graph, "run_investigation_tool", "lake:query", "POST", "/api/v1/graph/investigate/query", {"tool": "host_processes", "args": {}}),+ (+ nl_detection,+ "translate_detection",+ "rules:read",+ "POST",+ "/api/v1/nl-detection/translate",+ {"description": "psexec lateral movement"},+ ),+ (+ translation,+ "translate_rule",+ "rules:read",+ "POST",+ "/api/v1/translation/translate",+ {"rule": "title: x", "source_format": "sigma", "target_formats": ["spl"]},+ ),+ (detection_loop, "suggest_fp_fix", "rules:read", "POST", "/api/v1/detection-loop/suggest", {"alert_id": str(uuid.uuid4())}),+]++#: A role holding each permission. `soc_analyst` for `lake:query` on purpose:+#: it is the role `rules:write` would have locked out, so the admitted case+#: fails if the hunt surface is ever re-gated on a detection permission.+HOLDER = {"lake:query": "soc_analyst", "rules:read": "threat_hunter"}++#: Roles that must be refused. `viewer` is the advisory shape. `api_service`+#: holds no lake permission either and is included because a machine key is+#: the credential most likely to be over-scoped by accident.+REFUSED = {"lake:query": ["viewer", "api_service"], "rules:read": ["viewer", "soc_analyst"]}+++def _user(role: str) -> CurrentUser:+ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role=role, email=f"{role}@tenant.example")+++def _db() -> AsyncMock:+ """A session that answers every lookup with "no such row".++ A 404 past the permission check is a pass for these tests: what is under+ test is whether the request reached the handler at all. Returning rows+ would mean maintaining seven different row shapes to prove one thing.+ """+ result = MagicMock()+ result.fetchone = MagicMock(return_value=None)+ result.fetchall = MagicMock(return_value=[])+ result.scalar_one_or_none = MagicMock(return_value=None)+ result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))+ result.rowcount = 0+ db = AsyncMock()+ db.execute = AsyncMock(return_value=result)+ db.get = AsyncMock(return_value=None)+ db.commit = AsyncMock()+ db.rollback = AsyncMock()+ db.refresh = AsyncMock()+ db.flush = AsyncMock()+ db.delete = AsyncMock()+ db.add = MagicMock()+ return db+++def _request(module: Any, role: str, method: str, path: str, payload: dict[str, Any] | None) -> tuple[int, bool]:+ app = FastAPI()+ app.include_router(module.router, prefix="/api/v1")+ db = _db()+ app.dependency_overrides[get_current_user] = lambda: _user(role)+ app.dependency_overrides[get_db] = lambda: db+ try:+ from app.db.rls import get_tenant_db # noqa: PLC0415 - optional per module++ app.dependency_overrides[get_tenant_db] = lambda: db+ except ImportError: # pragma: no cover - the alias moved+ pass+ client = TestClient(app, raise_server_exceptions=False)+ response = client.request(method, path, json=payload)+ return response.status_code, db.commit.await_count > 0+++def _permissions_on(route: Any) -> list[str]:+ """Permissions FastAPI will actually enforce, from the dependency tree."""+ found: list[str] = []++ def walk(dependant: Any) -> None:+ call = getattr(dependant, "call", None)+ if getattr(call, "__name__", "") == "_check":+ for cell in getattr(call, "__closure__", None) or ():+ if isinstance(cell.cell_contents, str):+ found.append(cell.cell_contents)+ for sub in getattr(dependant, "dependencies", []):+ walk(sub)++ walk(route.dependant)+ return found+++def _route_for(module: Any, handler_name: str) -> Any:+ for route in module.router.routes:+ if getattr(route, "endpoint", None) is getattr(module, handler_name):+ return route+ raise AssertionError(f"no route registered for {module.__name__}.{handler_name}")+++IDS = [f"{m.__name__.rsplit('.', 1)[-1]}.{h}" for m, h, *_ in GATED]+++class TestUnentitledCallersAreRefused:+ @pytest.mark.parametrize(("module", "handler", "permission", "method", "path", "payload"), GATED, ids=IDS)+ def test_every_role_without_the_permission_is_refused(+ self, module: Any, handler: str, permission: str, method: str, path: str, payload: dict[str, Any] | None+ ) -> None:+ for role in REFUSED[permission]:+ status, committed = _request(module, role, method, path, payload)+ assert not committed, f"{role} committed a write through {handler}"+ assert status == 403, f"{role} got HTTP {status} from {handler}, not 403"++ def test_a_viewer_cannot_delete_another_teams_saved_hunt(self) -> None:+ """Saved hunts are a tenant-shared list, which is what made this bite.++ The module's own docstring used to say anyone with read access to the+ `/hunt` page could save and delete. `viewer` has read access to that+ page and no write permission anywhere.+ """+ status, committed = _request(saved_hunts, "viewer", "DELETE", f"/api/v1/saved-hunts/{HUNT}", None)+ assert not committed+ assert status == 403++ def test_a_viewer_cannot_read_raw_events_through_an_investigation_pivot(self) -> None:+ """`viewer` is given no lake permission at all, by design."""+ status, _ = _request(graph, "viewer", "POST", "/api/v1/graph/investigate/query", {"tool": "host_processes", "args": {}})+ assert status == 403++ def test_a_viewer_cannot_read_detection_logic_through_a_draft(self) -> None:+ """`POST /detection-loop/suggest` returns the rule body it drafts from."""+ status, _ = _request(detection_loop, "viewer", "POST", "/api/v1/detection-loop/suggest", {"alert_id": str(uuid.uuid4())})+ assert status == 403+++class TestEntitledCallersStillWork:+ """The half that catches a permission applied too strongly."""++ @pytest.mark.parametrize(("module", "handler", "permission", "method", "path", "payload"), GATED, ids=IDS)+ def test_a_holder_of_the_permission_is_admitted(+ self, module: Any, handler: str, permission: str, method: str, path: str, payload: dict[str, Any] | None+ ) -> None:+ status, _ = _request(module, HOLDER[permission], method, path, payload)+ assert status != 403, f"{HOLDER[permission]} holds {permission} but {handler} answered 403"++ @pytest.mark.parametrize(+ ("module", "method", "path", "payload"),+ [+ (hunts, "POST", "/api/v1/hunts", {"title": "t", "hypothesis": "h"}),+ (saved_hunts, "POST", "/api/v1/saved-hunts", {"name": "n", "nl_query": "logins from iran"}),+ (nl_query, "POST", "/api/v1/nl-query/translate", {"question": "failed logins today"}),+ ],+ ids=["hunts", "saved-hunts", "nl-query"],+ )+ def test_an_analyst_may_still_use_the_hunt_surface(self, module: Any, method: str, path: str, payload: dict[str, Any]) -> None:+ """The outage `rules:write` would have caused, asserted rather than argued.++ `soc_analyst` holds no `rules:*` permission. The `/hunt` page is the+ analyst surface and the console's own client calls these three, so+ gating the workbench on a detection permission would have broken it+ for the role that uses it most.+ """+ status, _ = _request(module, "soc_analyst", method, path, payload)+ assert status != 403++ @pytest.mark.parametrize("role", ["soc_lead", "threat_hunter", "tenant_admin"])+ def test_every_hunting_role_may_run_a_saved_hunt(self, role: str) -> None:+ status, _ = _request(saved_hunts, role, "POST", f"/api/v1/saved-hunts/{HUNT}/run", None)+ assert status != 403++ def test_a_viewer_may_still_list_hunts(self) -> None:+ """Reads are unchanged: the shared list stays readable."""+ status, _ = _request(saved_hunts, "viewer", "GET", "/api/v1/saved-hunts", None)+ assert status != 403+++class TestWiring:+ @pytest.mark.parametrize(("module", "handler", "permission", "method", "path", "payload"), GATED, ids=IDS)+ def test_route_enforces_exactly_its_permission(+ self, module: Any, handler: str, permission: str, method: str, path: str, payload: dict[str, Any] | None+ ) -> None:+ assert _permissions_on(_route_for(module, handler)) == [permission]++ @pytest.mark.parametrize(+ "module", [hunts, saved_hunts, nl_query, nl_detection, translation, detection_loop], ids=lambda m: m.__name__.rsplit(".", 1)[-1]+ )+ def test_no_state_changing_route_in_these_modules_is_unguarded(self, module: Any) -> None:+ """These six are now fully gated, so the invariant is "all of them".++ `graph.py` is excluded: it has other state-changing routes that are+ this stack's later work, and asserting "all" there would fail for a+ reason this PR did not cause.+ """+ unguarded = [+ getattr(r.endpoint, "__name__", "?")+ for r in module.router.routes+ if r.methods & {"POST", "PUT", "PATCH", "DELETE"} and not _permissions_on(r)+ ]+ assert not unguarded, f"{module.__name__} has state-changing routes with no permission: {unguarded}"