Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion agentic_security/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .core.app import create_app
from .core.logging import setup_logging
from .middleware.cors import setup_cors
from .middleware.cors import setup_cors, setup_origin_guard
from .middleware.logging import LogNon200ResponsesMiddleware
from .routes import (
probe_router,
Expand All @@ -16,6 +16,7 @@

# Setup middleware
setup_cors(app)
setup_origin_guard(app)
app.add_middleware(LogNon200ResponsesMiddleware)

# Setup logging
Expand Down
91 changes: 87 additions & 4 deletions agentic_security/middleware/cors.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,96 @@
import os
import warnings

import tomli
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse

DEFAULT_CONFIG_PATH = "agentic_security.toml"
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})


def _read_toml_origins() -> list[str] | None:
"""Read `server.cors_allow_origins` from agentic_security.toml without side effects.

Returns None when the file is absent or unreadable, so the caller can fall back.
"""
try:
with open(DEFAULT_CONFIG_PATH, "rb") as handle:
data = tomli.load(handle)
except OSError, tomli.TOMLDecodeError:
return None
origins = data.get("server", {}).get("cors_allow_origins")
if origins is None:
return None
if isinstance(origins, str):
return [origins]
return list(origins)


def allowed_origins() -> list[str]:
"""Effective CORS allowlist.

Precedence: AGENTIC_SECURITY_CORS_ORIGINS env var, then
[server] cors_allow_origins in agentic_security.toml, then [] (same-origin only).
"""
env = os.getenv("AGENTIC_SECURITY_CORS_ORIGINS")
if env is not None:
return [origin.strip() for origin in env.split(",") if origin.strip()]
toml_origins = _read_toml_origins()
if toml_origins is not None:
return toml_origins
return []


def setup_cors(app: FastAPI):
origins = ["*"]
def setup_cors(app: FastAPI) -> None:
"""Configure CORS with an explicit allowlist instead of a wildcard.

The wildcard (`allow_origins=["*"]`) granted every web origin access to the
unauthenticated, state-changing /scan, /scan-csv, /stop and /verify endpoints.
Defaulting to [] keeps the server same-origin only; the bundled UI never needs
a cross-origin grant.
"""
origins = allowed_origins()
if "*" in origins:
warnings.warn(
"AGENTIC_SECURITY_CORS_ORIGINS / server.cors_allow_origins contains "
"'*': cross-origin access to unauthenticated scan endpoints is allowed. "
"Use an explicit allowlist instead.",
RuntimeWarning,
stacklevel=2,
)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
allow_methods=["*"],
allow_headers=["*"],
)


class OriginGuardMiddleware(BaseHTTPMiddleware):
"""Reject cross-origin browser requests to state-changing endpoints.

CORS controls whether a browser can *read* a cross-origin response, but simple
POSTs (/stop, /scan-csv) are still *sent* without a preflight. Same-origin
clients and non-browser tools send no Origin header and are unaffected.
"""

def __init__(self, app, allowed_origins: list[str]):
super().__init__(app)
self._allowed = set(allowed_origins)

async def dispatch(self, request: Request, call_next):
origin = request.headers.get("origin")
if origin and origin not in self._allowed and request.method not in SAFE_METHODS:
return JSONResponse(
{"detail": "cross-origin requests to this endpoint are not allowed"},
status_code=403,
)
return await call_next(request)


def setup_origin_guard(app: FastAPI) -> None:
app.add_middleware(OriginGuardMiddleware, allowed_origins=allowed_origins())
99 changes: 46 additions & 53 deletions tests/unit/test_cors_middleware.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
"""Unit tests for CORS middleware configuration.

Verifies that the wildcard-origins + allow_credentials=True spec violation
(CORS spec §3.2, Fetch §4.7) has been removed. Browsers silently strip
credentials when the response carries Access-Control-Allow-Origin: * paired
with Access-Control-Allow-Credentials: true, so the old config was both
broken and misleading.
The server defaults to a same-origin-only allowlist (``allow_origins=[]``) so that
unauthenticated, state-changing endpoints (/scan, /scan-csv, /stop, /verify) are
not reachable from arbitrary web origins.
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient

from agentic_security.middleware.cors import setup_cors
from agentic_security.middleware.cors import (
allowed_origins,
setup_cors,
)


def _get_cors_options(app: FastAPI) -> dict:
Expand All @@ -23,35 +24,49 @@ def _get_cors_options(app: FastAPI) -> dict:


class TestCorsSetup:
"""CORS middleware is configured correctly."""

def test_cors_middleware_is_registered(self):
"""setup_cors adds CORSMiddleware to the app."""
app = FastAPI()
setup_cors(app)
cls_names = [m.cls.__name__ for m in app.user_middleware]
assert "CORSMiddleware" in cls_names

def test_wildcard_origins_without_credentials(self):
"""allow_origins=['*'] must not be paired with allow_credentials=True.
assert "CORSMiddleware" in [m.cls.__name__ for m in app.user_middleware]

