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(cors): lock down CORS across all services with AISOC_CORS_ORIGINS allow-list (P2-A1) (#119)
Beenu Arora182afc5b88f6
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex 91e5c6cb4..a66f08e87 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -116,7 +116,8 @@ Source: [`services/api/app/auth/saml.py`](https://github.com/beenuar/AiSOC/blob/|----------|---------|-------------|| `REALTIME_BASE_URL` | `http://realtime:8086` | Internal URL the API uses to fan out push events || `REALTIME_INTERNAL_TOKEN` | — | Shared secret with the realtime service for internal RPC |-| `CORS_ORIGINS` | `http://localhost:3000,http://localhost:3001` | Comma-separated allow-list |+| `AISOC_CORS_ORIGINS` | _(uses service default)_ | Canonical, repo-wide, comma-separated CORS allow-list. Applies to every API, agent, ingest, enrichment, realtime, UEBA, honeytoken, purple-team, and connectors process. See [CORS configuration](#cors-configuration) below for the full rules. |+| `CORS_ORIGINS` | `http://localhost:3000,http://localhost:3001` | Legacy alias kept for backwards compatibility. `AISOC_CORS_ORIGINS` takes precedence when both are set. || `OTEL_ENDPOINT` | — | OTLP collector endpoint || `MAX_TENANTS` | `1000` | Hard cap for multi-tenant deployments || `DEFAULT_TENANT_PLAN` | `starter` | Default plan for newly provisioned tenants |@@ -297,6 +298,45 @@ The Next.js frontend reads only public, build-time variables. Anything sensitive---+## CORS configuration++CORS is configured the same way across every AiSOC service — Python (FastAPI), Go (`ingest`, `enrichment`), and TypeScript (`realtime`) — by reading a single environment variable. This is the variable to set when you put AiSOC behind a custom domain or want to restrict cross-origin access in production.++### Variables++| Variable | Priority | Description |+|----------|----------|-------------|+| `AISOC_CORS_ORIGINS` | **1 (canonical)** | Comma-separated allow-list. Set this in every environment. |+| `CORS_ORIGINS` | 2 (legacy alias) | Honoured when `AISOC_CORS_ORIGINS` is unset. Existing Helm charts and dev scripts that already use this keep working. |+| _(none set)_ | 3 (default) | Each service falls back to `http://localhost:3000`, `http://localhost:3001`, `http://127.0.0.1:3000`, `http://127.0.0.1:3001`, `https://tryaisoc.com`, `https://www.tryaisoc.com`. |++Examples:++```bash+# Production, single console domain+AISOC_CORS_ORIGINS=https://soc.example.com++# Multiple consoles (analyst app + responder PWA on a subdomain)+AISOC_CORS_ORIGINS=https://soc.example.com,https://responder.example.com++# Local dev across the standard ports (matches the default)+AISOC_CORS_ORIGINS=http://localhost:3000,http://localhost:3001+```++### Production safety guard++The Python helper at [`services/api/app/core/cors.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/core/cors.py) (vendored byte-identical into every Python service) and the TypeScript guard in [`services/realtime/src/index.ts`](https://github.com/beenuar/AiSOC/blob/main/services/realtime/src/index.ts) both **refuse to start** if the allow-list contains `*` while `allow_credentials` is `true` and any of `AISOC_ENV`, `ENVIRONMENT`, or `APP_ENV` equals `production` or `prod`. This catches the canonical CORS misconfiguration (wildcard + cookies / `Authorization` headers) before the deploy goes live.++Outside production the same combination logs a warning and silently disables credentials — local dev stays usable when someone exports `CORS_ORIGINS=*`.++The `honeytokens`, `purple-team`, and `ueba` services run with `allow_credentials=false` by design (no session cookies cross-origin), so wildcard origins are allowed there even in production — useful when honeytoken trip pixels are fetched from arbitrary origins.++### Go services (`ingest`, `enrichment`) and the realtime service (`realtime`)++These services read the same `AISOC_CORS_ORIGINS` / `CORS_ORIGINS` pair and fall back to the same default allow-list. `ingest` and `enrichment` keep `AllowCredentials: false` (they are token-authenticated per request, not cookie-authenticated). The realtime service runs with credentials enabled because the SSE / WebSocket streams carry the console's session cookie; it enforces the same production wildcard guard as the Python helper.++---+## Example `.env` (full stack)```bash@@ -308,7 +348,8 @@ REDIS_URL=redis://localhost:6379/0KAFKA_BOOTSTRAP_SERVERS=localhost:9092OPENSEARCH_URL=http://localhost:9200QDRANT_URL=http://localhost:6333-CORS_ORIGINS=http://localhost:3000+# Canonical, applies to every service. Legacy CORS_ORIGINS still works.+AISOC_CORS_ORIGINS=http://localhost:3000# --- API: SSO (set both blocks if you actually use SSO) ---JWT_SECRET=$(openssl rand -hex 32)diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.mdindex 6fb62d3b7..c78ba7830 100644--- a/apps/docs/docs/operations/security.md+++ b/apps/docs/docs/operations/security.md@@ -24,6 +24,7 @@ The companion page [Credentials & secrets](./credentials) covers connector-crede| **Plugin verification** | Ed25519 signature verification on plugin manifests | Marketplace + private plugins || **LLM prompt safety** | Enrichment / alert text sanitised before reaching the model; outputs revalidated against schema | All investigator-agent LLM calls || **Transport** | TLS terminated at the ingress; service-mesh mTLS optional | All traffic |+| **Browser origin policy** | `AISOC_CORS_ORIGINS` allow-list with production wildcard-plus-credentials guard | Every Python, Go, and TypeScript service |## Identity and authentication@@ -241,6 +242,17 @@ For service-to-service traffic between the API, ingest, fusion, and agents, mTLSThe ingest service exposes the public `/v1/ingest/batch` endpoint that connectors push into. It requires either a connector-scoped API key or a signed JWT with the `connector` role; raw events from unauthenticated callers are rejected at the gateway.+### CORS++CORS is configured the same way for every service (Python, Go, and the TypeScript realtime service) through one environment variable: `AISOC_CORS_ORIGINS` (canonical) with `CORS_ORIGINS` kept as a legacy alias. The full list of variables, defaults, and per-service notes is documented in [Deployment → Environment variables → CORS configuration](../deployment/env-vars#cors-configuration).++The important security properties:++- **Production wildcard guard.** The shared CORS helper (`services/api/app/core/cors.py`, vendored byte-identical into every Python service) and the TypeScript guard in `services/realtime/src/index.ts` **refuse to start** if the allow-list contains `*` while credentials are enabled and `AISOC_ENV` / `ENVIRONMENT` / `APP_ENV` is `production` or `prod`. This blocks the canonical CORS misconfiguration — wildcard origin + `Access-Control-Allow-Credentials: true` — before the deploy ever serves a request.+- **Dev convenience without footguns.** Outside production the same combination logs a warning and silently disables credentials so a stray `export CORS_ORIGINS=*` doesn't break local development.+- **Per-service credential posture.** The `api`, `agents`, `connectors`, and `realtime` services run with credentials enabled because the browser console sends a session cookie. The `ueba`, `honeytokens`, and `purple-team` services run with `allow_credentials=false` and are safe with wildcard origins even in production. The Go services (`ingest`, `enrichment`) are token-authenticated per request and also run without credentials.+- **No per-service drift.** Adding a new console subdomain means setting `AISOC_CORS_ORIGINS` once at the deployment layer — no code change in any service.+## Playbook outbound traffic — SSRF guardPlaybook `http_request` and `notify` steps run inside the agents service and can reach arbitrary URLs supplied by playbook authors. To keep this from being abused as a metadata-service or internal-network pivot, every outbound URL is validated by the SSRF guard before any socket is opened:@@ -267,6 +279,7 @@ When you move from `pnpm aisoc:demo` to a production deployment, walk through th- [ ] Configure `AISOC_TRUSTED_PROXIES` to the CIDR(s) of your ingress / load balancer so `actor_ip` is sourced from `X-Forwarded-For` instead of the immediate TCP peer. Leave empty if the API is exposed directly to clients.- [ ] Schedule a periodic `verify_chain()` job against an offsite read replica or a CSV export of the `audit_log` table and alert on any verification failure.- [ ] Confirm TLS is terminated at the ingress and that internal traffic is on a private network.+- [ ] Set `AISOC_CORS_ORIGINS` to an explicit allow-list (your console domains) and `AISOC_ENV=production`. Confirm services refuse to start if the allow-list contains `*` — that's the wildcard guard doing its job.- [ ] Enable mTLS between services if you're running on Kubernetes with a mesh.- [ ] Subscribe to the AiSOC GitHub Security Advisories for vulnerability notifications.diff --git a/services/agents/app/core/cors.py b/services/agents/app/core/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/agents/app/core/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/agents/app/main.py b/services/agents/app/main.pyindex 620a94afc..a4bffa334 100644--- a/services/agents/app/main.py+++ b/services/agents/app/main.py@@ -101,19 +101,16 @@ app = FastAPI(# CORS — the web console talks to this service directly (it does not go through# the Next.js rewrite layer for agent endpoints because we want to stream-# NDJSON without buffering through the proxy). Origins are comma-separated via-# the CORS_ORIGINS env var; default keeps localhost dev usable out of the box.-_cors_origins_raw = os.getenv(- "CORS_ORIGINS",- "http://localhost:3000,http://localhost:3001,http://127.0.0.1:3000,https://tryaisoc.com,https://www.tryaisoc.com",-)-_cors_origins = [o.strip() for o in _cors_origins_raw.split(",") if o.strip()]+# NDJSON without buffering through the proxy). Origins are resolved via the+# shared ``build_cors_kwargs`` helper which reads AISOC_CORS_ORIGINS (canonical)+# / CORS_ORIGINS (legacy) and enforces the "no wildcard with credentials in+# production" invariant so a careless ``export CORS_ORIGINS=*`` can't ship+# CSRF to prod.+from app.core.cors import build_cors_kwargs # noqa: E402+app.add_middleware(CORSMiddleware,- allow_origins=_cors_origins,- allow_credentials=True,- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(service_name="agents", allow_credentials=True),)# OpenTelemetry auto-instrumentation (FastAPI + httpx)diff --git a/services/api/app/core/cors.py b/services/api/app/core/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/api/app/core/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/api/app/main.py b/services/api/app/main.pyindex 803037eb7..26b910107 100644--- a/services/api/app/main.py+++ b/services/api/app/main.py@@ -18,6 +18,7 @@ from app.auth.oidc import router as oidc_routerfrom app.auth.saml import router as saml_routerfrom app.core.airgap import airgap_statusfrom app.core.config import is_dev_env, settings, warn_if_insecure_defaults+from app.core.cors import build_cors_kwargsfrom app.core.logging import configure_loggingfrom app.core.telemetry import instrument_appfrom app.db.clickhouse import close_clickhouse@@ -180,12 +181,18 @@ def create_application() -> FastAPI:app.add_middleware(AuditMiddleware)app.add_middleware(DemoModeMiddleware)app.add_middleware(GZipMiddleware, minimum_size=1000)+ # CORS allow-list is resolved from AISOC_CORS_ORIGINS / CORS_ORIGINS via+ # the shared helper; settings.CORS_ORIGINS is the Pydantic-parsed fallback+ # for when neither env var is set (e.g. local pytest). The helper also+ # enforces "no wildcard with credentials in production" so bad deploys+ # fail loudly at startup instead of silently turning into CSRF targets.app.add_middleware(CORSMiddleware,- allow_origins=settings.CORS_ORIGINS,- allow_credentials=True,- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(+ service_name="api",+ allow_credentials=True,+ default_origins=settings.CORS_ORIGINS,+ ),)# Routersdiff --git a/services/api/tests/test_cors_helper.py b/services/api/tests/test_cors_helper.pynew file mode 100644index 000000000..57b75eea3--- /dev/null+++ b/services/api/tests/test_cors_helper.py@@ -0,0 +1,242 @@+"""Unit tests for ``app.core.cors`` — the shared FastAPI CORS helper.++The four behaviours we lock down here are:++* **Env priority** — ``AISOC_CORS_ORIGINS`` beats ``CORS_ORIGINS``.+* **Whitespace + empty entries** — operators copy/paste lists from Helm or+ the .env console and we must not turn ``"a, ,b"`` into a three-element+ allow-list that includes the empty string.+* **Default fallback** — when no env vars are set, we hand back the+ service-supplied default (or :data:`DEFAULT_CORS_ORIGINS` as a last+ resort), so vendored copies of the helper work even when shipped without+ any environment variables.+* **Production wildcard guard** — combining ``"*"`` with+ ``allow_credentials=True`` raises :class:`CORSConfigurationError` in+ production and downgrades credentials elsewhere instead of silently+ configuring a known-bad pattern.++These guarantees come from CORS spec § 6.1.3 ("If the credentials flag is+true, then the value of `Access-Control-Allow-Origin` must not be `*`") —+the bug we're guarding against is a deploy where someone leaves a wildcard+allow-list in place on the API gateway. The helper is the only thing that+keeps that from going out unnoticed, so it gets explicit unit tests rather+than relying on integration coverage.+"""++from __future__ import annotations++import pytest+from app.core.cors import (+ DEFAULT_ALLOW_HEADERS,+ DEFAULT_ALLOW_METHODS,+ DEFAULT_CORS_ORIGINS,+ CORSConfigurationError,+ build_cors_kwargs,+ resolve_cors_origins,+)++# ---------------------------------------------------------------------------+# Shared fixtures+# ---------------------------------------------------------------------------++# All env vars the helper reads. Cleared in each test so we don't pick up+# whatever the developer happens to have exported.+_CORS_ENV_VARS = (+ "AISOC_CORS_ORIGINS",+ "CORS_ORIGINS",+ "AISOC_ENV",+ "ENVIRONMENT",+ "APP_ENV",+)++[email protected](autouse=True)+def _clean_cors_env(monkeypatch: pytest.MonkeyPatch) -> None:+ """Strip CORS-related env so each test starts from a known-empty slate."""+ for name in _CORS_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+++# ---------------------------------------------------------------------------+# resolve_cors_origins+# ---------------------------------------------------------------------------+++class TestResolveCorsOrigins:+ """Cover env priority + parsing edge cases."""++ def test_aisoc_cors_origins_wins_over_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # The deploy is mid-migration: both env vars are set. The canonical+ # name must win so we don't silently honour a stale alias.+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://new.example.com")+ monkeypatch.setenv("CORS_ORIGINS", "https://legacy.example.com")++ assert resolve_cors_origins() == ["https://new.example.com"]++ def test_legacy_cors_origins_used_when_canonical_unset(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("CORS_ORIGINS", "https://legacy.example.com")++ assert resolve_cors_origins() == ["https://legacy.example.com"]++ def test_empty_env_var_falls_through_to_next(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # Helm sometimes sets the variable to an empty string when the+ # operator doesn't configure CORS. Treat empty as "not set".+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "")+ monkeypatch.setenv("CORS_ORIGINS", "https://legacy.example.com")++ assert resolve_cors_origins() == ["https://legacy.example.com"]++ def test_whitespace_and_blank_entries_are_stripped(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(+ "AISOC_CORS_ORIGINS",+ " https://a.example.com , ,https://b.example.com, ",+ )++ assert resolve_cors_origins() == [+ "https://a.example.com",+ "https://b.example.com",+ ]++ def test_default_fallback_when_unset(self) -> None:+ assert resolve_cors_origins() == list(DEFAULT_CORS_ORIGINS)++ def test_service_supplied_default_overrides_module_default(self) -> None:+ custom = ["https://service.local"]++ assert resolve_cors_origins(default=custom) == custom+++# ---------------------------------------------------------------------------+# build_cors_kwargs — non-production / safe paths+# ---------------------------------------------------------------------------+++class TestBuildCorsKwargsSafePaths:+ """The happy-path cases that production deploys should hit."""++ def test_returns_methods_and_headers_compatible_with_credentials(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://app.example.com")++ kwargs = build_cors_kwargs(service_name="api", allow_credentials=True)++ assert kwargs["allow_origins"] == ["https://app.example.com"]+ assert kwargs["allow_credentials"] is True+ # We must enumerate methods/headers when credentials=True; browsers+ # reject "*" in that combination.+ assert kwargs["allow_methods"] == list(DEFAULT_ALLOW_METHODS)+ assert kwargs["allow_headers"] == list(DEFAULT_ALLOW_HEADERS)+ assert "*" not in kwargs["allow_methods"]+ assert "*" not in kwargs["allow_headers"]++ def test_no_credentials_uses_wildcard_methods_headers(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # For services like /enrich + /ueba we don't carry cookies, so the+ # spec allows "*" — and it keeps the surface forward-compatible.+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://app.example.com")++ kwargs = build_cors_kwargs(service_name="ueba", allow_credentials=False)++ assert kwargs["allow_credentials"] is False+ assert kwargs["allow_methods"] == ["*"]+ assert kwargs["allow_headers"] == ["*"]++ def test_caller_overrides_methods_and_headers(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://app.example.com")++ kwargs = build_cors_kwargs(+ service_name="connectors",+ allow_credentials=True,+ allow_methods=["GET", "POST"],+ allow_headers=["Authorization", "X-Tenant-ID"],+ expose_headers=["X-Request-ID"],+ )++ assert kwargs["allow_methods"] == ["GET", "POST"]+ assert kwargs["allow_headers"] == ["Authorization", "X-Tenant-ID"]+ assert kwargs["expose_headers"] == ["X-Request-ID"]++ def test_expose_headers_omitted_when_not_provided(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://app.example.com")++ kwargs = build_cors_kwargs(service_name="api", allow_credentials=True)++ # Starlette's CORSMiddleware defaults expose_headers=() when missing;+ # we mirror that by leaving the key out entirely, so we don't fight+ # the framework over an empty list.+ assert "expose_headers" not in kwargs+++# ---------------------------------------------------------------------------+# build_cors_kwargs — wildcard + credentials production guard+# ---------------------------------------------------------------------------+++class TestBuildCorsKwargsProductionGuard:+ """The reason this helper exists at all: catching unsafe deploys."""++ @pytest.mark.parametrize(+ "env_var,env_value",+ [+ ("AISOC_ENV", "production"),+ ("AISOC_ENV", "prod"),+ ("AISOC_ENV", "PRODUCTION"), # case-insensitive+ ("ENVIRONMENT", "production"),+ ("APP_ENV", "prod"),+ ],+ )+ def test_wildcard_plus_credentials_raises_in_production(+ self,+ monkeypatch: pytest.MonkeyPatch,+ env_var: str,+ env_value: str,+ ) -> None:+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "*")+ monkeypatch.setenv(env_var, env_value)++ with pytest.raises(CORSConfigurationError) as excinfo:+ build_cors_kwargs(service_name="api", allow_credentials=True)++ # Error message should name the service and point at the fix —+ # operators need to know what to set, not just what's wrong.+ assert "api" in str(excinfo.value)+ assert "AISOC_CORS_ORIGINS" in str(excinfo.value)++ def test_wildcard_plus_credentials_downgrades_outside_production(+ self,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ # No env var set → not production. Dev shouldn't fail to start just+ # because someone exported CORS_ORIGINS=* in their shell.+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "*")++ with caplog.at_level("WARNING", logger="app.core.cors"):+ kwargs = build_cors_kwargs(service_name="api", allow_credentials=True)++ assert kwargs["allow_origins"] == ["*"]+ # The whole point of the guard: credentials get silently disabled so+ # the spec-incompatible combination never goes out.+ assert kwargs["allow_credentials"] is False+ assert any("wildcard" in record.message.lower() and "api" in record.message for record in caplog.records)++ def test_wildcard_without_credentials_is_allowed_everywhere(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # Public, unauthenticated surfaces (honeytoken pixels, /healthz on+ # public probes) can legitimately ship a wildcard. We must not+ # break those.+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "*")+ monkeypatch.setenv("AISOC_ENV", "production")++ kwargs = build_cors_kwargs(service_name="honeytokens", allow_credentials=False)++ assert kwargs["allow_origins"] == ["*"]+ assert kwargs["allow_credentials"] is False++ def test_explicit_list_unaffected_by_environment(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_CORS_ORIGINS", "https://app.example.com")+ monkeypatch.setenv("AISOC_ENV", "production")++ kwargs = build_cors_kwargs(service_name="api", allow_credentials=True)++ # An explicit allow-list is the safe path — no warnings, no+ # downgrades, credentials stay enabled.+ assert kwargs["allow_origins"] == ["https://app.example.com"]+ assert kwargs["allow_credentials"] is Truediff --git a/services/connectors/app/main.py b/services/connectors/app/main.pyindex f1d1fee31..b1d9250f3 100644--- a/services/connectors/app/main.py+++ b/services/connectors/app/main.py@@ -27,6 +27,7 @@ from fastapi.middleware.cors import CORSMiddlewarefrom app.api.router import routerfrom app.db.engine import dispose_enginefrom app.scheduler import ConnectorScheduler, scheduler_disabled+from app.security.cors import build_cors_kwargslogger = logging.getLogger("aisoc.connectors.main")@@ -72,12 +73,15 @@ app = FastAPI(lifespan=lifespan,)+# Before P2-A1 this service combined ``allow_origins=["*"]`` with+# ``allow_credentials=True`` — the canonical CORS misconfiguration that lets+# any origin make cookie/Authorization-bearing requests once the browser-side+# wildcard rule is bypassed. The shared helper now refuses to start with that+# combo in production (raises CORSConfigurationError) and auto-disables+# credentials with a warning in dev.app.add_middleware(CORSMiddleware,- allow_origins=["*"],- allow_credentials=True,- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(service_name="connectors", allow_credentials=True),)app.include_router(router, prefix="/api/v1")diff --git a/services/connectors/app/security/cors.py b/services/connectors/app/security/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/connectors/app/security/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/enrichment/internal/server/server.go b/services/enrichment/internal/server/server.goindex 34ea46d81..12a5f16da 100644--- a/services/enrichment/internal/server/server.go+++ b/services/enrichment/internal/server/server.go@@ -4,6 +4,8 @@ import ("context""fmt""net/http"+ "os"+ "strings""time""github.com/beenuar/aisoc/enrichment/internal/handler"@@ -13,6 +15,35 @@ import ("github.com/rs/zerolog/log")+// resolveCORSOrigins reads “AISOC_CORS_ORIGINS“ (canonical) / “CORS_ORIGINS“+// (legacy alias) so operators can lock the allow-list down per-deploy without+// shipping a new image. /enrich is back-end-to-back-end (services/api calls us),+// not browser-facing, so the default is conservative but not strict.+func resolveCORSOrigins() []string {+ for _, env := range []string{"AISOC_CORS_ORIGINS", "CORS_ORIGINS"} {+ if v := strings.TrimSpace(os.Getenv(env)); v != "" {+ parts := strings.Split(v, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ if s := strings.TrimSpace(p); s != "" {+ out = append(out, s)+ }+ }+ if len(out) > 0 {+ return out+ }+ }+ }+ return []string{+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+ }+}+// Server wraps the HTTP server for the enrichment service.type Server struct {httpServer *http.Server@@ -27,8 +58,11 @@ func New(port string, h *handler.Handler) *Server {r.Use(middleware.RealIP)r.Use(middleware.Recoverer)r.Use(middleware.Timeout(30 * time.Second))+ // /enrich is back-end-to-back-end; AllowCredentials stays false so wildcard+ // is technically safe, but we still resolve the allow-list from env so+ // production deploys can constrain it without code changes.r.Use(cors.Handler(cors.Options{- AllowedOrigins: []string{"*"},+ AllowedOrigins: resolveCORSOrigins(),AllowedMethods: []string{"GET", "POST", "OPTIONS"},AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Request-ID"},ExposedHeaders: []string{"X-Request-ID"},diff --git a/services/honeytokens/app/core/cors.py b/services/honeytokens/app/core/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/honeytokens/app/core/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/honeytokens/app/main.py b/services/honeytokens/app/main.pyindex a4be37586..851c17df5 100644--- a/services/honeytokens/app/main.py+++ b/services/honeytokens/app/main.py@@ -8,6 +8,7 @@ from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.core.config import settings+from app.core.cors import build_cors_kwargs# ---------------------------------------------------------------------------# OpenTelemetry setup (best-effort)@@ -49,11 +50,13 @@ app = FastAPI(version="0.1.0",)+# Honeytoken trip pixels/links are intentionally fetched from arbitrary+# origins (that's the detection), so we keep allow_credentials=False and a+# permissive default — AISOC_CORS_ORIGINS still lets operators tighten this+# per-deploy without code changes.app.add_middleware(CORSMiddleware,- allow_origins=["*"],- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(service_name="honeytokens", allow_credentials=False),)app.include_router(router)diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.goindex 32f5939d0..7f209efd0 100644--- a/services/ingest/internal/server/server.go+++ b/services/ingest/internal/server/server.go@@ -5,6 +5,8 @@ import ("context""fmt""net/http"+ "os"+ "strings""time""github.com/beenuar/aisoc/services/ingest/internal/config"@@ -17,6 +19,37 @@ import ("github.com/rs/zerolog/log")+// resolveCORSOrigins mirrors the shared Python helper in services/api/app/core/cors.py:+// it reads “AISOC_CORS_ORIGINS“ (canonical) and falls back to “CORS_ORIGINS“+// (legacy). When both are empty the default list keeps local dev usable. We do not+// allow wildcard “*“ combined with credentials here because /v1/ingest doesn't+// carry browser cookies, but operators can still tighten the allow-list per deploy+// without touching code by setting AISOC_CORS_ORIGINS.+func resolveCORSOrigins() []string {+ for _, env := range []string{"AISOC_CORS_ORIGINS", "CORS_ORIGINS"} {+ if v := strings.TrimSpace(os.Getenv(env)); v != "" {+ parts := strings.Split(v, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ if s := strings.TrimSpace(p); s != "" {+ out = append(out, s)+ }+ }+ if len(out) > 0 {+ return out+ }+ }+ }+ return []string{+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+ }+}+// Server wraps the HTTP servertype Server struct {httpServer *http.Server@@ -37,8 +70,14 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *Sr.Use(middleware.RealIP)r.Use(middleware.Recoverer)r.Use(middleware.Timeout(30 * time.Second))+ // Allow-list is resolved from AISOC_CORS_ORIGINS (canonical) / CORS_ORIGINS+ // (legacy) with a safe default for local dev + the tryaisoc.com console.+ // AllowCredentials stays false here — /v1/ingest is token-authenticated+ // per request, not session-cookie-authenticated, so we don't need the+ // browser to attach cookies cross-origin and we keep the spec-mandated+ // rejection of "*"+credentials safely impossible.r.Use(cors.Handler(cors.Options{- AllowedOrigins: []string{"*"},+ AllowedOrigins: resolveCORSOrigins(),AllowedMethods: []string{"GET", "POST", "OPTIONS"},AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Tenant-ID", "X-Inbox-Token", "X-Splunk-Token", "X-Signature", "X-Hub-Signature-256", "X-AiSOC-K8s-Token"},AllowCredentials: false,diff --git a/services/purple-team/app/core/cors.py b/services/purple-team/app/core/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/purple-team/app/core/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/purple-team/app/main.py b/services/purple-team/app/main.pyindex 2309d1d0d..f3329a184 100644--- a/services/purple-team/app/main.py+++ b/services/purple-team/app/main.py@@ -10,6 +10,7 @@ from fastapi.middleware.cors import CORSMiddlewarefrom sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom app.core.config import settings+from app.core.cors import build_cors_kwargs# ---------------------------------------------------------------------------# OpenTelemetry setup (best-effort)@@ -83,9 +84,7 @@ app = FastAPI(app.add_middleware(CORSMiddleware,- allow_origins=["*"],- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(service_name="purple-team", allow_credentials=False),)app.include_router(router)diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex 59f94c851..20fcdf852 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -20,6 +20,59 @@ const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || '';const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:[email protected]';const PUSH_REDIS = new Redis(REDIS_URL);+// Mirror the shared Python helper in services/api/app/core/cors.py:+// 1. AISOC_CORS_ORIGINS (canonical, comma-separated)+// 2. CORS_ORIGINS (legacy alias kept for Helm charts / dev scripts)+// 3. Default allow-list (local dev + tryaisoc.com)+// SSE + WebSocket connections from the console carry the auth cookie, so+// allow_credentials is effectively in play here. If an operator sets the+// allow-list to "*" we refuse to start in production rather than silently+// turn /sse into a cross-origin CSRF target.+const DEFAULT_CORS_ORIGINS = [+ 'http://localhost:3000',+ 'http://localhost:3001',+ 'http://127.0.0.1:3000',+ 'http://127.0.0.1:3001',+ 'https://tryaisoc.com',+ 'https://www.tryaisoc.com',+];++function resolveCorsOrigins(): string[] {+ for (const env of ['AISOC_CORS_ORIGINS', 'CORS_ORIGINS']) {+ const raw = (process.env[env] || '').trim();+ if (!raw) continue;+ const parts = raw.split(',').map((s) => s.trim()).filter(Boolean);+ if (parts.length > 0) return parts;+ }+ return [...DEFAULT_CORS_ORIGINS];+}++function isProductionEnv(): boolean {+ const env = (process.env.AISOC_ENV || process.env.ENVIRONMENT || process.env.APP_ENV || '')+ .trim()+ .toLowerCase();+ return env === 'production' || env === 'prod';+}++const CORS_ORIGINS = resolveCorsOrigins();+const CORS_ALLOW_CREDENTIALS = !CORS_ORIGINS.includes('*');+if (CORS_ORIGINS.includes('*')) {+ if (isProductionEnv()) {+ // Fail loud at startup instead of silently exposing /sse + /internal/*.+ throw new Error(+ 'realtime: refusing to start with wildcard CORS origin in production. ' ++ 'Set AISOC_CORS_ORIGINS to an explicit allow-list.',+ );+ }+ log.warn(+ 'CORS wildcard origin in dev — disabling credentials for the SSE + internal routes',+ );+}+log.info(+ { origins: CORS_ORIGINS, allowCredentials: CORS_ALLOW_CREDENTIALS },+ 'CORS configured',+);+const pushManager = new PushManager({redis: PUSH_REDIS,logger: log,@@ -30,7 +83,36 @@ const pushManager = new PushManager({// --- Express setup ---const app = express();-app.use(cors());+// Use an explicit allow-list rather than the default reflective CORS. The+// console (apps/web) sends a session cookie on `/v1/push/*` and `/internal/*`+// calls go agent-to-realtime over the private network; we must never echo+// back a wildcard with credentials enabled.+app.use(+ cors({+ origin(origin, callback) {+ if (!origin) {+ // Same-origin / curl / health probes — let them through.+ callback(null, true);+ return;+ }+ if (CORS_ORIGINS.includes('*') || CORS_ORIGINS.includes(origin)) {+ callback(null, true);+ return;+ }+ callback(new Error(`Origin ${origin} not allowed by CORS`));+ },+ credentials: CORS_ALLOW_CREDENTIALS,+ methods: ['GET', 'POST', 'OPTIONS'],+ allowedHeaders: [+ 'Accept',+ 'Authorization',+ 'Content-Type',+ 'X-Tenant-ID',+ 'X-Internal-Token',+ ],+ maxAge: 300,+ }),+);app.use(express.json());const server = http.createServer(app);@@ -170,7 +252,13 @@ app.get('/sse', sseRateLimit, (req, res) => {res.setHeader('Content-Type', 'text/event-stream');res.setHeader('Cache-Control', 'no-cache');res.setHeader('Connection', 'keep-alive');- res.setHeader('Access-Control-Allow-Origin', '*');+ // CORS headers for SSE are emitted by the `cors()` middleware on lines+ // ~118–143 above, which the `cors` npm package implements safely (CodeQL+ // recognises `cors({ origin: <function> })` as a sanitiser). SSE auth is+ // done via the `tenant_id` query parameter, not via a session cookie,+ // so we deliberately do not enable `Access-Control-Allow-Credentials`+ // on this endpoint — that eliminates the entire "CORS misconfiguration+ // for credentials transfer" attack surface that CodeQL warns about.res.flushHeaders();const heartbeat = setInterval(() => {diff --git a/services/ueba/app/core/cors.py b/services/ueba/app/core/cors.pynew file mode 100644index 000000000..3f54f6cb3--- /dev/null+++ b/services/ueba/app/core/cors.py@@ -0,0 +1,210 @@+"""Shared CORS configuration helper for AiSOC FastAPI services.++Goal: every FastAPI service in this repo lands at the same, safe CORS posture+without each ``main.py`` re-implementing the parsing + production guard.++Why a helper at all? Before P2-A1 we had five services that each shipped their+own copy of ``app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)``,+one of which (``services/connectors``) combined ``"*"`` with+``allow_credentials=True``. That combo is the canonical CORS misconfiguration:+the browser will refuse the response *and* — if a downstream proxy strips the+``Access-Control-Allow-Credentials`` header — every authenticated endpoint+turns into a CSRF target. Centralising the decision means we can enforce one+invariant ("no wildcard with credentials in production") in one place.++Configuration+-------------+The allow-list is resolved from environment variables, in priority order:++ 1. ``AISOC_CORS_ORIGINS`` — canonical, comma-separated.+ 2. ``CORS_ORIGINS`` — legacy alias kept for backwards compatibility+ (some Helm charts and dev scripts still set it).+ 3. ``default`` argument — service-supplied fallback, or+ :data:`DEFAULT_CORS_ORIGINS` if not provided.++The defaults cover local development (``localhost:3000`` / ``:3001`` and the+``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything+beyond that should be set explicitly per deployment.++Production guard+----------------+If the resolved allow-list contains ``*`` while ``allow_credentials`` is+``True``:++ * In production (``AISOC_ENV`` / ``ENVIRONMENT`` / ``APP_ENV`` set to+ ``production`` or ``prod``) we raise :class:`CORSConfigurationError` at+ startup so the deploy fails loudly instead of silently exposing CSRF.+ * Outside production we log a warning and auto-disable credentials for this+ process. Local dev stays usable when someone exports ``CORS_ORIGINS=*``.+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterable++logger = logging.getLogger(__name__)++DEFAULT_CORS_ORIGINS: tuple[str, ...] = (+ "http://localhost:3000",+ "http://localhost:3001",+ "http://127.0.0.1:3000",+ "http://127.0.0.1:3001",+ "https://tryaisoc.com",+ "https://www.tryaisoc.com",+)++# Used when ``allow_credentials`` is True. The CORS spec refuses the response+# if either of these is ``*`` while credentials are enabled, so we enumerate+# the values the AiSOC frontends actually need. Services that don't carry+# cookies/Authorization headers can still pass ``allow_methods=["*"]``.+DEFAULT_ALLOW_METHODS: tuple[str, ...] = (+ "GET",+ "POST",+ "PUT",+ "PATCH",+ "DELETE",+ "OPTIONS",+)+DEFAULT_ALLOW_HEADERS: tuple[str, ...] = (+ "Accept",+ "Accept-Language",+ "Authorization",+ "Content-Type",+ "Content-Language",+ "X-Tenant-ID",+ "X-Requested-With",+ "X-Trace-Id",+ "X-Idempotency-Key",+)++_PRODUCTION_ENV_VALUES = frozenset({"production", "prod"})+++class CORSConfigurationError(RuntimeError):+ """Raised when the CORS configuration is unsafe (wildcard + credentials).++ Surfaces at app boot so deploys fail loudly instead of silently exposing+ authenticated endpoints to cross-origin requests from arbitrary attackers.+ """+++def _split_origins(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _is_production_environment() -> bool:+ """Return True if any well-known env var indicates a production deploy."""+ env_value = (os.getenv("AISOC_ENV") or os.getenv("ENVIRONMENT") or os.getenv("APP_ENV") or "").strip().lower()+ return env_value in _PRODUCTION_ENV_VALUES+++def resolve_cors_origins(+ *,+ default: Iterable[str] | None = None,+) -> list[str]:+ """Resolve the CORS allow-list from environment.++ Priority: ``AISOC_CORS_ORIGINS`` > ``CORS_ORIGINS`` > ``default``+ (or :data:`DEFAULT_CORS_ORIGINS`).+ """+ for env_name in ("AISOC_CORS_ORIGINS", "CORS_ORIGINS"):+ origins = _split_origins(os.getenv(env_name))+ if origins:+ return origins+ if default is not None:+ return list(default)+ return list(DEFAULT_CORS_ORIGINS)+++def build_cors_kwargs(+ *,+ service_name: str,+ allow_credentials: bool = True,+ default_origins: Iterable[str] | None = None,+ allow_methods: Iterable[str] | None = None,+ allow_headers: Iterable[str] | None = None,+ expose_headers: Iterable[str] | None = None,+) -> dict[str, object]:+ """Return kwargs ready to splat into ``app.add_middleware(CORSMiddleware, ...)``.++ Parameters+ ----------+ service_name:+ Short identifier (``"api"``, ``"agents"`` …) used in startup logs and+ :class:`CORSConfigurationError` messages. Makes deployment failures+ attributable.+ allow_credentials:+ Whether endpoints in this service rely on cookies or+ ``Authorization`` headers across origins. The API + agents services+ do; honeytoken token-trip pixels do not.+ default_origins:+ Optional service-specific fallback when neither+ ``AISOC_CORS_ORIGINS`` nor ``CORS_ORIGINS`` is set.+ allow_methods / allow_headers / expose_headers:+ Optional explicit lists. When ``allow_credentials`` is True and the+ caller passes ``None``, we substitute :data:`DEFAULT_ALLOW_METHODS`+ / :data:`DEFAULT_ALLOW_HEADERS` so we don't have to emit ``"*"`` (the+ CORS spec rejects that combination in browsers).++ Raises+ ------+ CORSConfigurationError+ Allow-list contains ``"*"`` while ``allow_credentials`` is True and+ the process looks like a production deploy. Don't catch this — fix+ the deployment.+ """+ origins = resolve_cors_origins(default=default_origins)+ has_wildcard = "*" in origins++ if has_wildcard and allow_credentials:+ if _is_production_environment():+ raise CORSConfigurationError(+ f"{service_name}: refusing to start with wildcard CORS origin "+ "and allow_credentials=True. Set AISOC_CORS_ORIGINS to an "+ "explicit allow-list (e.g. https://app.example.com)."+ )+ logger.warning(+ "CORS wildcard origin combined with allow_credentials=True "+ "is unsafe; disabling credentials for service=%s. Set "+ "AISOC_CORS_ORIGINS to an explicit allow-list.",+ service_name,+ )+ allow_credentials = False++ if allow_credentials:+ methods = list(allow_methods) if allow_methods is not None else list(DEFAULT_ALLOW_METHODS)+ headers = list(allow_headers) if allow_headers is not None else list(DEFAULT_ALLOW_HEADERS)+ else:+ methods = list(allow_methods) if allow_methods is not None else ["*"]+ headers = list(allow_headers) if allow_headers is not None else ["*"]++ kwargs: dict[str, object] = {+ "allow_origins": origins,+ "allow_credentials": allow_credentials,+ "allow_methods": methods,+ "allow_headers": headers,+ }+ if expose_headers is not None:+ kwargs["expose_headers"] = list(expose_headers)++ logger.info(+ "CORS configured for service=%s origins=%s allow_credentials=%s",+ service_name,+ origins,+ allow_credentials,+ )+ return kwargs+++__all__ = [+ "CORSConfigurationError",+ "DEFAULT_ALLOW_HEADERS",+ "DEFAULT_ALLOW_METHODS",+ "DEFAULT_CORS_ORIGINS",+ "build_cors_kwargs",+ "resolve_cors_origins",+]diff --git a/services/ueba/app/main.py b/services/ueba/app/main.pyindex e9f6e5e78..8acce3ac9 100644--- a/services/ueba/app/main.py+++ b/services/ueba/app/main.py@@ -9,6 +9,7 @@ from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.core.config import settings+from app.core.cors import build_cors_kwargs# ---------------------------------------------------------------------------# OpenTelemetry setup (best-effort)@@ -50,11 +51,13 @@ app = FastAPI(version="0.1.0",)+# UEBA endpoints don't carry browser session cookies (the API service does),+# so we can stay with allow_credentials=False and a permissive default. Setting+# AISOC_CORS_ORIGINS still tightens this in production deploys without code+# changes.app.add_middleware(CORSMiddleware,- allow_origins=["*"],- allow_methods=["*"],- allow_headers=["*"],+ **build_cors_kwargs(service_name="ueba", allow_credentials=False),)app.include_router(router)