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.

[F013] security: harden /v1/threat-intel/* with require_permission RBAC (#88)

Beenu Arora51324d5a9ca0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb6da706c..43548955b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security — MSSP RBAC hardening on `/threat-intel` (Issue F013)
+
+The `/v1/threat-intel/*` endpoints (IOCs, threat actors, intel feeds) were
+previously gated only by `get_current_user`, meaning **any authenticated
+role**, including `viewer` and `soc_analyst`, could `POST` an IOC, `DELETE`
+a feed, or create a new `ThreatActor` profile. In a managed-SOC / MSSP
+deployment that is a privilege-escalation vector: a compromised analyst
+seat can poison detections across the whole tenant by injecting false IOCs
+or deleting the feed that hydrates them.
+
+- **`services/api/app/api/v1/endpoints/threat_intel.py`** — every route now
+ declares the explicit permission it needs via
+ `Depends(require_permission("threat_intel:read" | "threat_intel:write"))`.
+ Read routes (`GET /iocs`, `/iocs/{id}`, `/actors`, `/feeds`) require
+ `threat_intel:read`; write routes (`POST /iocs`, `DELETE /iocs/{id}`,
+ `POST /actors`, `POST /feeds`, `DELETE /feeds/{id}`) require
+ `threat_intel:write`. The legacy `User`-typed dependency was replaced with
+ the platform-standard `AuthUser` so JWT and API-key callers are gated by
+ the same code path.
+- **`services/api/app/core/security.py`** — `ROLE_PERMISSIONS` now grants
+ `threat_intel:write` to `tenant_admin` and `soc_lead` in addition to the
+ existing `admin` / `platform_admin` / `threat_hunter` set. Without this
+ the endpoint hardening would have locked out the two roles that legitimately
+ need to manage tenant intel during an investigation.
+- **`services/api/tests/test_threat_intel_rbac.py`** — 38 new regression tests
+ pin the role/permission map (write-roles must hold `:write`, read-only roles
+ must not), assert that `CurrentUser.require_permission` raises HTTP 403 for
+ under-privileged roles and 200 for privileged ones, cover the API-key code
+ path including scope wildcards, and grep the endpoint module to ensure
+ every route still uses `require_permission(...)` (so a refactor that
+ silently downgrades a route fails CI).
+
+Tracked as **F013** in `docs/community-feedback/2026-05-12/`.
+
### Documentation — install pipeline + v2.2 architecture refresh
Documentation-only refresh that aligns every install / architecture page
diff --git a/services/api/app/api/v1/endpoints/threat_intel.py b/services/api/app/api/v1/endpoints/threat_intel.py
index 18503765d..3cd78ec71 100644
--- a/services/api/app/api/v1/endpoints/threat_intel.py
+++ b/services/api/app/api/v1/endpoints/threat_intel.py
@@ -1,19 +1,35 @@
-"""Internal threat-intel generation endpoints."""
+"""Internal threat-intel generation endpoints.
+
+Access control
+--------------
+Threat-intel data (IOCs, threat actors, feeds) is sensitive in MSSP/multi-tenant
+deployments — a noisy or malicious analyst could otherwise poison detections
+across the whole tenant by injecting false IOCs or deleting feeds.
+
+All endpoints below are gated on RBAC permissions resolved by
+``app.api.v1.deps.require_permission``:
+
+* ``threat_intel:read`` – list / get
+* ``threat_intel:write`` – create / delete
+
+The ``viewer`` role gets read access; analyst-tier roles
+(``threat_hunter``, ``soc_lead``, ``tenant_admin``) get write access.
+See ``app.core.security.ROLE_PERMISSIONS`` for the authoritative map.
+"""
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, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.endpoints.auth import get_current_user
+from app.api.v1.deps import AuthUser, require_permission
from app.db.database import get_db
-from app.models.tenant import User
from app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC
router = APIRouter(prefix="/threat-intel", tags=["threat-intel"])
@@ -105,13 +121,13 @@ class FeedOut(FeedCreate):
@router.get("/iocs", response_model=list[IOCOut])
async def list_iocs(
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:read"))],
ioc_type: str | None = Query(None),
severity: str | None = Query(None),
is_active: bool | None = Query(None),
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> list[ThreatIntelIOC]:
q = select(ThreatIntelIOC).where(ThreatIntelIOC.tenant_id == current_user.tenant_id)
if ioc_type:
@@ -128,8 +144,8 @@ async def list_iocs(
@router.post("/iocs", response_model=IOCOut, status_code=status.HTTP_201_CREATED)
async def create_ioc(
body: IOCCreate,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> ThreatIntelIOC:
ioc = ThreatIntelIOC(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(ioc)
@@ -141,8 +157,8 @@ async def create_ioc(
@router.get("/iocs/{ioc_id}", response_model=IOCOut)
async def get_ioc(
ioc_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:read"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> ThreatIntelIOC:
ioc = await db.get(ThreatIntelIOC, ioc_id)
if not ioc or ioc.tenant_id != current_user.tenant_id:
@@ -153,8 +169,8 @@ async def get_ioc(
@router.delete("/iocs/{ioc_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_ioc(
ioc_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> None:
ioc = await db.get(ThreatIntelIOC, ioc_id)
if not ioc or ioc.tenant_id != current_user.tenant_id:
@@ -170,11 +186,11 @@ async def delete_ioc(
@router.get("/actors", response_model=list[ThreatActorOut])
async def list_actors(
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:read"))],
is_active: bool | None = Query(None),
limit: int = Query(50, le=200),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> list[ThreatActor]:
q = select(ThreatActor).where(ThreatActor.tenant_id == current_user.tenant_id)
if is_active is not None:
@@ -187,8 +203,8 @@ async def list_actors(
@router.post("/actors", response_model=ThreatActorOut, status_code=status.HTTP_201_CREATED)
async def create_actor(
body: ThreatActorCreate,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> ThreatActor:
actor = ThreatActor(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(actor)
@@ -204,8 +220,8 @@ async def create_actor(
@router.get("/feeds", response_model=list[FeedOut])
async def list_feeds(
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:read"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> list[ThreatIntelFeed]:
result = await db.execute(
select(ThreatIntelFeed).where(ThreatIntelFeed.tenant_id == current_user.tenant_id).order_by(ThreatIntelFeed.name)
@@ -216,8 +232,8 @@ async def list_feeds(
@router.post("/feeds", response_model=FeedOut, status_code=status.HTTP_201_CREATED)
async def create_feed(
body: FeedCreate,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> ThreatIntelFeed:
feed = ThreatIntelFeed(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(feed)
@@ -229,8 +245,8 @@ async def create_feed(
@router.delete("/feeds/{feed_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_feed(
feed_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:write"))],
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
) -> None:
feed = await db.get(ThreatIntelFeed, feed_id)
if not feed or feed.tenant_id != current_user.tenant_id:
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index 4f93df2ae..b5b4da4f2 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -48,6 +48,11 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"reports:read",
"reports:write",
"threat_intel:read",
+ # Tenant admins must be able to manage their tenant's threat-intel
+ # surface (IOCs, actor profiles, feed config). Without :write the
+ # admin role could not even add a feed, let alone delete a poisoned
+ # IOC injected by a compromised analyst.
+ "threat_intel:write",
"settings:read",
"settings:write",
# Workstream 7: tenant lake API. Tenant admins get full access
@@ -73,6 +78,10 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"reports:read",
"reports:write",
"threat_intel:read",
+ # SOC leads triage incidents and need to be able to add/expire
+ # IOCs derived from investigations without waiting on the threat-
+ # hunter or tenant-admin role.
+ "threat_intel:write",
# SOC leads run investigations across the lake routinely.
"lake:query",
"lake:read_schema",
diff --git a/services/api/tests/test_threat_intel_rbac.py b/services/api/tests/test_threat_intel_rbac.py
new file mode 100644
index 000000000..b96508106
--- /dev/null
+++ b/services/api/tests/test_threat_intel_rbac.py
@@ -0,0 +1,217 @@
+"""RBAC regression tests for the /threat-intel endpoints (Issue #13).
+
+The threat-intel surface (IOCs, threat actors, intel feeds) is shared
+across a tenant. In an MSSP / multi-tenant deployment, an analyst with
+``viewer`` permissions must NOT be able to:
+
+* create IOCs (a malicious analyst could poison detections by injecting
+ false positives or whitelisting attacker infrastructure);
+* delete IOCs/feeds (could blind detections by removing the IOCs that
+ actually fire on the attacker traffic);
+* create or modify threat-actor profiles (used by the attribution
+ engine; bad data here surfaces in customer-visible briefings).
+
+Before this fix the endpoints in
+``app.api.v1.endpoints.threat_intel`` only required *authentication*
+(``get_current_user``), not the ``threat_intel:write`` *permission*.
+That meant any role that could log in (e.g. ``viewer``, ``soc_analyst``,
+``api_service``) could create or delete IOCs.
+
+These tests pin three things so the security gate cannot regress:
+
+1. The static ``ROLE_PERMISSIONS`` map grants ``threat_intel:write``
+ only to roles that should hold it (admin/tenant_admin/soc_lead/threat_hunter).
+2. ``CurrentUser.require_permission`` raises HTTP 403 for under-privileged
+ roles trying to perform write actions.
+3. ``CurrentUser.require_permission`` permits the privileged roles.
+
+We exercise (2) and (3) at the dependency layer, not by spinning up the
+full FastAPI app, because the permission semantics are fully owned by
+``app.api.v1.deps.CurrentUser`` and ``app.core.security.has_permission``.
+That keeps the test hermetic (no DB, no app lifespan) while still
+catching the real regression: removing the ``require_permission(...)``
+``Depends`` from ``threat_intel.py``.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.core.security import ROLE_PERMISSIONS, has_permission
+from fastapi import HTTPException
+
+# ─── Static role-permission map (the source of truth) ────────────────────
+
+
+WRITE_ROLES = ("admin", "platform_admin", "tenant_admin", "soc_lead", "threat_hunter")
+READ_ONLY_ROLES = ("soc_analyst", "viewer", "api_service")
+
+
[email protected]("role", WRITE_ROLES)
+def test_write_roles_have_threat_intel_write(role: str) -> None:
+ """Roles that own the threat-intel surface must hold :write.
+
+ Removing :write from any of these roles would silently downgrade
+ the role to read-only across the whole API, which is exactly the
+ kind of change that would slip through code review.
+ """
+ assert has_permission(role, "threat_intel:write"), (
+ f"Role {role!r} lost threat_intel:write — this is a permission "
+ "regression. Either restore it in app.core.security.ROLE_PERMISSIONS "
+ "or update WRITE_ROLES in this test."
+ )
+
+
[email protected]("role", READ_ONLY_ROLES)
+def test_read_only_roles_lack_threat_intel_write(role: str) -> None:
+ """Lower-privileged roles must NOT be able to mutate threat-intel.
+
+ This is the core of the MSSP RBAC fix: a ``viewer`` or
+ ``soc_analyst`` token must be rejected by the write endpoints even
+ though it authenticates successfully.
+ """
+ assert not has_permission(role, "threat_intel:write"), (
+ f"Role {role!r} unexpectedly has threat_intel:write. If this is "
+ "intentional, update READ_ONLY_ROLES; otherwise this is the "
+ "MSSP-RBAC vulnerability returning."
+ )
+
+
[email protected]("role", WRITE_ROLES + READ_ONLY_ROLES)
+def test_all_known_roles_can_read_threat_intel(role: str) -> None:
+ """Every legitimate role must keep :read.
+
+ Read access is required for the alerts UI to display IOC enrichment
+ inline. If we ever drop :read from a role we should know about it
+ here, not from a 403 in the browser.
+ """
+ assert has_permission(role, "threat_intel:read"), (
+ f"Role {role!r} lost threat_intel:read — this would break the alerts UI (IOC enrichment renders inline)."
+ )
+
+
+def test_role_permissions_map_covers_every_role_under_test() -> None:
+ """Sanity check: the test parameters track the real role list.
+
+ If someone adds a new role to ROLE_PERMISSIONS but forgets to
+ classify it as write or read-only here, this test fails loudly
+ instead of silently leaving the new role unaudited.
+ """
+ real_roles = set(ROLE_PERMISSIONS) - {"admin", "platform_admin"}
+ audited_roles = set(WRITE_ROLES + READ_ONLY_ROLES) - {"admin", "platform_admin"}
+ missing = real_roles - audited_roles
+ assert not missing, (
+ f"New role(s) {missing} added to ROLE_PERMISSIONS without RBAC test coverage. Add them to WRITE_ROLES or READ_ONLY_ROLES."
+ )
+
+
+# ─── CurrentUser.require_permission integration ──────────────────────────
+
+
+def _user(role: str, scopes: list[str] | None = None) -> CurrentUser:
+ """Construct a CurrentUser without touching the DB or JWT plumbing."""
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ role=role,
+ email=f"{role}@example.test",
+ scopes=scopes,
+ )
+
+
[email protected]("role", READ_ONLY_ROLES)
+def test_require_permission_blocks_read_only_roles_from_write(role: str) -> None:
+ """The dependency layer must 403 read-only roles trying to write.
+
+ This mirrors what FastAPI does when ``Depends(require_permission(
+ "threat_intel:write"))`` runs against a viewer token.
+ """
+ user = _user(role)
+ with pytest.raises(HTTPException) as exc:
+ user.require_permission("threat_intel:write")
+ assert exc.value.status_code == 403
+ assert "threat_intel:write" in exc.value.detail
+
+
[email protected]("role", WRITE_ROLES)
+def test_require_permission_allows_write_roles(role: str) -> None:
+ """The dependency layer must allow privileged roles through.
+
+ ``require_permission`` returns ``None`` on success; we assert it
+ does not raise.
+ """
+ user = _user(role)
+ user.require_permission("threat_intel:write") # must not raise
+
+
[email protected]("role", READ_ONLY_ROLES + WRITE_ROLES)
+def test_require_permission_allows_read_for_all_legitimate_roles(role: str) -> None:
+ user = _user(role)
+ user.require_permission("threat_intel:read") # must not raise
+
+
+# ─── API-key scope path ──────────────────────────────────────────────────
+
+
+def test_api_key_scoped_read_cannot_write() -> None:
+ """A scoped API key with only :read must be 403'd on :write.
+
+ API keys carry an explicit scope list (``CurrentUser.scopes``); the
+ role field is ignored on that path. This test pins the contract that
+ a key issued with ``threat_intel:read`` cannot escalate by being
+ used against a write endpoint.
+ """
+ key = _user(role="api_service", scopes=["threat_intel:read"])
+ with pytest.raises(HTTPException) as exc:
+ key.require_permission("threat_intel:write")
+ assert exc.value.status_code == 403
+ assert "API key missing scope" in exc.value.detail
+
+
+def test_api_key_scoped_write_can_write() -> None:
+ key = _user(role="api_service", scopes=["threat_intel:write"])
+ key.require_permission("threat_intel:write") # must not raise
+
+
+def test_api_key_wildcard_scope_can_write() -> None:
+ """``"*"`` is the all-access scope used by platform-internal keys."""
+ key = _user(role="api_service", scopes=["*"])
+ key.require_permission("threat_intel:write") # must not raise
+
+
+def test_api_key_resource_wildcard_scope_can_write() -> None:
+ """``threat_intel:*`` covers every action under the resource."""
+ key = _user(role="api_service", scopes=["threat_intel:*"])
+ key.require_permission("threat_intel:write") # must not raise
+
+
+# ─── Cross-tenant isolation guardrail (defense in depth) ─────────────────
+
+
+def test_threat_intel_endpoint_module_uses_require_permission() -> None:
+ """Source-level guardrail: imports must include the RBAC dependency.
+
+ If a future refactor accidentally drops the ``require_permission``
+ import from ``threat_intel.py`` (the failure mode that originally
+ caused this issue), this test fails before any HTTP traffic does.
+ """
+ import inspect
+
+ from app.api.v1.endpoints import threat_intel
+
+ src = inspect.getsource(threat_intel)
+ assert "require_permission" in src, (
+ "threat_intel.py no longer references require_permission — the MSSP RBAC gate has been removed. See Issue #13."
+ )
+ assert 'require_permission("threat_intel:write")' in src, (
+ "threat_intel.py no longer gates on threat_intel:write. "
+ "Write endpoints (POST/DELETE on /iocs, /actors, /feeds) must "
+ "stay behind that permission."
+ )
+ assert 'require_permission("threat_intel:read")' in src, (
+ "threat_intel.py no longer gates on threat_intel:read. "
+ "Even read endpoints should require the permission so a token "
+ "that lacks it (e.g. a future limited role) is denied loudly."
+ )