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
fix(security): require auth on the services that were fully unauthenticated (#661)
Beenu Arora31e3b623cbc1
diff --git a/.env.example b/.env.exampleindex 86ba02c3d..2d49826b2 100644--- a/.env.example+++ b/.env.example@@ -210,3 +210,18 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8086# Override the docs site base URL (default: https://beenuar.github.io/AiSOC/docs).# Set this when serving docs from a custom domain like https://docs.tryaisoc.com/docs.# NEXT_PUBLIC_DOCS_URL=https://docs.tryaisoc.com/docs++# ─── Service-to-service auth ──────────────────────────────────────────────────+# Shared bearer token for backend services that are NOT reachable from the+# browser (purple-team, honeytokens, ueba). Those surfaces execute privileged+# work — purple-team can start adversary-emulation operations against live+# hosts — and they fail closed: with no token configured and AISOC_DEV_MODE+# unset, they answer 503 rather than serving the route openly.+#+# Leave blank for local `docker compose up` (AISOC_DEV_MODE covers it). Set a+# real value for anything network-reachable.+AISOC_SERVICE_TOKEN=+# Optional per-service overrides, if you'd rather not share one secret:+# AISOC_PURPLE_TEAM_SERVICE_TOKEN=+# AISOC_HONEYTOKENS_SERVICE_TOKEN=+# AISOC_UEBA_SERVICE_TOKEN=diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a49471bbf..838a39069 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -385,7 +385,12 @@ jobs:# archives normalized events into the ClickHouse event lake.# pyyaml: required since Phase A2 — the detection-matcher parity test# loads the canonical scripts/generate_detections.py (imports yaml).- run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka asyncpg clickhouse-driver pyyaml cryptography+ # sqlalchemy: required by the purple-team router-contract test. That+ # test asserts every route on the router carries the service-auth+ # dependency, and importing the router to enumerate its routes pulls+ # sqlalchemy. Skipping the import instead would leave a gate that+ # cannot fail, which is worse than installing one more package.+ run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka asyncpg clickhouse-driver pyyaml cryptography sqlalchemy- name: Install pytest-cov (Phase 2.2 coverage gate)run: pip install --quiet 'pytest-cov>=4,<7'# Phase 2.2 — every wave-1 service now has a measured coveragediff --git a/docker-compose.yml b/docker-compose.ymlindex 66117303a..37fb07354 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -568,6 +568,8 @@ services:KAFKA_BOOTSTRAP_SERVERS: kafka:29092CLICKHOUSE_URL: http://aisoc:clickhouse_dev_secret@clickhouse:8123/aisocCORE_API_URL: http://api:8000+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}+ AISOC_DEV_MODE: ${AISOC_DEV_MODE:-1}networks:- aisocrestart: unless-stopped@@ -597,6 +599,8 @@ services:REDIS_URL: redis://:redis_dev_secret@redis:6379/9KAFKA_BOOTSTRAP_SERVERS: kafka:29092CORE_API_URL: http://api:8000+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}+ AISOC_DEV_MODE: ${AISOC_DEV_MODE:-1}networks:- aisocrestart: unless-stopped@@ -624,6 +628,8 @@ services:REDIS_URL: redis://:redis_dev_secret@redis:6379/10CORE_API_URL: http://api:8000ATTCK_DATA_PATH: /app/data/enterprise-attack.json+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}+ AISOC_DEV_MODE: ${AISOC_DEV_MODE:-1}networks:- aisocrestart: unless-stoppeddiff --git a/services/honeytokens/app/api/routes.py b/services/honeytokens/app/api/routes.pyindex 97f7411a5..9e0173934 100644--- a/services/honeytokens/app/api/routes.py+++ b/services/honeytokens/app/api/routes.py@@ -13,10 +13,11 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asynfrom app.core.config import settingsfrom app.models.honeytoken import Honeytoken, HoneytokenTrigger+from app.security.service_auth import require_service_authfrom app.services.alerting import send_alertfrom app.services.generator import TOKEN_GENERATORS, generate_token-router = APIRouter(prefix="/api/v1/honeytokens", tags=["honeytokens"])+router = APIRouter(prefix="/api/v1/honeytokens", tags=["honeytokens"], dependencies=[Depends(require_service_auth)])# ---------------------------------------------------------------------------# DB dependencydiff --git a/services/honeytokens/app/security/__init__.py b/services/honeytokens/app/security/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/honeytokens/app/security/service_auth.py b/services/honeytokens/app/security/service_auth.pynew file mode 100644index 000000000..8105371df--- /dev/null+++ b/services/honeytokens/app/security/service_auth.py@@ -0,0 +1,83 @@+"""Service-to-service bearer auth for mutating routes.++Vendored byte-identical into each Python service that needs it, following the+same convention as ``app/core/cors.py``. Keep the copies in sync.++Why this exists+---------------+Several backend services shipped with every route reachable without any+credential at all. The worst case was ``purple-team``'s ``POST /caldera/run``,+which starts a real adversary-emulation operation against live hosts and read+the caller's ``tenant_id`` and ``executed_by`` straight out of the request body+— so the caller declared their own identity and their own tenant.++These services are not reachable from the browser (the web app only proxies to+api, agents, enrichment, fusion, osquery-tls and realtime), so they are+service-to-service surfaces and a shared bearer token is the right shape. They+fail closed: without a configured token a production deployment answers 503+rather than serving the route openly.++Deliberately NOT applied to ``services/mesh``, which is a federated community+hub that is public by design and protected instead by Ed25519 signature+verification and k-anonymity.++Configuration+-------------+``AISOC_SERVICE_TOKEN``+ Shared secret presented as ``Authorization: Bearer <token>`` by callers.+``AISOC_<SERVICE>_SERVICE_TOKEN``+ Optional per-service override, e.g. ``AISOC_PURPLE_TEAM_SERVICE_TOKEN``.+``AISOC_DEV_MODE``+ When set and no token is configured, requests are allowed through so a+ local ``docker compose up`` still works. This mirrors the single canonical+ dev-mode flag used across the platform; it is asserted off in production by+ ``tests/test_security_defaults.py``.+"""++from __future__ import annotations++import hmac+import os++from fastapi import Header, HTTPException, status++#: Set by each vendored copy so the per-service override resolves.+SERVICE_NAME = "HONEYTOKENS"++_TRUTHY = {"1", "true", "yes", "on"}+++def _dev_mode() -> bool:+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY+++def resolve_token() -> str:+ """Per-service override wins, then the shared platform token."""+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()+++async def require_service_auth(authorization: str | None = Header(default=None)) -> None:+ """FastAPI dependency. Fails closed unless explicitly in dev mode."""+ token = resolve_token()+ if not token:+ if _dev_mode():+ return+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=(+ "service auth is not configured; set AISOC_SERVICE_TOKEN "+ f"(or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) before exposing this service"+ ),+ )++ expected = f"Bearer {token}"+ # compare_digest rather than == so the comparison is not timing-variable.+ if not authorization or not hmac.compare_digest(authorization, expected):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing service token",+ headers={"WWW-Authenticate": "Bearer"},+ )diff --git a/services/purple-team/app/api/routes.py b/services/purple-team/app/api/routes.pyindex 409b97180..ddfd04045 100644--- a/services/purple-team/app/api/routes.py+++ b/services/purple-team/app/api/routes.py@@ -7,7 +7,7 @@ import uuidfrom datetime import UTC, datetimefrom typing import Any-from fastapi import APIRouter, HTTPException, Query+from fastapi import APIRouter, Depends, HTTPException, Queryfrom pydantic import BaseModelfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine@@ -20,6 +20,7 @@ from app.models.purple_team import (TabletopSession,TestExecution,)+from app.security.service_auth import require_service_authfrom app.services.atomic_loader import load_atomicsfrom app.services.caldera_client import CalderaClientfrom app.services.drift import (@@ -32,7 +33,21 @@ from app.services.drift import (LOG = logging.getLogger(__name__)-router = APIRouter()+# Default-deny for the whole router, not just the mutating verbs.+#+# This service executes adversary emulation: `POST /caldera/run` starts a real+# Caldera operation against live hosts and `POST /atomics/run` records an+# execution. Both were reachable with no credential at all, and both read+# `tenant_id` and `executed_by` from the request body, so a caller declared+# their own identity and their own tenant.+#+# The read routes are included deliberately rather than left open: they take+# `tenant_id` as a plain query parameter, so an unauthenticated caller could+# enumerate any tenant's execution history and coverage posture.+#+# `/health` and the probes in `app/_health.py` are registered on the app, not+# this router, so they stay reachable for orchestrators.+router = APIRouter(dependencies=[Depends(require_service_auth)])# ---------------------------------------------------------------------------# Database helpersdiff --git a/services/purple-team/app/security/__init__.py b/services/purple-team/app/security/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/purple-team/app/security/service_auth.py b/services/purple-team/app/security/service_auth.pynew file mode 100644index 000000000..9bf04204a--- /dev/null+++ b/services/purple-team/app/security/service_auth.py@@ -0,0 +1,83 @@+"""Service-to-service bearer auth for mutating routes.++Vendored byte-identical into each Python service that needs it, following the+same convention as ``app/core/cors.py``. Keep the copies in sync.++Why this exists+---------------+Several backend services shipped with every route reachable without any+credential at all. The worst case was ``purple-team``'s ``POST /caldera/run``,+which starts a real adversary-emulation operation against live hosts and read+the caller's ``tenant_id`` and ``executed_by`` straight out of the request body+— so the caller declared their own identity and their own tenant.++These services are not reachable from the browser (the web app only proxies to+api, agents, enrichment, fusion, osquery-tls and realtime), so they are+service-to-service surfaces and a shared bearer token is the right shape. They+fail closed: without a configured token a production deployment answers 503+rather than serving the route openly.++Deliberately NOT applied to ``services/mesh``, which is a federated community+hub that is public by design and protected instead by Ed25519 signature+verification and k-anonymity.++Configuration+-------------+``AISOC_SERVICE_TOKEN``+ Shared secret presented as ``Authorization: Bearer <token>`` by callers.+``AISOC_<SERVICE>_SERVICE_TOKEN``+ Optional per-service override, e.g. ``AISOC_PURPLE_TEAM_SERVICE_TOKEN``.+``AISOC_DEV_MODE``+ When set and no token is configured, requests are allowed through so a+ local ``docker compose up`` still works. This mirrors the single canonical+ dev-mode flag used across the platform; it is asserted off in production by+ ``tests/test_security_defaults.py``.+"""++from __future__ import annotations++import hmac+import os++from fastapi import Header, HTTPException, status++#: Set by each vendored copy so the per-service override resolves.+SERVICE_NAME = "PURPLE_TEAM"++_TRUTHY = {"1", "true", "yes", "on"}+++def _dev_mode() -> bool:+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY+++def resolve_token() -> str:+ """Per-service override wins, then the shared platform token."""+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()+++async def require_service_auth(authorization: str | None = Header(default=None)) -> None:+ """FastAPI dependency. Fails closed unless explicitly in dev mode."""+ token = resolve_token()+ if not token:+ if _dev_mode():+ return+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=(+ "service auth is not configured; set AISOC_SERVICE_TOKEN "+ f"(or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) before exposing this service"+ ),+ )++ expected = f"Bearer {token}"+ # compare_digest rather than == so the comparison is not timing-variable.+ if not authorization or not hmac.compare_digest(authorization, expected):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing service token",+ headers={"WWW-Authenticate": "Bearer"},+ )diff --git a/services/purple-team/tests/test_service_auth.py b/services/purple-team/tests/test_service_auth.pynew file mode 100644index 000000000..67b56e135--- /dev/null+++ b/services/purple-team/tests/test_service_auth.py@@ -0,0 +1,132 @@+"""Default-deny on the purple-team API.++This service executes adversary emulation. Before this gate existed, every+route answered without a credential, including `POST /caldera/run`, which+starts a real Caldera operation against live hosts, and which took `tenant_id`+and `executed_by` from the request body so the caller declared their own+identity and tenant.++These tests pin the three properties that matter:++ * unconfigured in production -> 503, never open+ * configured but unauthenticated -> 401+ * a wrong token -> 401++They deliberately assert on the *auth* outcome only. A correctly authenticated+request may still fail downstream on a database or Caldera connection, which+is why the positive case asserts "not 401/503" rather than a 2xx.+"""++from __future__ import annotations++import pytest+from app.security.service_auth import require_service_auth, resolve_token+from fastapi import HTTPException++TOKEN = "test-service-token-value"++[email protected](autouse=True)+def _clean_env(monkeypatch: pytest.MonkeyPatch):+ for var in (+ "AISOC_SERVICE_TOKEN",+ "AISOC_PURPLE_TEAM_SERVICE_TOKEN",+ "AISOC_DEV_MODE",+ ):+ monkeypatch.delenv(var, raising=False)+++async def _call(authorization: str | None):+ return await require_service_auth(authorization=authorization)+++async def test_unconfigured_in_production_fails_closed():+ """No token and no dev mode must be a 503, not an open door."""+ with pytest.raises(HTTPException) as exc:+ await _call(None)+ assert exc.value.status_code == 503+++async def test_unconfigured_in_dev_mode_is_allowed(monkeypatch: pytest.MonkeyPatch):+ """`docker compose up` with no token still works locally."""+ monkeypatch.setenv("AISOC_DEV_MODE", "1")+ assert await _call(None) is None+++async def test_missing_header_is_rejected(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", TOKEN)+ with pytest.raises(HTTPException) as exc:+ await _call(None)+ assert exc.value.status_code == 401+++ "header",+ [+ "Bearer wrong-token",+ TOKEN, # right value, missing the scheme+ f"bearer {TOKEN}", # scheme is case-sensitive here on purpose+ f"Bearer {TOKEN} ", # trailing whitespace must not pass+ "",+ ],+)+async def test_bad_authorization_values_are_rejected(monkeypatch: pytest.MonkeyPatch, header: str):+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", TOKEN)+ with pytest.raises(HTTPException) as exc:+ await _call(header)+ assert exc.value.status_code == 401+++async def test_correct_token_passes(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", TOKEN)+ assert await _call(f"Bearer {TOKEN}") is None+++async def test_dev_mode_does_not_bypass_a_configured_token(+ monkeypatch: pytest.MonkeyPatch,+):+ """Dev mode is a fallback for *no* token, not a master key.++ Otherwise anyone who can set an env var on the container downgrades a+ configured deployment to open.+ """+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", TOKEN)+ monkeypatch.setenv("AISOC_DEV_MODE", "1")+ with pytest.raises(HTTPException) as exc:+ await _call("Bearer nope")+ assert exc.value.status_code == 401+++def test_per_service_override_wins(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "shared")+ monkeypatch.setenv("AISOC_PURPLE_TEAM_SERVICE_TOKEN", "specific")+ assert resolve_token() == "specific"+++def test_shared_token_used_when_no_override(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "shared")+ assert resolve_token() == "shared"+++def test_every_api_route_requires_auth():+ """The dependency is on the router, so no route can be added without it.++ A per-route decorator would let the next contributor forget one; asserting+ on the router's dependency list is what makes that impossible.+ """+ from app.api.routes import router++ assert router.dependencies, "purple-team router must carry a default-deny dependency"+ names = {getattr(d.dependency, "__name__", "") for d in router.dependencies}+ assert "require_service_auth" in names++ # And nothing slipped in with its own empty dependency override.+ for route in router.routes:+ deps = {getattr(d.dependency, "__name__", "") for d in getattr(route, "dependencies", [])}+ assert "require_service_auth" not in deps or deps, route.pathdiff --git a/services/ueba/app/api/routes.py b/services/ueba/app/api/routes.pyindex 526fc6b89..00ad3b054 100644--- a/services/ueba/app/api/routes.py+++ b/services/ueba/app/api/routes.py@@ -13,9 +13,10 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asynfrom app.core.config import settingsfrom app.models.ueba import EntityBaseline, PeerGroup, UEBAAnomaly+from app.security.service_auth import require_service_authfrom app.services.scoring import ScoringService-router = APIRouter(prefix="/api/v1/ueba", tags=["ueba"])+router = APIRouter(prefix="/api/v1/ueba", tags=["ueba"], dependencies=[Depends(require_service_auth)])# ---------------------------------------------------------------------------# DB dependencydiff --git a/services/ueba/app/security/__init__.py b/services/ueba/app/security/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/ueba/app/security/service_auth.py b/services/ueba/app/security/service_auth.pynew file mode 100644index 000000000..5ca5ab712--- /dev/null+++ b/services/ueba/app/security/service_auth.py@@ -0,0 +1,83 @@+"""Service-to-service bearer auth for mutating routes.++Vendored byte-identical into each Python service that needs it, following the+same convention as ``app/core/cors.py``. Keep the copies in sync.++Why this exists+---------------+Several backend services shipped with every route reachable without any+credential at all. The worst case was ``purple-team``'s ``POST /caldera/run``,+which starts a real adversary-emulation operation against live hosts and read+the caller's ``tenant_id`` and ``executed_by`` straight out of the request body+— so the caller declared their own identity and their own tenant.++These services are not reachable from the browser (the web app only proxies to+api, agents, enrichment, fusion, osquery-tls and realtime), so they are+service-to-service surfaces and a shared bearer token is the right shape. They+fail closed: without a configured token a production deployment answers 503+rather than serving the route openly.++Deliberately NOT applied to ``services/mesh``, which is a federated community+hub that is public by design and protected instead by Ed25519 signature+verification and k-anonymity.++Configuration+-------------+``AISOC_SERVICE_TOKEN``+ Shared secret presented as ``Authorization: Bearer <token>`` by callers.+``AISOC_<SERVICE>_SERVICE_TOKEN``+ Optional per-service override, e.g. ``AISOC_PURPLE_TEAM_SERVICE_TOKEN``.+``AISOC_DEV_MODE``+ When set and no token is configured, requests are allowed through so a+ local ``docker compose up`` still works. This mirrors the single canonical+ dev-mode flag used across the platform; it is asserted off in production by+ ``tests/test_security_defaults.py``.+"""++from __future__ import annotations++import hmac+import os++from fastapi import Header, HTTPException, status++#: Set by each vendored copy so the per-service override resolves.+SERVICE_NAME = "UEBA"++_TRUTHY = {"1", "true", "yes", "on"}+++def _dev_mode() -> bool:+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY+++def resolve_token() -> str:+ """Per-service override wins, then the shared platform token."""+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()+++async def require_service_auth(authorization: str | None = Header(default=None)) -> None:+ """FastAPI dependency. Fails closed unless explicitly in dev mode."""+ token = resolve_token()+ if not token:+ if _dev_mode():+ return+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=(+ "service auth is not configured; set AISOC_SERVICE_TOKEN "+ f"(or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) before exposing this service"+ ),+ )++ expected = f"Bearer {token}"+ # compare_digest rather than == so the comparison is not timing-variable.+ if not authorization or not hmac.compare_digest(authorization, expected):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing service token",+ headers={"WWW-Authenticate": "Bearer"},+ )