Skip to content

"Vibe-Trading: Your Personal Trading Agent"

harden(api): authenticate capability surfaces and enforce CSP (#961)

Dineesh D0f5ddf102a38
diff --git a/README.md b/README.md
index 4a1699d2a..4348c890d 100644
--- a/README.md
+++ b/README.md
@@ -1019,7 +1019,10 @@ vibe-trading serve --port 8899
| `GET` | `/correlation/regime` | Correlation edge-density regime timeline |
| `GET` | `/agents.json` · `POST` `/v1/query` | OpenBB Workspace bridge — registered only with the optional `openbb` extra; `/v1/query` requires auth |
-Interactive docs: `http://localhost:8899/docs`
+Interactive docs are available at `http://localhost:8899/docs` in keyless
+loopback development mode. When `API_AUTH_KEY` is configured, `/docs` and
+`/redoc` are disabled; authenticated tooling can fetch `/openapi.json` with an
+`Authorization: Bearer <key>` header.
### Security defaults
diff --git a/agent/.env.example b/agent/.env.example
index 5ee40304d..5afd52e1e 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -242,6 +242,10 @@ TUSHARE_TOKEN=your-tushare-token
# VIBE_TRADING_TRUST_DOCKER_LOOPBACK=0
# Advanced local-only opt-in: expose shell execution tools to the agent.
# VIBE_TRADING_ENABLE_SHELL_TOOLS=0
+# Ship the Content-Security-Policy as Report-Only instead of enforcing it.
+# Rollback switch only — set to 1 if a customized frontend build or a
+# proxy-injected asset is blocked by the enforcing policy.
+# VIBE_TRADING_CSP_REPORT_ONLY=0
# Optional import roots for read_document/analyze_trade_journal.
# Use comma-separated absolute paths. Defaults include agent/uploads, agent/runs,
# ./uploads, ./data, ~/.vibe-trading/uploads, and ~/.vibe-trading/imports.
diff --git a/agent/api_server.py b/agent/api_server.py
index 960ac9769..8ff2c3ac7 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -164,8 +164,9 @@ app = FastAPI(
title="Vibe-Trading API",
description="Vibe-Trading API: natural-language finance research, backtesting, and swarm workflows",
version=APP_VERSION,
- docs_url="/docs",
- redoc_url="/redoc",
+ docs_url=None, # docs/redoc/openapi re-registered behind require_auth
+ redoc_url=None, # in register_system_routes -- see the rationale there
+ openapi_url=None,
lifespan=_lifespan,
)
diff --git a/agent/src/api/security.py b/agent/src/api/security.py
index 42ff3df76..faec2058d 100644
--- a/agent/src/api/security.py
+++ b/agent/src/api/security.py
@@ -183,12 +183,16 @@ _PERMISSIONS_POLICY = (
"magnetometer=(), gyroscope=(), accelerometer=()"
)
-# Report-Only first: a later switch to enforcing mode can be validated against
-# real traffic without risking a broken app. Scoped to what the built SPA needs:
-# same-origin scripts/styles/fonts/img plus same-origin fetch & EventSource.
-# Inline styles are allowed because ECharts and React ``style={}`` props set
-# them; fonts are self-hosted (@fontsource) so no external font host is listed.
-_CSP_REPORT_ONLY = (
+# Enforced by default. Scoped to what the built SPA needs: same-origin
+# scripts/styles/fonts/img plus same-origin fetch & EventSource. Inline styles
+# are allowed because ECharts and React ``style={}`` props set them; fonts are
+# self-hosted (@fontsource) so no external font host is listed. The SPA entry is
+# an external module script and ``lib/api.ts`` fetches a same-origin base, so
+# no inline-script or cross-origin-connect allowance is needed.
+#
+# Set ``VIBE_TRADING_CSP_REPORT_ONLY=1`` to ship this Report-Only instead --
+# a rollback switch for deployments serving assets this policy does not cover.
+_CSP_POLICY = (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline'; "
@@ -200,6 +204,33 @@ _CSP_REPORT_ONLY = (
"form-action 'self'"
)
+# Swagger UI and ReDoc load their bundle and stylesheet from jsdelivr and run a
+# bootstrap block that FastAPI's ``get_swagger_ui_html`` / ``get_redoc_html``
+# hardcode inline, so the strict policy above would leave both pages blank.
+# Both routes require auth and render only the OpenAPI schema, so they get a
+# narrowly scoped exception rather than relaxing the policy app-wide. Favicons
+# are pointed at the self-hosted ``/favicon.svg`` so ``img-src`` stays tight.
+_CSP_DOCS_POLICY = (
+ "default-src 'self'; "
+ "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
+ "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
+ "img-src 'self' data:; "
+ "font-src 'self' data:; "
+ "connect-src 'self'; "
+ "frame-ancestors 'none'; "
+ "base-uri 'self'; "
+ "form-action 'self'"
+)
+
+_CSP_DOCS_PATHS = frozenset({"/docs", "/redoc"})
+
+
+def _csp_header_name() -> str:
+ """Return the CSP header to emit (enforcing unless opted out)."""
+ if get_env_config().api.vibe_trading_csp_report_only:
+ return "Content-Security-Policy-Report-Only"
+ return "Content-Security-Policy"
+
async def _apply_security_headers(request: Request, call_next):
"""Attach baseline security response headers to every response.
@@ -211,7 +242,10 @@ async def _apply_security_headers(request: Request, call_next):
"""
response = await call_next(request)
headers = response.headers
- headers.setdefault("Content-Security-Policy-Report-Only", _CSP_REPORT_ONLY)
+ policy = (
+ _CSP_DOCS_POLICY if request.url.path in _CSP_DOCS_PATHS else _CSP_POLICY
+ )
+ headers.setdefault(_csp_header_name(), policy)
headers.setdefault("X-Content-Type-Options", "nosniff")
headers.setdefault("X-Frame-Options", "DENY")
headers.setdefault("Permissions-Policy", _PERMISSIONS_POLICY)
@@ -510,7 +544,7 @@ def _default_gateway_ips() -> set[ipaddress.IPv4Address]:
def _trusted_docker_loopback_ip(ip: ipaddress._BaseAddress) -> bool:
- """Return whether an IP is the trusted Docker host gateway."""
+ """Return whether an IP is the explicitly trusted Docker host gateway."""
if not isinstance(ip, ipaddress.IPv4Address):
return False
if not get_env_config().api.vibe_trading_trust_docker_loopback:
diff --git a/agent/src/api/swarm_routes.py b/agent/src/api/swarm_routes.py
index 3990effd3..ce65d611e 100644
--- a/agent/src/api/swarm_routes.py
+++ b/agent/src/api/swarm_routes.py
@@ -76,9 +76,14 @@ def register_swarm_routes(
# --- Routes ---
- @app.get("/swarm/presets")
+ @app.get("/swarm/presets", dependencies=[Depends(require_auth)])
async def list_swarm_presets():
- """List Swarm YAML presets."""
+ """List Swarm YAML presets.
+
+ Authenticated for the same reason as ``/skills``: the preset inventory
+ describes configured agent capabilities and should not be readable by a
+ peer that cannot start a swarm run.
+ """
from src.swarm.presets import list_presets
return list_presets()
diff --git a/agent/src/api/system_routes.py b/agent/src/api/system_routes.py
index 8f02ece0b..30e52b2f6 100644
--- a/agent/src/api/system_routes.py
+++ b/agent/src/api/system_routes.py
@@ -24,6 +24,8 @@ from fastapi import (
Security,
status,
)
+from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
+from fastapi.responses import JSONResponse
from fastapi.security import HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
@@ -184,6 +186,7 @@ def register_system_routes(
_security = host._security
_require_shutdown_authorization = host._require_shutdown_authorization
+ _configured_api_key = host._configured_api_key
require_auth = host.require_auth
_app_version = app_version if app_version is not None else host.APP_VERSION
@@ -344,9 +347,13 @@ def register_system_routes(
"timestamp": datetime.now(timezone.utc).isoformat(),
}
- @app.get("/skills")
+ @app.get("/skills", dependencies=[Depends(require_auth)])
async def list_skills():
- """List registered skills (name and description)."""
+ """List registered skills (name and description).
+
+ Authenticated: the skill inventory describes the agent's installed
+ capabilities and is not appropriate pre-auth reconnaissance material.
+ """
from src.agent.skills import SkillsLoader
loader = SkillsLoader()
@@ -367,3 +374,64 @@ def register_system_routes(
"docs": "/docs",
"health": "/health",
}
+
+ # --- API documentation ---
+ #
+ # ``api_server`` constructs the app with ``docs_url``/``redoc_url``/
+ # ``openapi_url`` set to ``None`` and delegates here so the schema and its
+ # schema sits behind ``require_auth``. It enumerates every route -- including
+ # the live-trading and mandate control plane -- so an unauthorized peer must
+ # not be able to read it.
+ #
+ # A browser navigation cannot attach a Bearer header before Swagger's
+ # ``Authorize`` control loads, and its initial schema fetch is unauthenticated
+ # too. Interactive docs therefore remain available only in keyless loopback
+ # dev mode. Keyed deployments return 404 for both viewers and expose the
+ # schema only to programmatic callers that send the Bearer header.
+
+ _openapi_url = "/openapi.json"
+
+ @app.get(_openapi_url, include_in_schema=False, dependencies=[Depends(require_auth)])
+ async def openapi_schema():
+ """Serve the OpenAPI schema to authorized callers only."""
+ return JSONResponse(app.openapi())
+
+ # Favicons point at the SPA's self-hosted asset rather than FastAPI's
+ # default remote one, so the docs CSP exception does not have to widen
+ # ``img-src`` to a third-party host.
+ _docs_favicon = "/favicon.svg"
+
+ @app.get("/docs", include_in_schema=False)
+ async def swagger_ui(
+ request: Request,
+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),
+ ):
+ """Serve Swagger UI only in keyless loopback development mode."""
+ if _configured_api_key():
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found")
+ await require_auth(request, cred)
+ return get_swagger_ui_html(
+ openapi_url=_openapi_url,
+ title=f"{app.title} - Swagger UI",
+ swagger_favicon_url=_docs_favicon,
+ )
+
+ @app.get("/redoc", include_in_schema=False)
+ async def redoc_ui(
+ request: Request,
+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),
+ ):
+ """Serve ReDoc only in keyless loopback development mode."""
+ if _configured_api_key():
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found")
+ await require_auth(request, cred)
+ # ``with_google_fonts=False`` drops ReDoc's fonts.googleapis.com
+ # stylesheet, so the docs CSP exception stays limited to the bundle
+ # host instead of also allowing a font CDN. ReDoc falls back to system
+ # fonts and is otherwise unchanged.
+ return get_redoc_html(
+ openapi_url=_openapi_url,
+ title=f"{app.title} - ReDoc",
+ redoc_favicon_url=_docs_favicon,
+ with_google_fonts=False,
+ )
diff --git a/agent/src/channels/msteams.py b/agent/src/channels/msteams.py
index ef542a9c1..67e584108 100644
--- a/agent/src/channels/msteams.py
+++ b/agent/src/channels/msteams.py
@@ -60,6 +60,36 @@ MSTEAMS_DEFAULT_TRUSTED_SERVICE_URL_HOSTS = [
"smba.infra.dod.teams.microsoft.us",
"*.botframework.com",
]
+# Hard ceiling on an inbound webhook body. Read before the bearer token can be
+# validated (the token is checked against the activity payload), so an
+# unauthenticated caller controls this allocation -- a Bot Framework activity is
+# a few KB, and 1 MiB leaves generous headroom without letting a declared
+# Content-Length drive unbounded memory use.
+MSTEAMS_MAX_INBOUND_BODY_BYTES = 1024 * 1024
+
+
+def msteams_validate_content_length(raw: str | None) -> tuple[int, int | None]:
+ """Validate an inbound ``Content-Length`` before allocating for the body.
+
+ Args:
+ raw: The raw header value, or ``None`` when absent.
+
+ Returns:
+ ``(length, error_status)``. ``error_status`` is ``None`` when the body
+ may be read, ``400`` for a malformed or negative value, and ``413``
+ when it exceeds :data:`MSTEAMS_MAX_INBOUND_BODY_BYTES`.
+ """
+ try:
+ length = int(raw if raw is not None else "0")
+ except (TypeError, ValueError):
+ return 0, 400
+ if length < 0:
+ return 0, 400
+ if length > MSTEAMS_MAX_INBOUND_BODY_BYTES:
+ return 0, 413
+ return length, None
+
+
MSTEAMS_REF_META_FILENAME = "msteams_conversations_meta.json"
MSTEAMS_REF_LOCK_FILENAME = "msteams_conversations.lock"
MSTEAMS_REF_TOUCH_INTERVAL_S = 300
@@ -169,8 +199,25 @@ class MSTeamsChannel(BaseChannel):
self.end_headers()
return
+ # Bound the body before reading it: this runs before the bearer
+ # token can be validated (validation needs the parsed activity),
+ # so an unauthenticated caller controls the declared size.
+ length, length_error = msteams_validate_content_length(
+ self.headers.get("Content-Length")
+ )
+ if length_error is not None:
+ channel.logger.warning(
+ "Rejecting inbound activity: Content-Length {!r} -> {}",
+ self.headers.get("Content-Length"),
+ length_error,
+ )
+ self.send_response(length_error)
+ self.end_headers()
+ return
+
try:
- length = int(self.headers.get("Content-Length", "0"))
+ # Bounded by the check above, so a hostile Content-Length
+ # cannot drive the allocation.
raw = self.rfile.read(length) if length > 0 else b"{}"
payload = json.loads(raw.decode("utf-8"))
except Exception as e:
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index 660fc2bcd..446321206 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -264,6 +264,13 @@ class APIConfig(_EnvBase):
vibe_trading_trust_docker_loopback: EnvBool = Field(
alias="VIBE_TRADING_TRUST_DOCKER_LOOPBACK", default=False,
)
+ # Ship the Content-Security-Policy as Report-Only instead of enforcing it.
+ # The policy is enforced by default; this is a rollback switch for a
+ # deployment that serves extra assets the stock policy does not cover
+ # (a reverse proxy injecting a script, a customized frontend build).
+ vibe_trading_csp_report_only: EnvBool = Field(
+ alias="VIBE_TRADING_CSP_REPORT_ONLY", default=False,
+ )
vibe_trading_enable_shell_tools: EnvBool = Field(
alias="VIBE_TRADING_ENABLE_SHELL_TOOLS", default=False,
)
diff --git a/agent/tests/test_msteams_inbound_body_limit.py b/agent/tests/test_msteams_inbound_body_limit.py
new file mode 100644
index 000000000..f9b650da3
--- /dev/null
+++ b/agent/tests/test_msteams_inbound_body_limit.py
@@ -0,0 +1,55 @@
+"""Security regression tests for the MSTeams inbound webhook body bound."""
+
+from __future__ import annotations
+
+import pytest
+
+from src.channels.msteams import (
+ MSTEAMS_MAX_INBOUND_BODY_BYTES,
+ msteams_validate_content_length,
+)
+
+
[email protected]("raw", ["0", None])
+def test_absent_or_zero_length_is_accepted(raw: str | None) -> None:
+ """An absent or zero body is valid; the handler substitutes ``{}``."""
+ length, error = msteams_validate_content_length(raw)
+
+ assert error is None
+ assert length == 0
+
+
+def test_ordinary_activity_size_is_accepted() -> None:
+ length, error = msteams_validate_content_length("4096")
+
+ assert error is None
+ assert length == 4096
+
+
+def test_limit_boundary_is_inclusive() -> None:
+ length, error = msteams_validate_content_length(str(MSTEAMS_MAX_INBOUND_BODY_BYTES))
+
+ assert error is None
+ assert length == MSTEAMS_MAX_INBOUND_BODY_BYTES
+
+
+def test_oversized_declared_length_is_rejected_before_read() -> None:
+ """A hostile Content-Length must not drive an unbounded allocation."""
+ _length, error = msteams_validate_content_length(
+ str(MSTEAMS_MAX_INBOUND_BODY_BYTES + 1)
+ )
+
+ assert error == 413
+
+
+def test_absurd_declared_length_is_rejected() -> None:
+ _length, error = msteams_validate_content_length("10000000000")
+
+ assert error == 413
+
+
[email protected]("raw", ["-1", "abc", "1.5", "0x10", " ", ""])
+def test_malformed_length_is_rejected(raw: str) -> None:
+ _length, error = msteams_validate_content_length(raw)
+
+ assert error == 400
diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.py
index 93c16d821..4b8c1576a 100644
--- a/agent/tests/test_security_auth_api.py
+++ b/agent/tests/test_security_auth_api.py
@@ -22,12 +22,22 @@ def _local_client() -> TestClient:
@pytest.fixture(autouse=True)
-def clear_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
- """Start every auth test from dev-mode auth."""
+def clear_api_key(monkeypatch: pytest.MonkeyPatch):
+ """Start every auth test from dev-mode auth.
+
+ The cached ``EnvConfig`` singleton is reset on both sides of the test so a
+ case that sets ``API_AUTH_KEY`` / ``VIBE_TRADING_TRUST_DOCKER_LOOPBACK``
+ cannot leak a stale config into the next one.
+ """
+ from src.config.accessor import reset_env_config
+
monkeypatch.delenv("API_AUTH_KEY", raising=False)
monkeypatch.delenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", raising=False)
monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)
monkeypatch.setattr(api_server, "_API_KEY", "")
+ reset_env_config()
+ yield
+ reset_env_config()
def test_remote_write_requires_api_key_when_key_unset() -> None:
@@ -65,9 +75,18 @@ def test_local_dev_write_allowed_when_key_unset() -> None:
assert response.status_code in {201, 501}
+def test_remote_capability_inventory_requires_api_key_when_key_unset() -> None:
+ client = _remote_client()
+
+ for path in ("/skills", "/swarm/presets", "/openapi.json"):
+ assert client.get(path).status_code == 403, path
+
+
def test_docker_gateway_dev_write_allowed_only_with_compose_trust_flag(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ from src.config.accessor import reset_env_config
+
request = SimpleNamespace(client=SimpleNamespace(host="172.18.0.1"))
monkeypatch.setattr(
api_server,
@@ -78,12 +97,30 @@ def test_docker_gateway_dev_write_allowed_only_with_compose_trust_flag(
assert not api_server._is_local_client(request)
monkeypatch.setenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", "1")
- from src.config.accessor import reset_env_config
reset_env_config()
assert api_server._is_local_client(request)
+def test_default_docker_gateway_browser_flow_remains_zero_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The compose gateway trust reaches a sensitive route without a key."""
+ from src.config.accessor import reset_env_config
+
+ monkeypatch.setenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", "1")
+ monkeypatch.setattr(
+ api_server,
+ "_default_gateway_ips",
+ lambda: {ipaddress.IPv4Address("172.18.0.1")},
+ )
+ reset_env_config()
+
+ client = TestClient(api_server.app, client=("172.18.0.1", 50000))
+ response = client.post("/sessions", json={})
+ assert response.status_code in {201, 501}
+
+
def test_docker_network_peer_is_not_local_even_with_compose_trust_flag(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -110,6 +147,9 @@ def test_configured_api_key_required_for_sensitive_reads(
"/sessions",
"/sessions/abcdef012345/goal",
"/swarm/runs",
+ "/skills",
+ "/swarm/presets",
+ "/openapi.json",
]:
response = client.get(path)
assert response.status_code == 401, path
@@ -121,12 +161,10 @@ def test_configured_api_key_accepts_bearer_for_sensitive_reads(
monkeypatch.setenv("API_AUTH_KEY", "secret")
monkeypatch.setattr(api_server, "_API_KEY", "secret")
- response = _remote_client().get(
- "/runs",
- headers={"Authorization": "Bearer secret"},
- )
-
- assert response.status_code == 200
+ client = _remote_client()
+ for path in ("/runs", "/skills", "/swarm/presets", "/openapi.json"):
+ response = client.get(path, headers={"Authorization": "Bearer secret"})
+ assert response.status_code == 200, path
def test_loopback_requires_auth_when_api_key_configured(
@@ -156,6 +194,35 @@ def test_loopback_requires_auth_when_api_key_configured(
assert remote_bearer.status_code == 200
+def test_interactive_docs_are_loopback_only_in_keyless_dev_mode() -> None:
+ """Default docs work locally without exposing the schema to remote peers."""
+ local = _local_client()
+ remote = _remote_client()
+
+ for path in ("/docs", "/redoc", "/openapi.json"):
+ assert local.get(path).status_code == 200, path
+ assert remote.get(path).status_code == 403, path
+
+
+def test_keyed_deployment_disables_viewers_but_allows_bearer_schema(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A configured key never creates a browser docs bootstrap deadlock."""
+ from src.config.accessor import reset_env_config
+
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ reset_env_config()
+ bearer = {"Authorization": "Bearer secret"}
+
+ for client in (_local_client(), _remote_client()):
+ for path in ("/docs", "/redoc"):
+ assert client.get(path).status_code == 404, path
+ assert client.get(path, headers=bearer).status_code == 404, path
+ assert client.get("/openapi.json").status_code == 401
+ assert client.get("/openapi.json", headers=bearer).status_code == 200
+
+
def _llm_settings_payload(base_url: str = "https://api.openai.com/v1") -> dict[str, object]:
return {
"provider": "openai",
diff --git a/agent/tests/test_sse_ticket_and_headers.py b/agent/tests/test_sse_ticket_and_headers.py
index cfcc26f1c..5b7b0fbf4 100644
--- a/agent/tests/test_sse_ticket_and_headers.py
+++ b/agent/tests/test_sse_ticket_and_headers.py
@@ -143,16 +143,63 @@ def test_security_headers_present_on_response() -> None:
assert response.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
assert "geolocation=()" in response.headers.get("Permissions-Policy", "")
- csp = response.headers.get("Content-Security-Policy-Report-Only", "")
+ # Enforcing by default -- Report-Only provides no protection.
+ csp = response.headers.get("Content-Security-Policy", "")
assert "default-src 'self'" in csp
assert "frame-ancestors 'none'" in csp
- # Ships Report-Only first, never as an enforcing policy.
- assert response.headers.get("Content-Security-Policy") is None
+ assert "script-src 'self';" in csp
+ assert response.headers.get("Content-Security-Policy-Report-Only") is None
# No HSTS from the app — that belongs at the TLS-terminating proxy.
assert response.headers.get("Strict-Transport-Security") is None
+def test_csp_report_only_opt_out(monkeypatch: pytest.MonkeyPatch) -> None:
+ """``VIBE_TRADING_CSP_REPORT_ONLY=1`` is the documented rollback switch."""
+ from src.config.accessor import reset_env_config
+
+ monkeypatch.setenv("VIBE_TRADING_CSP_REPORT_ONLY", "1")
+ reset_env_config()
+ try:
+ response = _local_client().get("/health")
+ assert "default-src 'self'" in response.headers.get(
+ "Content-Security-Policy-Report-Only", ""
+ )
+ assert response.headers.get("Content-Security-Policy") is None
+ finally:
+ monkeypatch.delenv("VIBE_TRADING_CSP_REPORT_ONLY", raising=False)
+ reset_env_config()
+
+
+def test_docs_csp_allows_bundle_host_but_app_pages_do_not() -> None:
+ """The Swagger/ReDoc CDN exception must not leak into the SPA's policy."""
+ client = _local_client()
+
+ docs_csp = client.get("/docs").headers.get("Content-Security-Policy", "")
+ assert "https://cdn.jsdelivr.net" in docs_csp
+ assert "frame-ancestors 'none'" in docs_csp
+
+ app_csp = client.get("/health").headers.get("Content-Security-Policy", "")
+ assert "cdn.jsdelivr.net" not in app_csp
+ assert "'unsafe-inline'" not in app_csp.split("style-src")[0]
+
+
+def test_docs_pages_reference_no_host_outside_their_csp() -> None:
+ """Every remote asset the docs pages load must be covered by the policy.
+
+ Guards against a FastAPI bump reintroducing an asset host the exception
+ does not allow (ReDoc's Google Fonts stylesheet was one such case), which
+ would silently render a blocked page under the enforcing policy.
+ """
+ import re
+
+ client = _local_client()
+ for path in ("/docs", "/redoc"):
+ html = client.get(path).text
+ hosts = set(re.findall(r"https?://([a-zA-Z0-9.\-]+)", html))
+ assert hosts <= {"cdn.jsdelivr.net"}, f"{path} references {hosts}"
+
+
def test_security_headers_present_on_error_response(
monkeypatch: pytest.MonkeyPatch,
) -> None: