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.

security(api): authorize asset inventory, both entity graphs and insider threat (#1055)

Beenu Arora02489935eb39
diff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.py
index 465628ae1..8335bc7fc 100644
--- a/scripts/check_route_authz.py
+++ b/scripts/check_route_authz.py
@@ -102,7 +102,12 @@ AUTHZ_CALLS = frozenset(
#: 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`).
+#: detection logic; promoting a draft is separately `rules:write`), then 61
+#: once the asset inventory and both entity graphs took `settings:write` (CMDB
+#: data and correlation infrastructure, matching `/graph/context/import`, which
+#: already required it), insider threat took `cases:write` (investigative
+#: judgement about a subject) and `/identity-timeline/build` took `alerts:read`
+#: (a read-shaped POST over the only table it queries).
#:
#: Four routes under `/mssp/organizations` remain in this count and are not
#: debt: they authorize through `_admin_scope`, an organisation owner/admin
@@ -110,7 +115,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 = 77
+MAX_UNAUTHORIZED = 61
def _authorizing_names(tree: ast.Module) -> set[str]:
diff --git a/services/api/app/api/v1/endpoints/assets.py b/services/api/app/api/v1/endpoints/assets.py
index 4c34a2479..2b2d0e09b 100644
--- a/services/api/app/api/v1/endpoints/assets.py
+++ b/services/api/app/api/v1/endpoints/assets.py
@@ -1,16 +1,33 @@
-"""Asset inventory and vulnerability management endpoints."""
+"""Asset inventory and vulnerability management endpoints.
+
+Authorization
+-------------
+Writes require ``settings:write``. An asset row is CMDB data — criticality,
+owner, business context — and the graph's own CMDB import
+(``POST /graph/context/import``) already requires the same permission, so the
+two doors onto the same class of data agree. It is the tenant's inventory of
+record rather than investigative working material: an analyst reads it while
+triaging and does not curate it, and a wrong criticality silently mis-ranks
+every alert that touches the host.
+
+There is no first-party caller: the console does not reach ``/assets`` and
+nothing inside the platform posts to it, so this is an integration surface,
+and an integration authenticates with an API key whose scopes are granted
+deliberately. Before this it was reachable by ``viewer``, which could delete
+the inventory row for a tier-1 host.
+"""
from __future__ import annotations
import uuid
-from typing import Any
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.deps import CurrentUser
+from app.api.v1.deps import CurrentUser, require_permission
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.asset import Asset, AssetVulnerability
@@ -119,8 +136,8 @@ async def list_assets(
@router.post("", response_model=AssetOut, status_code=status.HTTP_201_CREATED)
async def create_asset(
body: AssetCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> Asset:
data = body.model_dump()
asset = Asset(
@@ -169,8 +186,8 @@ async def get_asset(
async def update_asset(
asset_id: uuid.UUID,
body: AssetUpdate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> Asset:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
@@ -188,8 +205,8 @@ async def update_asset(
@router.delete("/{asset_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_asset(
asset_id: uuid.UUID,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> None:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
@@ -206,8 +223,8 @@ async def delete_asset(
@router.post("/vulnerabilities", response_model=VulnerabilityOut, status_code=status.HTTP_201_CREATED)
async def create_vulnerability(
body: VulnerabilityCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> AssetVulnerability:
# ensure asset belongs to this tenant
asset = await db.get(Asset, body.asset_id)
diff --git a/services/api/app/api/v1/endpoints/graph.py b/services/api/app/api/v1/endpoints/graph.py
index 3fc30e581..2f4ddc458 100644
--- a/services/api/app/api/v1/endpoints/graph.py
+++ b/services/api/app/api/v1/endpoints/graph.py
@@ -868,6 +868,13 @@ async def get_mitre_coverage_compat(
# ─── Write Endpoints ──────────────────────────────────────────────────────────
+# The four entity upserts below require `settings:write`, the same permission
+# as `/context/import` above. They write the graph every investigation reads as
+# fact, and `upsert_alert_graph` links an alert to hosts, users, IOCs and ATT&CK
+# techniques — a forged link is not a visibly bad row, it is a wrong conclusion
+# nothing downstream re-derives. No first-party caller posts here: the platform
+# writes this graph in-process through `app.services.graph_service`, so these
+# routes exist for integrations, which authenticate with a scoped API key.
@router.post(
"/entities/host",
status_code=status.HTTP_201_CREATED,
@@ -875,7 +882,7 @@ async def get_mitre_coverage_compat(
)
async def upsert_host(
payload: UpsertHostRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> dict[str, str]:
"""Create or update a Host node in the knowledge graph."""
await graph_service.upsert_host(
@@ -896,7 +903,7 @@ async def upsert_host(
)
async def upsert_user(
payload: UpsertUserRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> dict[str, str]:
"""Create or update a User node in the knowledge graph."""
await graph_service.upsert_user(
@@ -917,7 +924,7 @@ async def upsert_user(
)
async def upsert_alert_graph(
payload: UpsertAlertGraphRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> dict[str, str]:
"""
Create or update an Alert node and link it to Host, User, IOC, and Technique nodes.
@@ -943,7 +950,7 @@ async def upsert_alert_graph(
)
async def upsert_case_graph(
payload: UpsertCaseGraphRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> dict[str, str]:
"""Create or update a Case node and link it to Alert nodes."""
await graph_service.upsert_case_node(
diff --git a/services/api/app/api/v1/endpoints/identity_graph.py b/services/api/app/api/v1/endpoints/identity_graph.py
index 8a0480798..636dca617 100644
--- a/services/api/app/api/v1/endpoints/identity_graph.py
+++ b/services/api/app/api/v1/endpoints/identity_graph.py
@@ -1,17 +1,33 @@
-"""Identity-centric correlation graph endpoints."""
+"""Identity-centric correlation graph endpoints.
+
+Authorization
+-------------
+Writes require ``settings:write``, the same permission as the entity upserts
+in ``graph.py`` and for the same reason: a node, an edge or an alert-to-
+identity link is correlation infrastructure that every later investigation
+reads as fact. A forged edge between an attacker-controlled account and a
+service identity does not show up as a bad row, it shows up as a conclusion,
+and nothing downstream re-derives it.
+
+``cases:write`` was the alternative — these are written during correlation
+work — and was rejected because it would put graph mutation in the hands of
+every investigating role including ``api_service``, when no first-party
+caller posts here at all. This is an integration surface; an integration's
+API key can be scoped for it explicitly.
+"""
from __future__ import annotations
import uuid
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.deps import CurrentUser
+from app.api.v1.deps import CurrentUser, require_permission
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode
@@ -108,8 +124,8 @@ async def list_nodes(
@router.post("/nodes", response_model=NodeOut, status_code=status.HTTP_201_CREATED)
async def create_node(
body: NodeCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> IdentityNode:
node = IdentityNode(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(node)
@@ -172,8 +188,8 @@ async def list_edges(
@router.post("/edges", response_model=EdgeOut, status_code=status.HTTP_201_CREATED)
async def create_edge(
body: EdgeCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> IdentityEdge:
edge = IdentityEdge(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(edge)
@@ -190,8 +206,8 @@ async def create_edge(
@router.post("/alert-links", response_model=AlertLinkOut, status_code=status.HTTP_201_CREATED)
async def link_alert_to_identity(
body: AlertLinkCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> AlertIdentityLink:
link = AlertIdentityLink(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(link)
diff --git a/services/api/app/api/v1/endpoints/identity_timeline.py b/services/api/app/api/v1/endpoints/identity_timeline.py
index 9fc9a6511..be12bb09e 100644
--- a/services/api/app/api/v1/endpoints/identity_timeline.py
+++ b/services/api/app/api/v1/endpoints/identity_timeline.py
@@ -15,14 +15,14 @@ from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
-from typing import Any, Literal
+from typing import Annotated, Any, Literal
import structlog
-from fastapi import APIRouter, Query, status
+from fastapi import APIRouter, Depends, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import text
-from app.api.v1.deps import AuthUser, DBSession
+from app.api.v1.deps import AuthUser, DBSession, require_permission
router = APIRouter(prefix="/identity-timeline", tags=["identity_timeline"])
log = structlog.get_logger(__name__)
@@ -90,6 +90,15 @@ def _mitre_from_alert(raw: dict[str, Any]) -> str | None:
# ────────────────────────────────────────────────────────────────────────────
+# `alerts:read`, not a write permission: this route persists nothing. It reads
+# `aisoc_alerts` — the only source it actually queries, whatever the summary
+# above still promises — and returns a chronological projection of it, so the
+# honest entitlement is the read permission for the rows it returns.
+#
+# Every human role holds `alerts:read`, deliberately: a timeline is what an
+# analyst and a viewer both legitimately open. The refusal it does make is
+# real, because an API key carries an explicit scope list rather than a role,
+# so a key minted for connector health cannot pull an identity's alert history.
@router.post(
"/build",
response_model=IdentityTimeline,
@@ -99,7 +108,7 @@ def _mitre_from_alert(raw: dict[str, Any]) -> str | None:
async def build_timeline(
body: BuildTimelineRequest,
db: DBSession,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("alerts:read"))],
) -> IdentityTimeline:
now = datetime.now(UTC)
from_ts = body.from_ts or (now - timedelta(hours=72))
diff --git a/services/api/app/api/v1/endpoints/insider_threat.py b/services/api/app/api/v1/endpoints/insider_threat.py
index 871ac8dd8..f755ba6fe 100644
--- a/services/api/app/api/v1/endpoints/insider_threat.py
+++ b/services/api/app/api/v1/endpoints/insider_threat.py
@@ -1,17 +1,32 @@
-"""Insider-threat module endpoints."""
+"""Insider-threat module endpoints.
+
+Authorization
+-------------
+Writes require ``cases:write``. Watchlisting a person, recording an indicator
+against them and acknowledging one are investigative acts about a subject —
+the same class of judgement as working a case, held by every investigating
+role and withheld from ``viewer``. It was ``viewer`` that mattered: a
+read-only account could put an employee on the watchlist with a reason of its
+choosing, or manufacture indicators against one.
+
+``settings:write`` was the alternative and is the wrong shape. It would
+restrict the module to tenant administrators, which takes insider-threat work
+away from the analysts the module exists for, and watchlisting a subject is
+not tenant configuration.
+"""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
-from typing import Any
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.deps import CurrentUser
+from app.api.v1.deps import CurrentUser, require_permission
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile
@@ -128,8 +143,8 @@ async def get_profile(
async def update_watchlist(
profile_id: uuid.UUID,
body: WatchlistUpdate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("cases:write"))],
) -> UserRiskProfile:
profile = await db.get(UserRiskProfile, profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
@@ -171,8 +186,8 @@ async def list_indicators(
@router.post("/indicators", response_model=IndicatorOut, status_code=status.HTTP_201_CREATED)
async def create_indicator(
body: IndicatorCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("cases:write"))],
) -> InsiderIndicator:
profile = await db.get(UserRiskProfile, body.profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
@@ -190,8 +205,8 @@ async def create_indicator(
@router.post("/indicators/{indicator_id}/acknowledge", response_model=IndicatorOut)
async def acknowledge_indicator(
indicator_id: uuid.UUID,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("cases:write"))],
) -> InsiderIndicator:
indicator = await db.get(InsiderIndicator, indicator_id)
if not indicator or indicator.tenant_id != current_user.tenant_id:
@@ -222,8 +237,8 @@ async def list_peer_groups(
@router.post("/peer-groups", response_model=PeerGroupOut, status_code=status.HTTP_201_CREATED)
async def create_peer_group(
body: PeerGroupCreate,
- db: AsyncSession = Depends(get_db),
- current_user: CurrentUser = Depends(get_current_user),
+ db: Annotated[AsyncSession, Depends(get_db)],
+ current_user: Annotated[CurrentUser, Depends(require_permission("cases:write"))],
) -> InsiderPeerGroup:
group = InsiderPeerGroup(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(group)
diff --git a/services/api/tests/test_inventory_route_permissions.py b/services/api/tests/test_inventory_route_permissions.py
new file mode 100644
index 000000000..66914ab62
--- /dev/null
+++ b/services/api/tests/test_inventory_route_permissions.py
@@ -0,0 +1,338 @@
+"""Inventory, entity-graph and insider-threat writes authenticated and stopped.
+
+Sixteen routes across five modules. None of them had a first-party caller, so
+none of them had a reason to be reachable by a session alone, and all of them
+were: a `viewer` could delete the inventory row for a tier-1 host, forge an
+edge between an attacker-controlled account and a service identity, or put a
+named employee on the insider-threat watchlist with a reason of its choosing.
+
+Three permissions, chosen by what the row *is* rather than by which table it
+lands in.
+
+`settings:write` for the inventory and the correlation graph. An asset row is
+CMDB data and the graph's own CMDB import already required exactly this, so
+the two doors onto one class of data now agree. A graph edge is worse than a
+bad row: nothing downstream re-derives it, so a forged one arrives in the next
+investigation as a conclusion.
+
+`cases:write` for insider threat. Watchlisting a subject and recording
+indicators against them is investigative judgement, held by every
+investigating role and withheld from `viewer`. `settings:write` was rejected
+here for the opposite reason it was chosen above — it would take
+insider-threat work away from the analysts the module is for.
+
+`alerts:read` for `POST /identity-timeline/build`, which persists nothing and
+reads only `aisoc_alerts`. Every human role holds it deliberately; the
+refusal it makes is against a narrowly-scoped API key, which carries a scope
+list rather than a role. That case is asserted below rather than assumed,
+because a permission every role holds would otherwise be a fig leaf.
+"""
+
+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 assets, graph, identity_graph, identity_timeline, insider_threat
+from app.db.database import get_db
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")
+ROW = uuid.UUID("22222222-2222-2222-2222-222222222222")
+
+GATED: list[tuple[Any, str, str, str, str, dict[str, Any] | None]] = [
+ (assets, "create_asset", "settings:write", "POST", "/api/v1/assets", {"name": "db-1", "asset_type": "host"}),
+ (assets, "update_asset", "settings:write", "PATCH", f"/api/v1/assets/{ROW}", {"criticality": "low"}),
+ (assets, "delete_asset", "settings:write", "DELETE", f"/api/v1/assets/{ROW}", None),
+ (
+ assets,
+ "create_vulnerability",
+ "settings:write",
+ "POST",
+ "/api/v1/assets/vulnerabilities",
+ {"asset_id": str(ROW), "cve_id": "CVE-2026-0001", "severity": "high"},
+ ),
+ (
+ identity_graph,
+ "create_node",
+ "settings:write",
+ "POST",
+ "/api/v1/identity-graph/nodes",
+ {"node_type": "user", "identifier": "svc_deploy"},
+ ),
+ (
+ identity_graph,
+ "create_edge",
+ "settings:write",
+ "POST",
+ "/api/v1/identity-graph/edges",
+ {"source_id": str(ROW), "target_id": str(ROW), "edge_type": "assumes"},
+ ),
+ (
+ identity_graph,
+ "link_alert_to_identity",
+ "settings:write",
+ "POST",
+ "/api/v1/identity-graph/alert-links",
+ {"alert_id": str(ROW), "node_id": str(ROW)},
+ ),
+ (graph, "upsert_host", "settings:write", "POST", "/api/v1/graph/entities/host", {"host_id": "h1", "hostname": "db-1"}),
+ (graph, "upsert_user", "settings:write", "POST", "/api/v1/graph/entities/user", {"user_id": "u1", "username": "svc_deploy"}),
+ (
+ graph,
+ "upsert_alert_graph",
+ "settings:write",
+ "POST",
+ "/api/v1/graph/entities/alert",
+ {"alert_id": "a1", "title": "t", "severity": "high"},
+ ),
+ (
+ graph,
+ "upsert_case_graph",
+ "settings:write",
+ "POST",
+ "/api/v1/graph/entities/case",
+ {"case_id": "c1", "title": "t", "severity": "high"},
+ ),
+ (
+ insider_threat,
+ "update_watchlist",
+ "cases:write",
+ "PATCH",
+ f"/api/v1/insider-threat/profiles/{ROW}/watchlist",
+ {"is_watchlisted": True, "watchlist_reason": "resignation"},
+ ),
+ (
+ insider_threat,
+ "create_indicator",
+ "cases:write",
+ "POST",
+ "/api/v1/insider-threat/indicators",
+ {"profile_id": str(ROW), "indicator_type": "exfiltration", "severity": "high"},
+ ),
+ (
+ insider_threat,
+ "acknowledge_indicator",
+ "cases:write",
+ "POST",
+ f"/api/v1/insider-threat/indicators/{ROW}/acknowledge",
+ None,
+ ),
+ (insider_threat, "create_peer_group", "cases:write", "POST", "/api/v1/insider-threat/peer-groups", {"name": "engineering"}),
+ (
+ identity_timeline,
+ "build_timeline",
+ "alerts:read",
+ "POST",
+ "/api/v1/identity-timeline/build",
+ {"identity_type": "user", "identity_value": "svc_deploy"},
+ ),
+]
+
+#: A role that holds each permission. `soc_analyst` for `cases:write` on
+#: purpose: it is the role `settings:write` would have locked out of the
+#: insider-threat module.
+HOLDER = {"settings:write": "tenant_admin", "cases:write": "soc_analyst", "alerts:read": "viewer"}
+
+#: Roles that must be refused. `alerts:read` is held by every role in the
+#: static map, so it has no role-based refusal — the API-key case below is its
+#: proof instead, and listing none here says so rather than hiding it.
+REFUSED: dict[str, list[str]] = {
+ "settings:write": ["viewer", "soc_analyst", "soc_lead", "threat_hunter"],
+ "cases:write": ["viewer"],
+ "alerts:read": [],
+}
+
+IDS = [f"{m.__name__.rsplit('.', 1)[-1]}.{h}" for m, h, *_ in GATED]
+
+
+def _user(role: str) -> CurrentUser:
+ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role=role, email=f"{role}@tenant.example")
+
+
+def _api_key(scopes: list[str]) -> CurrentUser:
+ """An API-key principal: explicit scopes, no role-derived permissions."""
+ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role="api_service", email="api-key:aisoc_abc123", scopes=scopes)
+
+
+def _db() -> AsyncMock:
+ 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, principal: CurrentUser, 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: principal
+ app.dependency_overrides[get_db] = lambda: db
+ 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]:
+ 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}")
+
+
+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, _user(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_the_inventory_row_for_a_host(self) -> None:
+ status, committed = _request(assets, _user("viewer"), "DELETE", f"/api/v1/assets/{ROW}", None)
+ assert not committed
+ assert status == 403
+
+ def test_a_viewer_cannot_forge_an_identity_graph_edge(self) -> None:
+ """A forged edge is not a visibly bad row, it is a wrong conclusion."""
+ status, committed = _request(
+ identity_graph,
+ _user("viewer"),
+ "POST",
+ "/api/v1/identity-graph/edges",
+ {"source_id": str(ROW), "target_id": str(ROW), "edge_type": "assumes"},
+ )
+ assert not committed
+ assert status == 403
+
+ def test_a_viewer_cannot_watchlist_an_employee(self) -> None:
+ status, committed = _request(
+ insider_threat,
+ _user("viewer"),
+ "PATCH",
+ f"/api/v1/insider-threat/profiles/{ROW}/watchlist",
+ {"is_watchlisted": True, "watchlist_reason": "fabricated"},
+ )
+ assert not committed
+ assert status == 403
+
+
+class TestTheApiKeyRefusalIsReal:
+ """`alerts:read` is held by every role, so this is where it bites.
+
+ Without this, gating a read-shaped POST on a permission nobody lacks
+ would be a fig leaf that satisfies the ratchet and changes nothing.
+ """
+
+ def test_a_key_scoped_elsewhere_cannot_build_an_identity_timeline(self) -> None:
+ status, _ = _request(
+ identity_timeline,
+ _api_key(["connectors:read"]),
+ "POST",
+ "/api/v1/identity-timeline/build",
+ {"identity_type": "user", "identity_value": "svc_deploy"},
+ )
+ assert status == 403
+
+ def test_a_key_scoped_for_alerts_can(self) -> None:
+ status, _ = _request(
+ identity_timeline,
+ _api_key(["alerts:read"]),
+ "POST",
+ "/api/v1/identity-timeline/build",
+ {"identity_type": "user", "identity_value": "svc_deploy"},
+ )
+ assert status != 403
+
+ def test_a_key_scoped_for_connectors_cannot_write_the_entity_graph(self) -> None:
+ status, _ = _request(
+ graph, _api_key(["connectors:read"]), "POST", "/api/v1/graph/entities/host", {"host_id": "h1", "hostname": "db-1"}
+ )
+ assert status == 403
+
+ def test_the_integration_key_these_routes_exist_for_still_works(self) -> None:
+ """They have no first-party caller; a scoped key is the real client."""
+ status, _ = _request(
+ graph, _api_key(["settings:write"]), "POST", "/api/v1/graph/entities/host", {"host_id": "h1", "hostname": "db-1"}
+ )
+ assert status != 403
+
+
+class TestEntitledCallersStillWork:
+ @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, _user(HOLDER[permission]), method, path, payload)
+ assert status != 403, f"{HOLDER[permission]} holds {permission} but {handler} answered 403"
+
+ @pytest.mark.parametrize("role", ["soc_analyst", "soc_lead", "threat_hunter"])
+ def test_every_investigating_role_may_still_work_insider_threat(self, role: str) -> None:
+ """The outage `settings:write` would have caused on this module."""
+ status, _ = _request(
+ insider_threat,
+ _user(role),
+ "POST",
+ "/api/v1/insider-threat/indicators",
+ {"profile_id": str(ROW), "indicator_type": "exfiltration", "severity": "high"},
+ )
+ assert status != 403
+
+ def test_a_viewer_may_still_read_the_asset_inventory(self) -> None:
+ status, _ = _request(assets, _user("viewer"), "GET", "/api/v1/assets", 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",
+ [assets, identity_graph, identity_timeline, insider_threat, graph],
+ ids=lambda m: m.__name__.rsplit(".", 1)[-1],
+ )
+ def test_no_state_changing_route_in_these_modules_is_unguarded(self, module: Any) -> None:
+ 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}"