The combination is forbidden by the CORS spec and causes browsers to
silently drop credentials on every cross-origin request.
"""
def test_default_allowlist_is_same_origin_only(self):
"""Without configuration, allow_origins is [] (no wildcard)."""
app = FastAPI()
setup_cors(app)
opts = _get_cors_options(app)
allow_origins = opts.get("allow_origins", [])
allow_credentials = opts.get("allow_credentials", False)

if "*" in allow_origins or allow_origins == ["*"]:
assert not allow_credentials, (
"allow_origins=['*'] with allow_credentials=True is invalid per "
"the CORS spec — browsers reject it and credentials are silently dropped"
)
assert _get_cors_options(app).get("allow_origins") == []

def test_allowlist_from_env_var(self, monkeypatch):
"""AGENTIC_SECURITY_CORS_ORIGINS is parsed as a comma-separated list."""
monkeypatch.setenv("AGENTIC_SECURITY_CORS_ORIGINS", "https://example.com, https://internal.test")
assert allowed_origins() == ["https://example.com", "https://internal.test"]

def test_env_var_takes_precedence_over_toml(self, monkeypatch, tmp_path):
"""The env var wins when both it and agentic_security.toml are present."""
toml_file = tmp_path / "agentic_security.toml"
toml_file.write_text('[server]\ncors_allow_origins = ["https://toml.example"]\n')
monkeypatch.setattr("agentic_security.middleware.cors.DEFAULT_CONFIG_PATH", str(toml_file))
monkeypatch.setenv("AGENTIC_SECURITY_CORS_ORIGINS", "https://env.example")
assert allowed_origins() == ["https://env.example"]

def test_allowlist_from_toml(self, monkeypatch, tmp_path):
"""[server] cors_allow_origins in agentic_security.toml is honoured."""
toml_file = tmp_path / "agentic_security.toml"
toml_file.write_text('[server]\ncors_allow_origins = ["https://toml.example"]\n')
monkeypatch.setattr("agentic_security.middleware.cors.DEFAULT_CONFIG_PATH", str(toml_file))
monkeypatch.delenv("AGENTIC_SECURITY_CORS_ORIGINS", raising=False)
assert allowed_origins() == ["https://toml.example"]

def test_wildcard_origins_triggers_warning(self, monkeypatch, recwarn):
"""Configuring '*' is accepted but warns, since it re-opens the issue."""
monkeypatch.setenv("AGENTIC_SECURITY_CORS_ORIGINS", "*")
app = FastAPI()
setup_cors(app)
runtime_warnings = [w for w in recwarn.list if issubclass(w.category, RuntimeWarning)]
assert any("'*'" in str(w.message) for w in runtime_warnings)

def test_cors_allows_cross_origin_requests(self):
"""Cross-origin preflight requests return a 200 with CORS headers."""
def test_cors_rejects_cross_origin_preflight(self):
"""A cross-origin preflight from a non-listed origin gets no ACAO header."""
app = FastAPI()

@app.get("/probe")
Expand All @@ -60,35 +75,13 @@ async def probe():

setup_cors(app)
client = TestClient(app, raise_server_exceptions=True)

response = client.options(
"/probe",
headers={
"Origin": "http://localhost:3000",
"Origin": "https://evil.example.com",
"Access-Control-Request-Method": "GET",
},
)
assert response.status_code == 200
assert "access-control-allow-origin" in response.headers

def test_cors_no_credentials_header_with_wildcard(self):
"""With wildcard origins, the response must not include
Access-Control-Allow-Credentials: true."""
app = FastAPI()

@app.get("/probe")
async def probe():
return {"ok": True}

setup_cors(app)
client = TestClient(app)
response = client.get("/probe", headers={"Origin": "http://evil.example.com"})

acao = response.headers.get("access-control-allow-origin", "")
acac = response.headers.get("access-control-allow-credentials", "false")

if acao == "*":
assert acac.lower() != "true", (
"Wildcard ACAO + ACAC:true is a spec violation (RFC 6454 §7.2, "
"Fetch §4.7) and silently breaks credentialed cross-origin requests"
)
# A non-listed origin is not granted CORS access (preflight rejected).
assert response.status_code == 400
assert "access-control-allow-origin" not in response.headers
65 changes: 65 additions & 0 deletions tests/unit/test_origin_guard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Tests for OriginGuardMiddleware.

Cross-origin browser requests to state-changing endpoints are rejected with 403.
Same-origin clients and non-browser tools (no Origin header) are unaffected, as
are read-only and preflight requests.
"""

from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.responses import JSONResponse

from agentic_security.middleware.cors import OriginGuardMiddleware


def _make_app(allowed_origins=None):
app = FastAPI()

@app.post("/stop")
async def stop():
return JSONResponse({"status": "stopped"})

@app.get("/probe")
async def probe():
return JSONResponse({"ok": True})

@app.options("/probe")
async def probe_options():
return JSONResponse({"ok": True})

app.add_middleware(OriginGuardMiddleware, allowed_origins=allowed_origins or [])
return app


class TestOriginGuard:
def test_cross_origin_post_is_rejected(self):
app = _make_app()
client = TestClient(app, raise_server_exceptions=True)
response = client.post("/stop", headers={"Origin": "https://evil.example.com"})
assert response.status_code == 403

def test_no_origin_post_is_allowed(self):
"""curl, the CLI and the test suite send no Origin header."""
app = _make_app()
client = TestClient(app, raise_server_exceptions=True)
response = client.post("/stop")
assert response.status_code == 200

def test_allowlisted_origin_post_is_allowed(self):
app = _make_app(["https://example.com"])
client = TestClient(app, raise_server_exceptions=True)
response = client.post("/stop", headers={"Origin": "https://example.com"})
assert response.status_code == 200

def test_cross_origin_get_is_allowed(self):
"""Read-only requests are not guarded (CORS still limits response access)."""
app = _make_app()
client = TestClient(app, raise_server_exceptions=True)
response = client.get("/probe", headers={"Origin": "https://evil.example.com"})
assert response.status_code == 200

def test_options_preflight_is_allowed(self):
app = _make_app()
client = TestClient(app, raise_server_exceptions=True)
response = client.options("/probe", headers={"Origin": "https://evil.example.com"})
assert response.status_code == 200