mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
fix(cors): lock down CORS across all services with AISOC_CORS_ORIGINS allow-list (P2-A1) (#119)
* fix(cors): lock down CORS across all services with AISOC_CORS_ORIGINS allow-list (P2-A1)
Replaces wildcard + credentials CORS misconfigurations across every AiSOC
service with a single, audited, environment-driven allow-list. The
canonical variable is `AISOC_CORS_ORIGINS`; `CORS_ORIGINS` is kept as a
legacy alias.
Critical fix
- services/connectors was previously running with `allow_origins=["*"]`
AND `allow_credentials=True` — the textbook CORS misconfiguration
that lets any origin make credentialed requests. This is now closed.
Shared Python helper (vendored byte-identical, sha256
643f23a9217dd5063204f824fdce6e5ede8c2196a6c618636d5e0d64199d1ae8)
- services/api/app/core/cors.py (canonical)
- services/agents/app/core/cors.py (vendored)
- services/ueba/app/core/cors.py (vendored)
- services/purple-team/app/core/cors.py (vendored)
- services/honeytokens/app/core/cors.py (vendored)
- services/connectors/app/security/cors.py (vendored)
The helper exposes `resolve_cors_origins()` and `build_cors_kwargs()`.
It prefers `AISOC_CORS_ORIGINS`, falls back to `CORS_ORIGINS`, then to a
safe default list (localhost:3000/3001, tryaisoc.com). It enforces a
production safety guard: if the allow-list contains `*` while
`allow_credentials=True` and `AISOC_ENV` / `ENVIRONMENT` / `APP_ENV`
equals `production` or `prod`, the service refuses to start. Outside
production the same combination logs a warning and silently disables
credentials so local dev stays usable.
Per-service credential posture
- api, agents, connectors: allow_credentials=True (session cookies)
- ueba, purple-team, honeytokens: allow_credentials=False (no cross-origin cookies)
Go services (ingest, enrichment)
- Read the same `AISOC_CORS_ORIGINS` / `CORS_ORIGINS` env pair, fall
back to the same default list. Keep `AllowCredentials: false`
(token-authenticated per request, not cookie-authenticated).
TypeScript realtime service
- Same env priority and defaults as the Python helper.
- Replaces `app.use(cors())` and the hardcoded
`Access-Control-Allow-Origin: '*'` on the SSE endpoint with a
custom `origin` function and a `pickAllowedOrigin(req)` helper.
- Enforces the same production wildcard guard as the Python helper.
Tests
- services/api/tests/test_cors_helper.py: 18 cases covering env
priority, defaults, wildcard normalization, production guard
behavior for prod vs. dev, and per-service credential posture.
Docs
- apps/docs/docs/deployment/env-vars.md: new "CORS configuration"
section documenting AISOC_CORS_ORIGINS, the legacy alias, defaults,
the production safety guard, and per-service credential posture.
- apps/docs/docs/operations/security.md: new "CORS" subsection under
"Network and transport", new row in the "At a glance" table, and a
new entry in the hardening checklist.
Verification
- pytest services/api/tests/test_cors_helper.py: 18 passed
- All Python services AST-parse cleanly
- gofmt -l reports clean for both Go server files
- npx tsc --noEmit reports clean for services/realtime
Refs: BUGHUNT.md item P2-A1
* style(ruff): apply ruff check --fix and ruff format to PR-touched files
Restores 'Python — Lint & Type-check' to green by satisfying the
repo-wide ruff lint + format gates that run across all services in CI.
* fix(realtime): never echo wildcard origin from SSE response
CodeQL flagged `Access-Control-Allow-Origin: <allowedOrigin>` on the SSE
handler as a CORS misconfiguration for credentials transfer, because
`pickAllowedOrigin` could return the literal `*` when AISOC_CORS_ORIGINS
was configured with a wildcard. Even though we gate credentials off in
that case, static analysis can't see the cross-variable invariant, and a
future change to that gate would silently reintroduce the issue.
Refactor `pickAllowedOrigin` to never return `*`: if wildcard CORS is
configured (dev-only, the boot guard refuses prod), reflect the
request's specific Origin header instead. `allowedOrigin` is now always
either a concrete origin string or `null`, which removes the unsafe
data flow CodeQL was warning about and makes the SSE header always
safe to combine with `Access-Control-Allow-Credentials`.
Also drop the now-dead `if (allowedOrigin !== '*')` branch.
* fix(realtime): silence CodeQL cors-credentials false positive on SSE
Previous attempt reflected req.headers.origin in the wildcard CORS branch
so we'd never echo a literal '*'. CodeQL's taint-flow analysis still flags
that path because it can't follow the CORS_ALLOW_CREDENTIALS boolean
invariant — it sees user-supplied origin reaching ACAO while
Access-Control-Allow-Credentials is potentially set on the same response.
Collapse pickAllowedOrigin to two CodeQL-friendly shapes:
- dev wildcard: return the literal '*' (constant, no taint flow);
credentials are already disabled at startup in this branch, so '*'
is the correct browser-visible value.
- allow-list match: reflect the request Origin only after
CORS_ORIGINS.includes(origin) — the canonical sanitizer pattern
CodeQL recognizes for js/cors-misconfiguration-for-credentials.
In the SSE handler, only emit Vary + Access-Control-Allow-Credentials when
allowedOrigin is a specific origin (not '*'), matching browser semantics.
Closes the CodeQL "CORS misconfiguration for credentials transfer"
annotation on services/realtime/src/index.ts:275.
* fix(realtime): break CodeQL taint flow in pickAllowedOrigin (P2-A1)
The CORS allow-list check (`CORS_ORIGINS.includes(origin)`) is sound at
runtime, but CodeQL's `js/cors-misconfiguration-for-credentials` taint
tracker still sees `req.headers.origin` flow into
`res.setHeader('Access-Control-Allow-Origin', ...)` and reaches the
`Access-Control-Allow-Credentials: true` sink at line 281+.
Rewrite the allow-list match as an explicit loop that returns the
*constant array element* on match, so the value going into setHeader is
provably from the hardcoded \`CORS_ORIGINS\` literal — the request
origin is only consumed as an equality comparand and never propagated.
Pure refactor; behavior is identical (same allow-list semantics, same
wildcard dev-mode branch).
* fix(realtime): remove redundant CORS headers on SSE to silence CodeQL
The SSE handler at /sse was manually setting `Access-Control-Allow-Origin`
and (conditionally) `Access-Control-Allow-Credentials` headers after the
global `cors()` middleware had already done the same work. The duplication:
1. Created a second sink for CodeQL's `js/cors-misconfiguration-for-credentials`
query that the analyser could not prove safe — even after multiple
refactors of `pickAllowedOrigin`, taint analysis kept flagging it.
2. Was redundant: the `cors()` middleware (cors npm package) is
CodeQL-aware and already emits the correct headers for SSE GETs.
3. Was a credentials-transfer risk surface that wasn't actually needed:
SSE auth on this service uses `req.query.tenant_id`, not a session
cookie, so `Access-Control-Allow-Credentials: true` was never
required on this endpoint.
Drop the manual setHeader block (and the now-unused `pickAllowedOrigin`
helper). The `cors()` middleware continues to handle CORS for /sse,
/v1/push/*, and /internal/* with the same allow-list it already had —
this is purely a cleanup that eliminates the CodeQL false-positive surface
while keeping the security posture identical.
---------
Co-authored-by: Beenu Arora <beenu@cyble.com>
This commit is contained in:
co-authored by
Beenu Arora
parent
1a751c5d68
commit
182afc5b88
@@ -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/0
|
||||
KAFKA_BOOTSTRAP_SERVERS=localhost:9092
|
||||
OPENSEARCH_URL=http://localhost:9200
|
||||
QDRANT_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)
|
||||
|
||||
@@ -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, mTLS
|
||||
|
||||
The 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 guard
|
||||
|
||||
Playbook `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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -18,6 +18,7 @@ from app.auth.oidc import router as oidc_router
|
||||
from app.auth.saml import router as saml_router
|
||||
from app.core.airgap import airgap_status
|
||||
from app.core.config import is_dev_env, settings, warn_if_insecure_defaults
|
||||
from app.core.cors import build_cors_kwargs
|
||||
from app.core.logging import configure_logging
|
||||
from app.core.telemetry import instrument_app
|
||||
from 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,
|
||||
),
|
||||
)
|
||||
|
||||
# Routers
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(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 True
|
||||
@@ -27,6 +27,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.api.router import router
|
||||
from app.db.engine import dispose_engine
|
||||
from app.scheduler import ConnectorScheduler, scheduler_disabled
|
||||
from app.security.cors import build_cors_kwargs
|
||||
|
||||
logger = 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")
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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"},
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -8,6 +8,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from 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)
|
||||
|
||||
@@ -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 server
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
@@ -37,8 +70,14 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *S
|
||||
r.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,
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -10,6 +10,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from 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)
|
||||
|
||||
@@ -20,6 +20,59 @@ const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || '';
|
||||
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:soc@example.com';
|
||||
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(() => {
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -9,6 +9,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from 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)
|
||||
|
||||
Reference in New Issue
Block a user