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 posture, compliance, reporting and platform config (#1056)

Beenu Arora236308b2620e
diff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.py
index 8335bc7fc..4cd600885 100644
--- a/scripts/check_route_authz.py
+++ b/scripts/check_route_authz.py
@@ -107,7 +107,20 @@ AUTHZ_CALLS = frozenset(
#: 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).
+#: (a read-shaped POST over the only table it queries), then 45 once posture,
+#: EASM scanning, deployment config and knowledge-base curation took
+#: `settings:write` / `settings:read`, report templates and compliance evidence
+#: collection took `reports:write`, and evidence *review* took `settings:write`
+#: — deliberately a different permission from collection, so a `soc_lead`
+#: cannot accept the evidence it produced.
+#:
+#: `POST /kb/query` is left in this count on purpose. The vocabulary has no
+#: knowledge-base permission: every candidate is held by every role including
+#: machine keys, or is admin-only and would take the runbooks away from the
+#: analysts who need them mid-incident. Which entitlement governs reading the
+#: library, and whether LLM synthesis needs a stronger one than retrieval, is
+#: a product decision; `test_platform_route_permissions.py` pins it ungated so
+#: changing that takes a decision rather than a drive-by edit.
#:
#: Four routes under `/mssp/organizations` remain in this count and are not
#: debt: they authorize through `_admin_scope`, an organisation owner/admin
@@ -115,7 +128,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 = 61
+MAX_UNAUTHORIZED = 45
def _authorizing_names(tree: ast.Module) -> set[str]:
diff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.py
index 1d9198320..d36d0448d 100644
--- a/services/api/app/api/v1/endpoints/compliance.py
+++ b/services/api/app/api/v1/endpoints/compliance.py
@@ -13,6 +13,31 @@ Endpoints
* ``GET /compliance/evidence/{id}`` Get single evidence item.
* ``POST /compliance/evidence/{id}/review`` Accept or reject an evidence item.
* ``GET /compliance/report`` Generate a compliance posture report.
+
+Authorization
+-------------
+Collecting evidence requires ``reports:write`` — an evidence item is an
+audit-grade artefact, and this is the permission the platform already uses
+for producing those. Reviewing one requires ``settings:write``, which is
+deliberately a *different* permission rather than the same one.
+
+Two permissions because an evidence item's ``status`` is the assertion an
+auditor relies on, and one permission for both would let whoever collected an
+item accept it. Splitting them gives a role-level separation: a ``soc_lead``
+holds ``reports:write`` and can collect but not accept; accepting needs a
+tenant administrator.
+
+That is a coarser control than the person-level separation of duties
+``services/actions`` enforces on response approvals, and the reason is a
+schema fact rather than a choice: migration 013's
+``aisoc_compliance_evidence`` records ``reviewed_by`` and no collector at all,
+so there is nobody to compare an approver against. Adding a ``collected_by``
+column is the prerequisite for the stronger check and is not done here — a
+separation of duties cannot be evaluated against nobody, and pretending
+otherwise would be worse than the coarse control.
+
+Before either, every route here was reachable by ``viewer``: a read-only
+account could append to the hash chain and then accept its own entries.
"""
from __future__ import annotations
@@ -22,13 +47,13 @@ import json
import logging
import uuid
from datetime import UTC, datetime
-from typing import Any, Literal
+from typing import Annotated, Any, Literal
-from fastapi import APIRouter, HTTPException, Query, status
+from fastapi import APIRouter, Depends, HTTPException, 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
logger = logging.getLogger(__name__)
@@ -229,7 +254,9 @@ async def list_framework_controls(framework_id: str) -> ControlsResponse:
status_code=status.HTTP_202_ACCEPTED,
summary="Trigger evidence collection job",
)
-async def trigger_evidence_collection(body: CollectJobRequest, user: AuthUser) -> CollectJobResponse:
+async def trigger_evidence_collection(
+ body: CollectJobRequest, user: Annotated[AuthUser, Depends(require_permission("reports:write"))]
+) -> CollectJobResponse:
if body.framework not in FRAMEWORKS:
raise HTTPException(status_code=404, detail=f"Framework '{body.framework}' not found.")
return CollectJobResponse(
@@ -242,7 +269,9 @@ async def trigger_evidence_collection(body: CollectJobRequest, user: AuthUser) -
@router.post("/evidence", response_model=EvidenceResponse, status_code=status.HTTP_201_CREATED, summary="Collect evidence item")
-async def collect_evidence(body: CollectEvidenceRequest, db: DBSession, user: AuthUser) -> EvidenceResponse:
+async def collect_evidence(
+ body: CollectEvidenceRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("reports:write"))]
+) -> EvidenceResponse:
prev_hash = await _latest_hash(db, body.framework, user.tenant_id)
new_hash = _compute_hash(prev_hash, body.summary, body.raw_payload)
now = datetime.now(UTC)
@@ -334,7 +363,12 @@ async def get_evidence(evidence_id: uuid.UUID, db: DBSession, user: AuthUser) ->
@router.post("/evidence/{evidence_id}/review", response_model=EvidenceResponse, summary="Accept or reject evidence")
-async def review_evidence(evidence_id: uuid.UUID, body: ReviewEvidenceRequest, db: DBSession, user: AuthUser) -> EvidenceResponse:
+async def review_evidence(
+ evidence_id: uuid.UUID,
+ body: ReviewEvidenceRequest,
+ db: DBSession,
+ user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+) -> EvidenceResponse:
now = datetime.now(UTC)
q = text("""
UPDATE aisoc_compliance_evidence
diff --git a/services/api/app/api/v1/endpoints/deployment.py b/services/api/app/api/v1/endpoints/deployment.py
index 8e93c856e..275abfff7 100644
--- a/services/api/app/api/v1/endpoints/deployment.py
+++ b/services/api/app/api/v1/endpoints/deployment.py
@@ -1,13 +1,24 @@
-"""Air-gap deployment configuration endpoints."""
+"""Air-gap deployment configuration endpoints.
+
+Authorization
+-------------
+Both writes require ``settings:write``, which is what they are: ``PUT /config``
+edits the deployment's own configuration and ``POST /airgap/bundle`` triggers
+an offline update bundle. Nothing about either was ever analyst work, and the
+config route mutates process-wide state — a module-level ``_config`` — so on
+the pre-fix tree one ``viewer`` request changed the answer every other caller
+got.
+"""
import uuid
from datetime import UTC, datetime
from enum import Enum
+from typing import Annotated
-from fastapi import APIRouter, HTTPException, status
+from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
-from app.api.v1.deps import AuthUser
+from app.api.v1.deps import AuthUser, require_permission
router = APIRouter(prefix="/deployment", tags=["Deployment"])
@@ -95,7 +106,9 @@ async def get_deployment_config(user: AuthUser) -> DeploymentConfig:
@router.put("/config", response_model=DeploymentConfig)
-async def update_deployment_config(body: DeploymentConfigUpdate, user: AuthUser) -> DeploymentConfig:
+async def update_deployment_config(
+ body: DeploymentConfigUpdate, user: Annotated[AuthUser, Depends(require_permission("settings:write"))]
+) -> DeploymentConfig:
"""Update deployment configuration fields."""
global _config
@@ -169,7 +182,7 @@ async def get_airgap_status(user: AuthUser) -> AirgapStatus:
@router.post("/airgap/bundle", response_model=BundleJob, status_code=status.HTTP_202_ACCEPTED)
-async def create_airgap_bundle(user: AuthUser) -> BundleJob:
+async def create_airgap_bundle(user: Annotated[AuthUser, Depends(require_permission("settings:write"))]) -> BundleJob:
"""Trigger creation of an offline update bundle for air-gapped deployments."""
return BundleJob(
job_id=str(uuid.uuid4()),
diff --git a/services/api/app/api/v1/endpoints/easm.py b/services/api/app/api/v1/endpoints/easm.py
index 4b1f98074..e955d6934 100644
--- a/services/api/app/api/v1/endpoints/easm.py
+++ b/services/api/app/api/v1/endpoints/easm.py
@@ -1,9 +1,20 @@
-"""EASM (External Attack Surface Management) endpoints (Tier 3.6)."""
+"""EASM (External Attack Surface Management) endpoints (Tier 3.6).
+
+Authorization
+-------------
+``POST /scan`` requires ``settings:write``. ``scoped_tenant_or_403`` already
+intersected the requested tenant with the caller's scope, but scoping answers
+*whose* estate, not *whether this caller may probe it* — and this route runs
+passive reconnaissance connectors and, when enabled, an **active TCP connect
+probe** against hosts the tenant claims to own. Launching outbound scanning
+traffic is an administrative act, and it was reachable by any authenticated
+session including ``viewer``.
+"""
from __future__ import annotations
import logging
-from typing import Any
+from typing import Annotated, Any
from uuid import UUID
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
@@ -11,7 +22,7 @@ from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.deps import CurrentUser, get_current_user
+from app.api.v1.deps import CurrentUser, get_current_user, require_permission
from app.core.config import get_settings
from app.db.database import get_db
from app.models.easm import ExternalAsset, ExternalAssetDrift, ExternalAssetType
@@ -59,8 +70,8 @@ async def _run_scan_job(
async def trigger_easm_scan(
body: ScanRequest,
background_tasks: BackgroundTasks,
- 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"))],
) -> dict[str, Any]:
"""
Trigger an EASM discovery scan for a tenant (Tier 3.6).
diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.py
index f008fa122..a5eddba84 100644
--- a/services/api/app/api/v1/endpoints/knowledge_base.py
+++ b/services/api/app/api/v1/endpoints/knowledge_base.py
@@ -13,6 +13,29 @@ Endpoints
* ``POST /kb/query`` Semantic/keyword search + optional LLM synthesis.
* ``GET /kb/runbooks/for-triage`` Internal: retrieval for the agents service,
with a point-in-time cutoff. Gap-closure Phase 6.3.
+
+Authorization
+-------------
+``POST /ingest`` and ``DELETE /documents/{id}`` require ``settings:write``.
+The knowledge base is the tenant's operational content of record — runbooks,
+policies, SOPs — and the delete is wider than its path suggests: it removes
+*every chunk sharing the document's title*, tenant-wide, so one request from a
+``viewer`` erased a runbook for everybody. It is also what the agents service
+retrieves during triage, so a document planted here is a document the model
+is told to follow.
+
+``POST /query`` is deliberately **left ungated** and counted in
+``scripts/check_route_authz.py``'s ledger. Searching the runbook library is
+something every role should be able to do, and the vocabulary has no
+knowledge-base permission: every candidate is either held by every role
+including machine keys (``cases:read``, ``reports:read``) or restricted to
+tenant administrators (``settings:read``), which would take the runbooks away
+from the analysts who need them mid-incident. Choosing one on the strength of
+its role list rather than what the route does would be reverse-engineering a
+permission from the answer. The open questions are whether reading the
+library is an entitlement at all and whether LLM synthesis — which spends the
+tenant's budget — needs a stronger one than retrieval; both are product
+decisions, not gaps to be papered over.
"""
from __future__ import annotations
@@ -23,11 +46,11 @@ import uuid
from datetime import UTC, datetime
from typing import Annotated, Any, Literal
-from fastapi import APIRouter, Header, HTTPException, Query, status
+from fastapi import APIRouter, Depends, Header, HTTPException, 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
from app.api.v1.endpoints.alert_writeback import service_token_valid
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
from app.db.rls import set_rls_context
@@ -156,7 +179,9 @@ async def _synthesise(question: str, chunks: list[KBChunk]) -> str | None:
@router.post(
"/ingest", response_model=list[KBDocResponse], status_code=status.HTTP_201_CREATED, summary="Ingest document into knowledge base"
)
-async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDocResponse]:
+async def ingest(
+ body: IngestRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("settings:write"))]
+) -> list[KBDocResponse]:
chunks = chunk_text(body.content)
now = datetime.now(UTC)
rows = []
@@ -225,7 +250,9 @@ async def get_document(doc_id: uuid.UUID, db: DBSession, user: AuthUser) -> KBDo
@router.delete("/documents/{doc_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None, summary="Remove KB document")
-async def delete_document(doc_id: uuid.UUID, db: DBSession, user: AuthUser) -> None:
+async def delete_document(
+ doc_id: uuid.UUID, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("settings:write"))]
+) -> None:
existing = (
await db.execute(
text("SELECT title FROM aisoc_kb_documents WHERE id = :id AND tenant_id = :tenant_id").bindparams(
diff --git a/services/api/app/api/v1/endpoints/posture.py b/services/api/app/api/v1/endpoints/posture.py
index 5b3758c99..963950a65 100644
--- a/services/api/app/api/v1/endpoints/posture.py
+++ b/services/api/app/api/v1/endpoints/posture.py
@@ -1,17 +1,36 @@
-"""Cloud Security Posture Management (CSPM/KSPM) endpoints."""
+"""Cloud Security Posture Management (CSPM/KSPM) endpoints.
+
+Authorization
+-------------
+Posture is cloud configuration hygiene, so the writes take ``settings:write``
+and the stateless previews take ``settings:read``.
+
+``suppress_finding`` is the one that matters. It writes ``status`` =
+``suppressed`` with a reason and stands the finding down, which is a policy
+exception over the tenant's own cloud estate — the CSPM equivalent of the
+pre-approval GHSA-wj5c-88hg-5926 let a ``viewer`` install. Before this, a
+read-only account could suppress every finding in the tenant one id at a
+time, and the dashboard would go green.
+
+``cspm_scan`` and ``destination_preview`` persist nothing: one evaluates a
+resource snapshot supplied in the request, the other renders the payload a
+destination would send. ``settings:read`` rather than the write because
+nothing changes, and rather than nothing because they are still features of
+an administrative surface that an API key should have to be scoped for.
+"""
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.posture import PostureFinding, PostureScanRun
@@ -124,8 +143,8 @@ async def list_findings(
@router.post("/findings", response_model=FindingOut, status_code=status.HTTP_201_CREATED)
async def ingest_finding(
body: FindingCreate,
- 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"))],
) -> PostureFinding:
finding = PostureFinding(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(finding)
@@ -150,8 +169,8 @@ async def get_finding(
async def suppress_finding(
finding_id: uuid.UUID,
body: SuppressRequest,
- 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"))],
) -> PostureFinding:
f = await db.get(PostureFinding, finding_id)
if not f or f.tenant_id != current_user.tenant_id:
@@ -168,8 +187,8 @@ async def suppress_finding(
@router.post("/findings/{finding_id}/resolve", response_model=FindingOut)
async def resolve_finding(
finding_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"))],
) -> PostureFinding:
f = await db.get(PostureFinding, finding_id)
if not f or f.tenant_id != current_user.tenant_id:
@@ -246,7 +265,7 @@ class CspmScanResponse(BaseModel):
@router.post("/scan", response_model=CspmScanResponse)
async def cspm_scan(
body: CspmScanRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:read"))],
) -> CspmScanResponse:
"""Agentless CSPM MVP (W6.2): evaluate a cloud-resource snapshot against the
misconfiguration checks, returning findings + a severity summary + the
@@ -269,7 +288,7 @@ class DestinationPreviewRequest(BaseModel):
@router.post("/destinations/preview")
async def destination_preview(
body: DestinationPreviewRequest,
- current_user: CurrentUser = Depends(get_current_user),
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:read"))],
) -> dict[str, Any]:
"""Preview the exact payload a destination would send (W6.3) — no send."""
if body.kind == "opsgenie":
diff --git a/services/api/app/api/v1/endpoints/reports.py b/services/api/app/api/v1/endpoints/reports.py
index 8c9d547b0..75932bcb4 100644
--- a/services/api/app/api/v1/endpoints/reports.py
+++ b/services/api/app/api/v1/endpoints/reports.py
@@ -1,5 +1,14 @@
"""Auto-generated board / executive report endpoints.
+Authorization
+-------------
+Templates and generation require ``reports:write``, held by ``tenant_admin``
+and ``soc_lead``. It is the permission named for exactly this act, it already
+existed, and it was already withheld from ``viewer`` — which could otherwise
+delete a board template or queue a report addressed to a recipient list of
+its choosing, since ``generate_report`` takes ``recipients`` from the body
+and persists it as ``delivered_to``.
+
Author: Beenu <[email protected]>
"""
@@ -7,7 +16,7 @@ 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 fastapi.responses import HTMLResponse, Response
@@ -15,7 +24,7 @@ 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.report import ReportArtefact, ReportTemplate
@@ -101,8 +110,8 @@ async def list_templates(
@router.post("/templates", response_model=TemplateOut, status_code=status.HTTP_201_CREATED)
async def create_template(
body: TemplateCreate,
- 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("reports:write"))],
) -> ReportTemplate:
template = ReportTemplate(
**body.model_dump(),
@@ -130,8 +139,8 @@ async def get_template(
@router.delete("/templates/{template_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_template(
template_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("reports:write"))],
) -> None:
tmpl = await db.get(ReportTemplate, template_id)
if not tmpl or tmpl.tenant_id != current_user.tenant_id:
@@ -167,8 +176,8 @@ async def list_artefacts(
@router.post("/generate", response_model=ArtefactOut, status_code=status.HTTP_202_ACCEPTED)
async def generate_report(
body: GenerateRequest,
- 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("reports:write"))],
) -> ReportArtefact:
"""Enqueue a report generation job. Returns the artefact record immediately with status='pending'."""
artefact = ReportArtefact(
diff --git a/services/api/tests/test_platform_route_permissions.py b/services/api/tests/test_platform_route_permissions.py
new file mode 100644
index 000000000..5a4ac08b5
--- /dev/null
+++ b/services/api/tests/test_platform_route_permissions.py
@@ -0,0 +1,314 @@
+"""Posture, compliance, reporting and platform-config writes authorize now.
+
+Sixteen routes across six modules resolved a session and then checked no
+entitlement. The two worth naming:
+
+`POST /posture/findings/{id}/suppress` stands a cloud misconfiguration down
+with a reason of the caller's choosing. It is the CSPM equivalent of the
+pre-approval GHSA-wj5c-88hg-5926 let a `viewer` install: a read-only account
+could suppress every finding in the tenant one id at a time and the dashboard
+would go green.
+
+`POST /compliance/evidence/{id}/review` sets the `status` an auditor relies
+on, on a hash-chained evidence item. Ungated, a read-only account could append
+to the chain and accept its own entries.
+
+Compliance takes two different permissions on purpose: `reports:write` to
+collect, `settings:write` to review, so a `soc_lead` can produce evidence and
+cannot accept it. That is a role-level separation rather than the person-level
+separation `services/actions` enforces on response approvals, and the reason
+is a schema fact — migration 013's `aisoc_compliance_evidence` records
+`reviewed_by` and no collector, so there is nobody to compare an approver
+against. `test_the_role_level_separation_is_real` asserts the split; the
+person-level check is not claimed anywhere.
+
+`POST /kb/query` is deliberately left ungated and
+`test_kb_query_is_deliberately_not_gated` records that as an assertion rather
+than a comment, so flipping it needs a decision and an edit 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 compliance, deployment, easm, knowledge_base, posture, reports
+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]] = [
+ (
+ posture,
+ "ingest_finding",
+ "settings:write",
+ "POST",
+ "/api/v1/posture/findings",
+ {"provider": "aws", "resource_id": "s3://b", "rule_id": "S3-1", "severity": "high", "title": "public bucket"},
+ ),
+ (posture, "suppress_finding", "settings:write", "POST", f"/api/v1/posture/findings/{ROW}/suppress", {"reason": "accepted"}),
+ (posture, "resolve_finding", "settings:write", "POST", f"/api/v1/posture/findings/{ROW}/resolve", None),
+ (posture, "cspm_scan", "settings:read", "POST", "/api/v1/posture/scan", {"resources": []}),
+ (
+ posture,
+ "destination_preview",
+ "settings:read",
+ "POST",
+ "/api/v1/posture/destinations/preview",
+ {"kind": "webhook", "alert": {"title": "t"}},
+ ),
+ (
+ compliance,
+ "trigger_evidence_collection",
+ "reports:write",
+ "POST",
+ "/api/v1/compliance/evidence/collect",
+ {"framework": "SOC2", "scope": "all"},
+ ),
+ (
+ compliance,
+ "collect_evidence",
+ "reports:write",
+ "POST",
+ "/api/v1/compliance/evidence",
+ {"framework": "SOC2", "control_id": "CC6.1", "summary": "s", "evidence_kind": "attestation"},
+ ),
+ (
+ compliance,
+ "review_evidence",
+ "settings:write",
+ "POST",
+ f"/api/v1/compliance/evidence/{ROW}/review",
+ {"decision": "accepted"},
+ ),
+ (easm, "trigger_easm_scan", "settings:write", "POST", "/api/v1/easm/scan", {"tenant_id": str(TENANT)}),
+ (deployment, "update_deployment_config", "settings:write", "PUT", "/api/v1/deployment/config", {"airgapped": True}),
+ (deployment, "create_airgap_bundle", "settings:write", "POST", "/api/v1/deployment/airgap/bundle", None),
+ (reports, "create_template", "reports:write", "POST", "/api/v1/reports/templates", {"name": "board", "report_type": "executive"}),
+ (reports, "delete_template", "reports:write", "DELETE", f"/api/v1/reports/templates/{ROW}", None),
+ (
+ reports,
+ "generate_report",
+ "reports:write",
+ "POST",
+ "/api/v1/reports/generate",
+ {"report_type": "executive", "title": "Q3", "period_start": "2026-07-01T00:00:00Z", "period_end": "2026-09-30T00:00:00Z"},
+ ),
+ (
+ knowledge_base,
+ "ingest",
+ "settings:write",
+ "POST",
+ "/api/v1/kb/ingest",
+ {"title": "runbook", "content": "steps", "doc_kind": "runbook"},
+ ),
+ (knowledge_base, "delete_document", "settings:write", "DELETE", f"/api/v1/kb/documents/{ROW}", None),
+]
+
+HOLDER = {"settings:write": "tenant_admin", "settings:read": "tenant_admin", "reports:write": "soc_lead"}
+
+REFUSED = {
+ "settings:write": ["viewer", "soc_analyst", "soc_lead", "threat_hunter"],
+ "settings:read": ["viewer", "soc_analyst", "soc_lead", "threat_hunter"],
+ "reports:write": ["viewer", "soc_analyst", "threat_hunter"],
+}
+
+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 _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, 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
+ 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, 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_suppress_a_cloud_misconfiguration(self) -> None:
+ """Suppressing every finding one id at a time turns the dashboard green."""
+ status, committed = _request(posture, "viewer", "POST", f"/api/v1/posture/findings/{ROW}/suppress", {"reason": "accepted"})
+ assert not committed
+ assert status == 403
+
+ def test_a_viewer_cannot_accept_compliance_evidence(self) -> None:
+ status, committed = _request(compliance, "viewer", "POST", f"/api/v1/compliance/evidence/{ROW}/review", {"decision": "accepted"})
+ assert not committed
+ assert status == 403
+
+ def test_a_viewer_cannot_launch_an_external_scan(self) -> None:
+ """`POST /easm/scan` runs an active TCP connect probe when enabled."""
+ status, _ = _request(easm, "viewer", "POST", "/api/v1/easm/scan", {"tenant_id": str(TENANT)})
+ assert status == 403
+
+ def test_a_viewer_cannot_erase_a_runbook_for_the_whole_tenant(self) -> None:
+ """The delete removes every chunk sharing the document's title."""
+ status, committed = _request(knowledge_base, "viewer", "DELETE", f"/api/v1/kb/documents/{ROW}", None)
+ assert not committed
+ assert status == 403
+
+ def test_a_viewer_cannot_change_the_deployment_config(self) -> None:
+ """`_config` is module-level, so one request changed it for everybody."""
+ status, _ = _request(deployment, "viewer", "PUT", "/api/v1/deployment/config", {"airgapped": True})
+ assert status == 403
+
+
+class TestTheRoleLevelSeparationIsReal:
+ """Collecting evidence and accepting it are two different permissions.
+
+ Asserted rather than described, because one permission for both would let
+ whoever produced an evidence item sign it off, and that is the whole point
+ of the artefact.
+ """
+
+ def test_a_lead_may_collect_evidence(self) -> None:
+ status, _ = _request(
+ compliance,
+ "soc_lead",
+ "POST",
+ "/api/v1/compliance/evidence",
+ {"framework": "SOC2", "control_id": "CC6.1", "summary": "s", "evidence_kind": "attestation"},
+ )
+ assert status != 403
+
+ def test_the_same_lead_may_not_accept_it(self) -> None:
+ status, committed = _request(compliance, "soc_lead", "POST", f"/api/v1/compliance/evidence/{ROW}/review", {"decision": "accepted"})
+ assert not committed
+ assert status == 403
+
+ def test_collection_and_review_do_not_share_a_permission(self) -> None:
+ collect = _permissions_on(_route_for(compliance, "collect_evidence"))
+ review = _permissions_on(_route_for(compliance, "review_evidence"))
+ assert collect and review
+ assert set(collect).isdisjoint(review), f"collect {collect} and review {review} share a permission"
+
+
+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, HOLDER[permission], method, path, payload)
+ assert status != 403, f"{HOLDER[permission]} holds {permission} but {handler} answered 403"
+
+ def test_a_lead_may_still_generate_a_board_report(self) -> None:
+ """`reports:write` is held by `soc_lead`, not admins only."""
+ status, _ = _request(
+ reports,
+ "soc_lead",
+ "POST",
+ "/api/v1/reports/generate",
+ {"report_type": "executive", "title": "Q3", "period_start": "2026-07-01T00:00:00Z", "period_end": "2026-09-30T00:00:00Z"},
+ )
+ assert status != 403
+
+ def test_a_viewer_may_still_read_posture_findings(self) -> None:
+ status, _ = _request(posture, "viewer", "GET", "/api/v1/posture/findings", 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", [posture, compliance, easm, deployment, reports], 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}"
+
+ def test_kb_query_is_deliberately_not_gated(self) -> None:
+ """The one route in this change left alone, pinned so it stays a decision.
+
+ The vocabulary has no knowledge-base permission: every candidate is
+ either held by every role including machine keys (`cases:read`,
+ `reports:read`) or restricted to tenant administrators
+ (`settings:read`), which would take the runbooks away from the
+ analysts who need them mid-incident. Picking one on the strength of
+ its role list rather than what the route does would be
+ reverse-engineering a permission from the answer.
+
+ If somebody gates it, this fails and they write down which entitlement
+ governs reading the library — and whether LLM synthesis needs a
+ stronger one than retrieval. The rest of `knowledge_base.py` is gated,
+ so a *new* ungated route there still fails the check below.
+ """
+ assert _permissions_on(_route_for(knowledge_base, "query_kb")) == []
+
+ def test_the_rest_of_the_knowledge_base_is_gated(self) -> None:
+ unguarded = {
+ getattr(r.endpoint, "__name__", "?")
+ for r in knowledge_base.router.routes
+ if r.methods & {"POST", "PUT", "PATCH", "DELETE"} and not _permissions_on(r)
+ }
+ assert unguarded == {"query_kb"}, f"unexpected ungated knowledge-base routes: {unguarded - {'query_kb'}}"