Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(threatintel): optional shared-secret auth on /api/v1/actors/* (RBAC) (#329)
Aadit Singalc2ad5d44fdbe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 284625d03..ddfa22034 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`AISOC_ATTRIBUTION_TIMEOUT_SECONDS` default of `10` → `30`), and added aregression test (`services/agents/tests/test_attribution_service_url.py`).+### Security++- **Optional auth on the threat-actor attribution endpoints+ (`/api/v1/actors/*`).** The `threatintel` service's actor-attribution+ router previously accepted any caller. It now supports a shared-secret+ gate: when `AISOC_THREATINTEL_SERVICE_TOKEN` is set, every+ `/api/v1/actors/*` call must present `Authorization: Bearer <token>`+ (constant-time compared, `401` on mismatch); when unset it stays+ unauthenticated for backward compatibility and logs a warning. The+ investigation agent forwards the same token via its own+ `AISOC_THREATINTEL_SERVICE_TOKEN`. Resolves the `[#TODO-attribution-rbac]`+ caveat in `docs/threat-actor-attribution.md`.+## [7.4.0] — 2026-05-29Security-hardening and platform release. Folds in the May 27–29 hardening wave,diff --git a/docs/threat-actor-attribution.md b/docs/threat-actor-attribution.mdindex 0c69bf764..76343e2ee 100644--- a/docs/threat-actor-attribution.md+++ b/docs/threat-actor-attribution.md@@ -124,11 +124,17 @@ Lists all profiles in the in-memory catalog.Returns a single profile, or `404` if the ID is unknown.-> **Auth caveat (v0):** the attribution endpoints are mounted on the-> `threatintel` service without RBAC enforcement. They are reachable-> only inside the cluster's service mesh / private network. Do **not**-> expose them through a public ingress until a RBAC dependency is added.-> Tracked in [#TODO-attribution-rbac].+> **Auth:** the `/api/v1/actors/*` endpoints support an optional shared+> secret. When `AISOC_THREATINTEL_SERVICE_TOKEN` is set on the+> `threatintel` service, every call must present+> `Authorization: Bearer <token>` (constant-time compared); a missing or+> wrong token returns `401`. When the variable is unset the endpoints stay+> unauthenticated for backward compatibility — the service is designed to+> run on the cluster's private network — and the service logs a warning so+> an exposed-but-open deployment is visible. **Set the token before+> exposing the service beyond that perimeter, and give the investigation+> agent the same value via its own `AISOC_THREATINTEL_SERVICE_TOKEN` so it+> can authenticate.**## Observabilitydiff --git a/services/agents/app/agents/investigation_agent.py b/services/agents/app/agents/investigation_agent.pyindex 841e13afb..11bc94a4c 100644--- a/services/agents/app/agents/investigation_agent.py+++ b/services/agents/app/agents/investigation_agent.py@@ -22,6 +22,11 @@ logger = structlog.get_logger()# Kubernetes / Fly / standalone deployments.THREAT_INTEL_SERVICE_URL = os.getenv("AISOC_THREATINTEL_URL", "http://threatintel:8005").rstrip("/")ATTRIBUTION_TIMEOUT_SECONDS = float(os.getenv("AISOC_ATTRIBUTION_TIMEOUT_SECONDS", "30.0"))+# Optional shared secret presented to the threatintel ``/api/v1/actors/*``+# endpoints when that service is configured to require one (its own+# ``AISOC_THREATINTEL_SERVICE_TOKEN``). Left empty for internal-only+# deployments, where the endpoints accept unauthenticated calls.+THREAT_INTEL_SERVICE_TOKEN = os.getenv("AISOC_THREATINTEL_SERVICE_TOKEN", "").strip()async def run_investigation(state: InvestigationState) -> InvestigationState:@@ -214,6 +219,7 @@ async def _call_attribution_service(httpx.HTTPError: on transport or non-2xx responses; the callerconverts these into a non-fatal finding."""+ headers = {"Authorization": f"Bearer {THREAT_INTEL_SERVICE_TOKEN}"} if THREAT_INTEL_SERVICE_TOKEN else {}try:async with httpx.AsyncClient(timeout=ATTRIBUTION_TIMEOUT_SECONDS) as client:response = await client.post(@@ -223,6 +229,7 @@ async def _call_attribution_service("mitre_techniques": mitre_techniques,"case_metadata": case_metadata,},+ headers=headers,)response.raise_for_status()return response.json()diff --git a/services/agents/tests/test_attribution_auth_header.py b/services/agents/tests/test_attribution_auth_header.pynew file mode 100644index 000000000..7b6f6c39c--- /dev/null+++ b/services/agents/tests/test_attribution_auth_header.py@@ -0,0 +1,55 @@+"""The investigation agent forwards the threatintel shared secret when set.++When ``AISOC_THREATINTEL_SERVICE_TOKEN`` is configured, the agent's+attribution call must carry ``Authorization: Bearer <token>`` so a+``threatintel`` service that enforces the gate accepts it; when unset, no+auth header is sent (internal-only default). Network mocked with respx.+"""++from __future__ import annotations++import importlib+import sys+from pathlib import Path++import httpx+import pytest+import respx++# Match the path-mutation pattern used by the rest of services/agents/tests/.+_AGENTS_ROOT = Path(__file__).resolve().parents[1]+if str(_AGENTS_ROOT) not in sys.path:+ sys.path.insert(0, str(_AGENTS_ROOT))++_BASE = "http://ti-test:8005"+++def _reload_agent(monkeypatch: pytest.MonkeyPatch, token: str | None):+ monkeypatch.setenv("AISOC_THREATINTEL_URL", _BASE)+ if token is None:+ monkeypatch.delenv("AISOC_THREATINTEL_SERVICE_TOKEN", raising=False)+ else:+ monkeypatch.setenv("AISOC_THREATINTEL_SERVICE_TOKEN", token)+ module = importlib.import_module("app.agents.investigation_agent")+ return importlib.reload(module)+++async def test_forwards_bearer_when_token_set(monkeypatch: pytest.MonkeyPatch):+ module = _reload_agent(monkeypatch, "s3cret-token")+ route = respx.post(f"{_BASE}/api/v1/actors/attribute").mock(+ return_value=httpx.Response(200, json={"actor_id": "unknown"}),+ )+ await module._call_attribution_service(iocs=[], mitre_techniques=["T1566"], case_metadata={})+ assert route.calls.last.request.headers.get("authorization") == "Bearer s3cret-token"+++async def test_no_auth_header_when_token_unset(monkeypatch: pytest.MonkeyPatch):+ module = _reload_agent(monkeypatch, None)+ route = respx.post(f"{_BASE}/api/v1/actors/attribute").mock(+ return_value=httpx.Response(200, json={"actor_id": "unknown"}),+ )+ await module._call_attribution_service(iocs=[], mitre_techniques=["T1566"], case_metadata={})+ header_names = {k.lower() for k in route.calls.last.request.headers.keys()}+ assert "authorization" not in header_namesdiff --git a/services/threatintel/app/api/actor_attribution.py b/services/threatintel/app/api/actor_attribution.pyindex 27e8297c5..110919b0e 100644--- a/services/threatintel/app/api/actor_attribution.py+++ b/services/threatintel/app/api/actor_attribution.py@@ -20,9 +20,18 @@ from app.actors.attribution import (ThreatActorAttributionEngine,ThreatActorProfile,)+from app.api.auth import require_actor_authlogger = structlog.get_logger(__name__)-router = APIRouter(prefix="/api/v1/actors", tags=["threat-actors"])++# ``require_actor_auth`` gates every route on this router: a no-op when+# ``AISOC_THREATINTEL_SERVICE_TOKEN`` is unset (internal-only default), a+# constant-time bearer-token check when it is set.+router = APIRouter(+ prefix="/api/v1/actors",+ tags=["threat-actors"],+ dependencies=[Depends(require_actor_auth)],+)def get_attribution_engine(request: Request) -> ThreatActorAttributionEngine:diff --git a/services/threatintel/app/api/auth.py b/services/threatintel/app/api/auth.pynew file mode 100644index 000000000..fbe66acf0--- /dev/null+++ b/services/threatintel/app/api/auth.py@@ -0,0 +1,75 @@+"""Optional shared-secret auth for the threat-actor attribution HTTP surface.++The ``threatintel`` service runs inside the cluster's private network, so by+default the ``/api/v1/actors/*`` endpoints accept internal calls without+authentication (their historical behaviour). When an operator exposes the+service beyond that perimeter — or runs it in an MSSP / multi-tenant+deployment — they set ``AISOC_THREATINTEL_SERVICE_TOKEN``; the endpoints then+require ``Authorization: Bearer <token>``, compared in constant time.++This mirrors two existing conventions in the codebase:++* the ingest ``k8s-audit`` shared-secret gate — a header token compared with+ ``subtle.ConstantTimeCompare`` (here: :func:`hmac.compare_digest`), and+* the actions->api ``AISOC_API_SERVICE_TOKEN`` inter-service token.++Resolves the ``[#TODO-attribution-rbac]`` caveat in+``docs/threat-actor-attribution.md``.+"""++from __future__ import annotations++import hmac++import structlog+from fastapi import Header, HTTPException, status++from app.config import settings++logger = structlog.get_logger(__name__)++_BEARER_PREFIX = "bearer "++# Warn at most once per process so an exposed-but-unauthenticated deployment+# is visible in logs without flooding them on every request.+_warned_unconfigured = False+++def _expected_token() -> str:+ return (getattr(settings, "AISOC_THREATINTEL_SERVICE_TOKEN", "") or "").strip()+++async def require_actor_auth(authorization: str | None = Header(default=None)) -> None:+ """FastAPI dependency gating the ``/api/v1/actors/*`` endpoints.++ * Token unset → allow (internal-only default), warning once so operators+ who have exposed the service notice it is unauthenticated.+ * Token set → require a matching ``Authorization: Bearer <token>``,+ constant-time compared; missing or wrong → ``401``.+ """+ expected = _expected_token()+ if not expected:+ global _warned_unconfigured+ if not _warned_unconfigured:+ logger.warning(+ "actor_auth.unconfigured",+ detail=(+ "AISOC_THREATINTEL_SERVICE_TOKEN is unset; /api/v1/actors/* "+ "is unauthenticated. Set it (and configure the investigation "+ "agent with the same value) before exposing the service "+ "beyond the private network."+ ),+ )+ _warned_unconfigured = True+ return++ presented = ""+ if authorization and authorization.lower().startswith(_BEARER_PREFIX):+ presented = authorization[len(_BEARER_PREFIX) :].strip()++ if not presented or not hmac.compare_digest(presented, expected):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing bearer token",+ headers={"WWW-Authenticate": "Bearer"},+ )diff --git a/services/threatintel/app/config.py b/services/threatintel/app/config.pyindex 4e66bb033..2b3a5fc22 100644--- a/services/threatintel/app/config.py+++ b/services/threatintel/app/config.py@@ -18,6 +18,13 @@ class Settings(BaseSettings):VERSION: str = "0.1.0"ENVIRONMENT: str = "development"+ # Optional shared-secret gate for the /api/v1/actors/* HTTP surface.+ # When set, callers must present ``Authorization: Bearer <token>``+ # (constant-time compared). Unset keeps the historical internal-only+ # behaviour (unauthenticated). Mirrors the actions->api+ # ``AISOC_API_SERVICE_TOKEN`` inter-service-token convention.+ AISOC_THREATINTEL_SERVICE_TOKEN: str = ""+# Redis (bloom filter + cache)REDIS_URL: str = "redis://redis:6379/2"BLOOM_CAPACITY: int = 10_000_000diff --git a/services/threatintel/tests/test_actor_attribution_auth.py b/services/threatintel/tests/test_actor_attribution_auth.pynew file mode 100644index 000000000..077c32428--- /dev/null+++ b/services/threatintel/tests/test_actor_attribution_auth.py@@ -0,0 +1,77 @@+"""HTTP-level tests for the optional shared-secret gate on /api/v1/actors/*.++The gate (``app.api.auth.require_actor_auth``) is a no-op when+``AISOC_THREATINTEL_SERVICE_TOKEN`` is unset (internal-only default) and a+constant-time bearer-token check when it is set. We mount the real router on+a throwaway app with a real (lightweight, os_store-less) attribution engine+and drive it with FastAPI's ``TestClient``.+"""++from __future__ import annotations++import pytest+from app.actors.attribution import ThreatActorAttributionEngine+from app.api.actor_attribution import router+from app.config import settings+from fastapi import FastAPI+from fastapi.testclient import TestClient+++def _client() -> TestClient:+ app = FastAPI()+ app.state.attribution_engine = ThreatActorAttributionEngine()+ app.include_router(router)+ return TestClient(app)+++def token(monkeypatch: pytest.MonkeyPatch):+ """Configure a shared secret for the duration of a test."""+ monkeypatch.setattr(settings, "AISOC_THREATINTEL_SERVICE_TOKEN", "s3cret-token")+ return "s3cret-token"+++def test_unconfigured_allows_unauthenticated(monkeypatch: pytest.MonkeyPatch):+ """With no token set, the endpoints keep their internal-only open behaviour."""+ monkeypatch.setattr(settings, "AISOC_THREATINTEL_SERVICE_TOKEN", "")+ resp = _client().get("/api/v1/actors/profiles")+ assert resp.status_code == 200+ assert isinstance(resp.json(), list)+++def test_configured_rejects_missing_token(token):+ resp = _client().get("/api/v1/actors/profiles")+ assert resp.status_code == 401+++def test_configured_rejects_wrong_token(token):+ resp = _client().get("/api/v1/actors/profiles", headers={"Authorization": "Bearer nope"})+ assert resp.status_code == 401+++def test_configured_accepts_correct_token(token):+ resp = _client().get("/api/v1/actors/profiles", headers={"Authorization": f"Bearer {token}"})+ assert resp.status_code == 200+++def test_attribute_endpoint_is_also_gated(token):+ """The POST /attribute route is gated by the same router dependency."""+ client = _client()+ body = {"iocs": [], "mitre_techniques": ["T1566"], "case_metadata": {}}++ assert client.post("/api/v1/actors/attribute", json=body).status_code == 401++ ok = client.post(+ "/api/v1/actors/attribute",+ json=body,+ headers={"Authorization": f"Bearer {token}"},+ )+ assert ok.status_code == 200+ assert "actor_id" in ok.json()+++def test_profile_by_id_is_also_gated(token):+ client = _client()+ assert client.get("/api/v1/actors/profiles/APT28").status_code == 401+ ok = client.get("/api/v1/actors/profiles/APT28", headers={"Authorization": f"Bearer {token}"})+ assert ok.status_code == 200