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 content publishing, installation and analyst feedback (#1057)

Beenu Arorab937278ddeb1
diff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.py
index 4cd600885..a2adc72e4 100644
--- a/scripts/check_route_authz.py
+++ b/scripts/check_route_authz.py
@@ -122,13 +122,26 @@ AUTHZ_CALLS = frozenset(
#: a product decision; `test_platform_route_permissions.py` pins it ungated so
#: changing that takes a decision rather than a drive-by edit.
#:
+#: 28 once community publishing/installation took the permission that governs
+#: authoring each content type locally (`plugins:admin`, `rules:write`,
+#: `playbooks:write`), marketplace install/uninstall took `settings:write`,
+#: STIX publication took `threat_intel:write`, alert-disposition feedback took
+#: `alerts:write` and phishing submission took `cases:write`.
+#:
+#: `POST /community/plugins/{id}/rate` is left in the count for the same kind
+#: of reason as `/kb/query`: every authenticated principal is a legitimate
+#: rater, there is no permission for holding an opinion, and requiring an
+#: administrative one would mean only administrators may rate. The integrity
+#: question there is one-vote-per-user, which the in-memory counter cannot
+#: express — storage and product, not authorization.
+#:
#: Four routes under `/mssp/organizations` remain in this count and are not
#: debt: they authorize through `_admin_scope`, an organisation owner/admin
#: check, which is the right vocabulary for a portfolio-scoped act and is not
#: 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 = 45
+MAX_UNAUTHORIZED = 28
def _authorizing_names(tree: ast.Module) -> set[str]:
diff --git a/services/api/app/api/v1/endpoints/community.py b/services/api/app/api/v1/endpoints/community.py
index 509307911..1ed94d99e 100644
--- a/services/api/app/api/v1/endpoints/community.py
+++ b/services/api/app/api/v1/endpoints/community.py
@@ -17,6 +17,36 @@ POST /community/playbooks/submit – submit a playbook
GET /community/playbooks – browse community playbooks
POST /community/playbooks/{id}/install – install playbook
PUT /community/playbooks/{id}/curate – admin: approve/reject playbook
+
+Authorization
+-------------
+Every write here either speaks publicly on the tenant's behalf or brings
+third-party content into it, and none of them checked anything: the review
+and curate routes required `plugins:admin` / `playbooks:admin` while the
+routes that *submitted* and *installed* required only a session. A `viewer`
+could publish a signed plugin as the tenant, and install one.
+
+The mapping is by content type, matching the permission that governs
+authoring that type locally — you should not be able to publish or install
+what you could not have written:
+
+* `plugins:admin` for the publisher keys and for plugin publish/install. A
+ plugin is code: installing one is an execution surface, and publishing one
+ is the tenant signing something. The keys take the same permission because
+ a signing key exists only in order to publish, so leaving that surface open
+ let an unentitled caller pre-stage a publisher identity for the tenant.
+* `rules:write` for detection publish/install — the same permission that
+ authors a detection rule.
+* `playbooks:write` for playbook submit/install — the same permission that
+ authors a playbook. Installing one creates executable automation.
+
+`POST /plugins/{id}/rate` is deliberately **left ungated** and counted in
+`scripts/check_route_authz.py`'s ledger. It is the one act here where every
+authenticated principal is a legitimate actor, the vocabulary has no
+permission for expressing an opinion, and requiring an administrative one
+would mean only administrators may rate. The real integrity question is
+one-vote-per-user, which the in-memory counter cannot express at all — that
+is a storage and product decision, not an authorization gap.
"""
from __future__ import annotations
@@ -146,7 +176,7 @@ class PublisherKeyOut(BaseModel):
@router.post("/publishers/keys", response_model=PublisherKeyOut, status_code=201)
async def add_publisher_key(
body: PublisherKeyIn,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("plugins:admin"))],
db: TenantDBSession,
) -> PublisherKeyOut:
"""Register a public key you will sign submissions with.
@@ -183,7 +213,7 @@ async def list_publisher_keys(
@router.delete("/publishers/keys/{fingerprint}", status_code=204)
async def revoke_publisher_key(
fingerprint: str,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("plugins:admin"))],
db: TenantDBSession,
) -> None:
"""Revoke a key.
@@ -210,7 +240,7 @@ async def revoke_publisher_key(
@router.post("/plugins/publish", status_code=201)
async def publish_plugin(
request: Request,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("plugins:admin"))],
db: TenantDBSession,
) -> dict[str, Any]:
"""Submit a signed plugin tarball for community review."""
@@ -332,7 +362,7 @@ async def get_community_plugin(plugin_id: str) -> CommunityPluginOut:
@router.post("/plugins/{plugin_id}/install")
async def install_community_plugin(
plugin_id: str,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("plugins:admin"))],
) -> dict[str, str]:
"""Install a community plugin to the current instance."""
p = _community_plugins.get(plugin_id)
@@ -392,7 +422,7 @@ async def review_community_plugin(
@router.post("/detections/publish", status_code=201)
async def publish_detection(
content: str = Body(..., media_type="text/plain"),
- current_user: AuthUser = None, # type: ignore[assignment]
+ current_user: Annotated[AuthUser, Depends(require_permission("rules:write"))] = None, # type: ignore[assignment]
) -> dict[str, Any]:
"""Submit a Sigma detection rule for community review."""
import yaml as _yaml
@@ -488,7 +518,7 @@ async def get_community_detection(detection_id: str) -> dict[str, Any]:
@router.post("/detections/{detection_id}/install")
async def install_community_detection(
detection_id: str,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("rules:write"))],
) -> dict[str, str]:
"""Install a community detection rule to the tenant."""
d = _community_detections.get(detection_id)
@@ -504,7 +534,7 @@ async def install_community_detection(
@router.post("/playbooks/submit", status_code=201)
async def submit_playbook(
definition: dict[str, Any] = Body(...),
- current_user: AuthUser = None, # type: ignore[assignment]
+ current_user: Annotated[AuthUser, Depends(require_permission("playbooks:write"))] = None, # type: ignore[assignment]
) -> dict[str, Any]:
"""Submit a community playbook."""
name = definition.get("name", "")
@@ -566,7 +596,7 @@ async def list_community_playbooks(
@router.post("/playbooks/{playbook_id}/install")
async def install_community_playbook(
playbook_id: str,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("playbooks:write"))],
) -> dict[str, str]:
"""Install a community playbook to the tenant."""
p = _community_playbooks.get(playbook_id)
diff --git a/services/api/app/api/v1/endpoints/feedback.py b/services/api/app/api/v1/endpoints/feedback.py
index c1b7377d1..22c132ccd 100644
--- a/services/api/app/api/v1/endpoints/feedback.py
+++ b/services/api/app/api/v1/endpoints/feedback.py
@@ -32,6 +32,23 @@ table was never noticed. Both ends are wired here — the optional
``reason_code`` on an override writes, and ``/context-statements`` reads —
because wiring only the read would have been a query against a table nothing
populates, which is the same defect wearing a different hat.
+
+Authorization
+-------------
+Both writes require ``alerts:write``. They change an alert's ``disposition``
+— one alert on an override, a confirmed batch on a re-disposition — which is
+the same act ``alerts.py`` already gates on ``alerts:write``, and the two
+doors onto that column now agree.
+
+It matters more here than on a single alert. An override is persisted into
+institutional memory as a per-signature prior, and a *trusted* benign prior
+auto-resolves matching repeat alerts without re-triage. So an ungated
+override was not one wrong verdict; it was a durable instruction to the
+platform to stop looking, writable by a ``viewer``.
+
+``threat_hunter`` holds no ``alerts:write`` and is therefore refused, which
+is consistent with the role's documented posture of handing off rather than
+dispositioning.
"""
from __future__ import annotations
@@ -45,7 +62,7 @@ from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import and_, func, select, text, update
-from app.api.v1.deps import AuthUser, CurrentUser, DBSession
+from app.api.v1.deps import AuthUser, CurrentUser, DBSession, require_permission
from app.api.v1.endpoints.alert_writeback import optional_user, service_token_valid
from app.db.rls import set_rls_context
from app.models.alert import Alert
@@ -180,7 +197,7 @@ class AlertOverrideResponse(BaseModel):
@router.post("/alert-override", response_model=AlertOverrideResponse)
async def submit_alert_override(
payload: AlertOverrideRequest,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("alerts:write"))],
db: DBSession,
) -> AlertOverrideResponse:
"""Record an analyst verdict correction on an alert and surface
@@ -322,7 +339,7 @@ class RedispositionApplyResponse(BaseModel):
@router.post("/redisposition/apply", response_model=RedispositionApplyResponse)
async def apply_redisposition_endpoint(
payload: RedispositionApplyRequest,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("alerts:write"))],
db: DBSession,
) -> RedispositionApplyResponse:
"""Bulk-update the disposition on past alerts the analyst confirmed.
diff --git a/services/api/app/api/v1/endpoints/marketplace.py b/services/api/app/api/v1/endpoints/marketplace.py
index da92fb507..885c89c18 100644
--- a/services/api/app/api/v1/endpoints/marketplace.py
+++ b/services/api/app/api/v1/endpoints/marketplace.py
@@ -4,6 +4,20 @@ The marketplace ships as a single static index (``marketplace/index.json``)
generated by ``scripts/build_marketplace.py`` from the on-disk
``detections/``, ``playbooks/``, and ``plugins/`` trees.
+Authorization
+-------------
+Install and uninstall require ``settings:write``. One permission covers all
+three item types because one route does: ``body.type`` is
+``detection | playbook | plugin``, so the permission has to be the ceiling of
+the three rather than the floor, and turning tenant-wide content on or off is
+tenant configuration. The per-type permissions live on ``community.py``,
+where each route handles exactly one type.
+
+The catalogue already refused reference-only items over the console's
+objections — that check was load-bearing because a POST straight at this
+route bypassed a button styled as disabled. This closes the other half: the
+caller's entitlement, not just the item's.
+
This module provides a thin HTTP surface so the web UI can:
- Read the index server-side (``GET /v1/marketplace``)
@@ -28,12 +42,12 @@ import json
import threading
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any, Literal
+from typing import Annotated, Any, Literal
-from fastapi import APIRouter, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
-from app.api.v1.deps import AuthUser
+from app.api.v1.deps import AuthUser, require_permission
router = APIRouter(prefix="/marketplace", tags=["marketplace"])
@@ -353,7 +367,7 @@ def _summarise(i: dict[str, Any]) -> dict[str, Any]:
@router.post("/install", response_model=InstallResponse)
async def install_marketplace_item(
body: InstallRequest,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> InstallResponse:
"""Activate a marketplace item for the caller's tenant.
@@ -434,7 +448,7 @@ async def install_marketplace_item(
async def uninstall_marketplace_item(
type: Literal["detection", "playbook", "plugin"],
id: str,
- current_user: AuthUser,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> dict[str, Any]:
"""Remove a previously installed marketplace item from the tenant."""
tenant_id = str(current_user.tenant_id)
diff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.py
index e82572c9c..467be35f9 100644
--- a/services/api/app/api/v1/endpoints/phishing.py
+++ b/services/api/app/api/v1/endpoints/phishing.py
@@ -10,6 +10,19 @@ Endpoints
* ``GET /phishing/submissions`` List submissions.
* ``GET /phishing/{id}`` Get a submission.
* ``POST /phishing/{id}/retriage`` Re-run triage (e.g. after analyst correction).
+
+Authorization
+-------------
+Both writes require ``cases:write``. A submission is investigative working
+material that can open a case — the module does exactly that — so it is the
+same entitlement as working one, and it is held by ``api_service`` too, which
+the summary above needs: automated ingestion submits here with a scoped API
+key.
+
+``viewer`` is refused, which is the point. Each submission runs LLM triage on
+attacker-supplied email text and persists a verdict and extracted IOCs, so an
+ungated route was both an unmetered spend and a way to seed indicators from
+an account entitled to read only.
"""
from __future__ import annotations
@@ -19,13 +32,13 @@ import logging
import os
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
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
from app.services.llm_safety import LLMContractViolation, safe_chat_completions_request
from app.services.model_aliases import chat_completions_url, resolve_api_key, resolve_model_alias
@@ -273,7 +286,9 @@ def _row_to_submission(row: Any) -> SubmissionResponse:
@router.post(
"/submit", response_model=SubmissionResponse, status_code=status.HTTP_201_CREATED, summary="Submit artifact for phishing triage"
)
-async def submit(body: SubmitRequest, db: DBSession, user: AuthUser) -> SubmissionResponse:
+async def submit(
+ body: SubmitRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> SubmissionResponse:
try:
result = await _triage(body.artifact_kind, body.raw_content or "", body.urls)
except AirgapViolation:
@@ -362,7 +377,9 @@ async def get_submission(submission_id: uuid.UUID, db: DBSession, user: AuthUser
@router.post("/{submission_id}/retriage", response_model=SubmissionResponse, summary="Re-run triage on submission")
-async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> SubmissionResponse:
+async def retriage(
+ submission_id: uuid.UUID, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> SubmissionResponse:
existing = (
await db.execute(
text("SELECT * FROM aisoc_phishing_submissions WHERE id = :id AND tenant_id = :tenant_id").bindparams(
diff --git a/services/api/app/api/v1/endpoints/stix_taxii.py b/services/api/app/api/v1/endpoints/stix_taxii.py
index de7b4d876..49fca23a3 100644
--- a/services/api/app/api/v1/endpoints/stix_taxii.py
+++ b/services/api/app/api/v1/endpoints/stix_taxii.py
@@ -6,17 +6,32 @@ the target host is allowed by the air-gap policy), POSTs to
downstream MISP instance via :mod:`app.services.misp_push`. The push
is opt-in per request (``?push_to_misp=true``) unless ``MISP_PUSH_AUTO``
is enabled.
+
+Authorization
+-------------
+All three writes require ``threat_intel:write``, which already existed for
+exactly this and is held by ``tenant_admin``, ``soc_lead`` and
+``threat_hunter``. Publishing a STIX indicator is authoring threat intel, and
+these routes can *leave the platform*: with MISP configured, a published
+indicator is mirrored downstream, so an ungated route let any authenticated
+session — including ``viewer`` — push an indicator of its choosing into the
+tenant's MISP instance under the tenant's credentials.
+
+``/misp/dry-run`` takes the same permission as the live push rather than a
+read: it is a preview of an outbound publication, and gating the rehearsal
+more weakly than the act is how a dry run becomes reconnaissance.
"""
import logging
import uuid
from datetime import UTC, datetime
from enum import Enum
+from typing import Annotated
-from fastapi import APIRouter, HTTPException, Query, status
+from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
-from app.api.v1.deps import AuthUser
+from app.api.v1.deps import AuthUser, require_permission
from app.core.airgap import AirgapViolation
from app.core.config import settings
from app.services.misp_push import (
@@ -347,7 +362,7 @@ async def _push_bundle_or_swallow(bundle: STIXBundle) -> MispPushResult | None:
)
async def create_indicator(
body: STIXIndicatorCreate,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
push_to_misp: bool | None = Query(
default=None,
description=("Mirror this indicator to the configured MISP instance. Defaults to the value of MISP_PUSH_AUTO."),
@@ -391,7 +406,7 @@ async def list_bundles(user: AuthUser) -> BundleListResponse:
)
async def create_bundle(
body: STIXBundleCreate,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
push_to_misp: bool | None = Query(
default=None,
description=(
@@ -467,7 +482,9 @@ async def misp_push_health(user: AuthUser) -> MispPushHealth:
@router.post("/misp/dry-run", response_model=MispDryRunResponse, tags=["MISP push"])
-async def misp_push_dry_run(body: MispDryRunRequest, user: AuthUser) -> MispDryRunResponse:
+async def misp_push_dry_run(
+ body: MispDryRunRequest, user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))]
+) -> MispDryRunResponse:
"""Show the MISP event payload that *would* be pushed, without sending it.
Useful for operators tuning STIX → MISP mappings, and for proving
diff --git a/services/api/tests/test_content_route_permissions.py b/services/api/tests/test_content_route_permissions.py
new file mode 100644
index 000000000..9866569ab
--- /dev/null
+++ b/services/api/tests/test_content_route_permissions.py
@@ -0,0 +1,331 @@
+"""Content publishing, installation and analyst feedback authorize now.
+
+Seventeen routes across five modules. The pattern in `community.py` is the
+sharpest instance of the whole class: its *review* and *curate* routes already
+required `plugins:admin` and `playbooks:admin`, while the routes that
+**submitted** and **installed** required only a session. So the moderation
+step was gated and the thing being moderated was not — a `viewer` could
+publish a signed plugin as the tenant, and install one.
+
+The permission follows the content type, matching what governs authoring that
+type locally: you should not be able to publish or install what you could not
+have written. `plugins:admin` for plugins (code, so installing is an execution
+surface), `rules:write` for detections, `playbooks:write` for playbooks.
+
+`feedback.py` is the subtle one. An override writes an alert's `disposition`
+*and* persists a per-signature prior into institutional memory, where a
+trusted benign prior auto-resolves matching repeat alerts without re-triage.
+Ungated, that was not one wrong verdict; it was a durable instruction to the
+platform to stop looking, writable by a read-only account.
+
+`POST /community/plugins/{id}/rate` is deliberately left ungated, and
+`test_rating_is_deliberately_not_gated` records that as an assertion.
+"""
+
+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 community, feedback, marketplace, phishing, stix_taxii
+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")
+
+SIGMA = "title: t\nid: 1\nstatus: test\ndescription: d\nlogsource:\n category: process_creation\ndetection:\n condition: selection\n"
+
+GATED: list[tuple[Any, str, str, str, str, Any]] = [
+ (community, "add_publisher_key", "plugins:admin", "POST", "/api/v1/community/publishers/keys", {"public_key_pem": "x"}),
+ (community, "revoke_publisher_key", "plugins:admin", "DELETE", "/api/v1/community/publishers/keys/abcd", None),
+ (community, "publish_plugin", "plugins:admin", "POST", "/api/v1/community/plugins/publish", None),
+ (community, "install_community_plugin", "plugins:admin", "POST", "/api/v1/community/plugins/p1/install", None),
+ (community, "publish_detection", "rules:write", "POST", "/api/v1/community/detections/publish", SIGMA),
+ (community, "install_community_detection", "rules:write", "POST", "/api/v1/community/detections/d1/install", None),
+ (community, "submit_playbook", "playbooks:write", "POST", "/api/v1/community/playbooks/submit", {"name": "p"}),
+ (community, "install_community_playbook", "playbooks:write", "POST", "/api/v1/community/playbooks/pb1/install", None),
+ (
+ marketplace,
+ "install_marketplace_item",
+ "settings:write",
+ "POST",
+ "/api/v1/marketplace/install",
+ {"type": "detection", "id": "det-cloud-001"},
+ ),
+ (
+ marketplace,
+ "uninstall_marketplace_item",
+ "settings:write",
+ "DELETE",
+ "/api/v1/marketplace/install?type=detection&id=det-cloud-001",
+ None,
+ ),
+ (
+ stix_taxii,
+ "create_indicator",
+ "threat_intel:write",
+ "POST",
+ "/api/v1/threatintel/stix/indicators",
+ {"pattern": "[ipv4-addr:value = '198.51.100.7']", "name": "c2", "indicator_types": ["malicious-activity"]},
+ ),
+ (stix_taxii, "create_bundle", "threat_intel:write", "POST", "/api/v1/threatintel/stix/bundles", {"indicator_ids": []}),
+ (
+ stix_taxii,
+ "misp_push_dry_run",
+ "threat_intel:write",
+ "POST",
+ "/api/v1/threatintel/stix/misp/dry-run",
+ {"pattern": "[ipv4-addr:value = '198.51.100.7']"},
+ ),
+ (
+ feedback,
+ "submit_alert_override",
+ "alerts:write",
+ "POST",
+ "/api/v1/feedback/alert-override",
+ {"alert_id": str(ROW), "original_verdict": "true_positive", "corrected_verdict": "benign"},
+ ),
+ (
+ feedback,
+ "apply_redisposition_endpoint",
+ "alerts:write",
+ "POST",
+ "/api/v1/feedback/redisposition/apply",
+ {"alert_ids": [str(ROW)], "new_disposition": "benign", "confirmation_token": "t"},
+ ),
+ (phishing, "submit", "cases:write", "POST", "/api/v1/phishing/submit", {"artifact_kind": "email", "raw_content": "hello"}),
+ (phishing, "retriage", "cases:write", "POST", f"/api/v1/phishing/{ROW}/retriage", None),
+]
+
+#: `plugins:admin` and `playbooks:write` name `tenant_admin` rather than
+#: `platform_admin`: the wildcard role would pass even on a misspelling.
+#: `plugins:admin` is not in `ROLE_PERMISSIONS` at all, so only the wildcard
+#: roles hold it — `admin` is used there and the docstring says why.
+HOLDER = {
+ "plugins:admin": "admin",
+ "rules:write": "threat_hunter",
+ "playbooks:write": "tenant_admin",
+ "settings:write": "tenant_admin",
+ "threat_intel:write": "soc_lead",
+ "alerts:write": "soc_analyst",
+ "cases:write": "soc_analyst",
+}
+
+REFUSED = {
+ "plugins:admin": ["viewer", "soc_analyst", "soc_lead", "threat_hunter", "tenant_admin"],
+ "rules:write": ["viewer", "soc_analyst"],
+ "playbooks:write": ["viewer", "soc_analyst", "soc_lead", "threat_hunter"],
+ "settings:write": ["viewer", "soc_analyst", "soc_lead", "threat_hunter"],
+ "threat_intel:write": ["viewer", "soc_analyst"],
+ "alerts:write": ["viewer", "threat_hunter"],
+ "cases:write": ["viewer"],
+}
+
+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.scalar = 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: Any) -> 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)
+ # Two routes take a text/plain body and one takes raw bytes; the rest JSON.
+ kwargs: dict[str, Any] = {}
+ if isinstance(payload, str):
+ kwargs["content"] = payload
+ kwargs["headers"] = {"Content-Type": "text/plain"}
+ elif payload is not None:
+ kwargs["json"] = payload
+ response = client.request(method, path, **kwargs)
+ 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: Any
+ ) -> 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_publish_a_plugin_as_the_tenant(self) -> None:
+ """The submit side of a surface whose review side was already gated."""
+ status, _ = _request(community, "viewer", "POST", "/api/v1/community/plugins/publish", None)
+ assert status == 403
+
+ def test_a_viewer_cannot_install_third_party_plugin_code(self) -> None:
+ status, _ = _request(community, "viewer", "POST", "/api/v1/community/plugins/p1/install", None)
+ assert status == 403
+
+ def test_a_viewer_cannot_push_an_indicator_out_to_misp(self) -> None:
+ """These routes leave the platform under the tenant's credentials."""
+ status, _ = _request(
+ stix_taxii,
+ "viewer",
+ "POST",
+ "/api/v1/threatintel/stix/indicators",
+ {"pattern": "[ipv4-addr:value = '198.51.100.7']", "name": "c2", "indicator_types": ["malicious-activity"]},
+ )
+ assert status == 403
+
+ def test_a_viewer_cannot_teach_the_platform_to_stop_looking(self) -> None:
+ """An override becomes a per-signature prior that auto-resolves repeats."""
+ status, committed = _request(
+ feedback,
+ "viewer",
+ "POST",
+ "/api/v1/feedback/alert-override",
+ {"alert_id": str(ROW), "original_verdict": "true_positive", "corrected_verdict": "benign"},
+ )
+ assert not committed
+ assert status == 403
+
+ def test_the_dry_run_is_not_weaker_than_the_push(self) -> None:
+ """Gating a rehearsal more weakly than the act makes it reconnaissance."""
+ live = _permissions_on(_route_for(stix_taxii, "create_indicator"))
+ dry = _permissions_on(_route_for(stix_taxii, "misp_push_dry_run"))
+ assert dry == live, f"dry run enforces {dry}, live push enforces {live}"
+
+
+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: Any
+ ) -> None:
+ status, _ = _request(module, HOLDER[permission], method, path, payload)
+ assert status != 403, f"{HOLDER[permission]} holds {permission} but {handler} answered 403"
+
+ def test_a_detection_engineer_may_still_install_a_community_rule(self) -> None:
+ """The console's detection catalogue calls this; `threat_hunter` uses it."""
+ status, _ = _request(community, "threat_hunter", "POST", "/api/v1/community/detections/d1/install", None)
+ assert status != 403
+
+ @pytest.mark.parametrize("role", ["soc_analyst", "soc_lead"])
+ def test_an_analyst_may_still_correct_a_verdict(self, role: str) -> None:
+ status, _ = _request(
+ feedback,
+ role,
+ "POST",
+ "/api/v1/feedback/alert-override",
+ {"alert_id": str(ROW), "original_verdict": "true_positive", "corrected_verdict": "benign"},
+ )
+ assert status != 403
+
+ def test_automated_ingestion_may_still_submit_phishing(self) -> None:
+ """`cases:write` is held by `api_service`, which the module needs."""
+ status, _ = _request(phishing, "api_service", "POST", "/api/v1/phishing/submit", {"artifact_kind": "email", "raw_content": "hi"})
+ assert status != 403
+
+ def test_a_viewer_may_still_browse_the_community_catalogue(self) -> None:
+ status, _ = _request(community, "viewer", "GET", "/api/v1/community/detections", 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: Any
+ ) -> None:
+ assert _permissions_on(_route_for(module, handler)) == [permission]
+
+ @pytest.mark.parametrize("module", [marketplace, stix_taxii, feedback, phishing], 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_rating_is_deliberately_not_gated(self) -> None:
+ """The one route in this change left alone, pinned so it stays a decision.
+
+ Every authenticated principal is a legitimate rater, the vocabulary
+ has no permission for expressing an opinion, and requiring an
+ administrative one would mean only administrators may rate. The real
+ integrity question is one-vote-per-user, which the in-memory counter
+ cannot express — a storage and product decision, not an authorization
+ gap.
+ """
+ assert _permissions_on(_route_for(community, "rate_community_plugin")) == []
+
+ def test_rating_is_the_only_ungated_community_route(self) -> None:
+ unguarded = {
+ getattr(r.endpoint, "__name__", "?")
+ for r in community.router.routes
+ if r.methods & {"POST", "PUT", "PATCH", "DELETE"} and not _permissions_on(r)
+ }
+ assert unguarded == {"rate_community_plugin"}, f"unexpected ungated community routes: {unguarded - {'rate_community_plugin'}}"
+
+ def test_publishing_is_never_weaker_than_moderating_a_different_type(self) -> None:
+ """Each content type's publish/install and its moderation route agree.
+
+ The defect was that they disagreed: moderation required an admin
+ permission and submission required nothing at all.
+ """
+ pairs = [
+ ("publish_plugin", "review_community_plugin"),
+ ("install_community_plugin", "review_community_plugin"),
+ ("submit_playbook", "curate_community_playbook"),
+ ("install_community_playbook", "curate_community_playbook"),
+ ]
+ for write, moderate in pairs:
+ write_perms = _permissions_on(_route_for(community, write))
+ moderate_perms = _permissions_on(_route_for(community, moderate))
+ assert write_perms, f"{write} enforces nothing while {moderate} enforces {moderate_perms}"