Personal AI, On Personal Devices
Python
fix(server): exempt OPTIONS requests from API key auth (#796)
havolline16338dba2f110
diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.pyindex 55c2dbd5..6c830c8f 100644--- a/src/openjarvis/server/app.py+++ b/src/openjarvis/server/app.py@@ -208,14 +208,6 @@ def create_app("https://tauri.localhost",])- app.add_middleware(- CORSMiddleware,- allow_origins=_origins,- allow_credentials=True,- allow_methods=["*"],- allow_headers=["*"],- )-# Store dependencies in app stateapp.state.engine = engineapp.state.model = model@@ -457,6 +449,18 @@ def create_app(except Exception as exc:logger.debug("Auth middleware init skipped: %s", exc)+ # Register CORS last so it is the outermost middleware. In addition to+ # handling preflights, this ensures browser clients can read 401 responses+ # produced directly by AuthMiddleware instead of seeing an opaque CORS+ # network error.+ app.add_middleware(+ CORSMiddleware,+ allow_origins=_origins,+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],+ )+# Mount webhook routes (always — SendBlue may be configured dynamically)if webhook_config:try:diff --git a/src/openjarvis/server/auth_middleware.py b/src/openjarvis/server/auth_middleware.pyindex 54d53136..c7199ba5 100644--- a/src/openjarvis/server/auth_middleware.py+++ b/src/openjarvis/server/auth_middleware.py@@ -39,6 +39,13 @@ class AuthMiddleware(BaseHTTPMiddleware):self._api_key = api_key or os.environ.get("OPENJARVIS_API_KEY", "")async def dispatch(self, request: Request, call_next): # noqa: ANN001+ # Browser CORS preflights never carry Authorization, and rejecting+ # them here means they never reach CORSMiddleware to get+ # Access-Control-Allow-* headers, breaking cross-origin access+ # outright (#758). Do not exempt arbitrary OPTIONS requests: a real+ # preflight is identified by both headers required by the CORS protocol.+ if self._is_cors_preflight(request):+ return await call_next(request)if self._api_key and self._requires_auth(request.url.path):auth = request.headers.get("Authorization", "")if not auth:@@ -55,6 +62,14 @@ class AuthMiddleware(BaseHTTPMiddleware):)return await call_next(request)+ @staticmethod+ def _is_cors_preflight(request: Request) -> bool:+ return (+ request.method == "OPTIONS"+ and bool(request.headers.get("Origin"))+ and bool(request.headers.get("Access-Control-Request-Method"))+ )+@staticmethoddef _requires_auth(path: str) -> bool:"""Protect API routes and operational metrics; leave the UI/health open.diff --git a/tests/server/test_auth_middleware.py b/tests/server/test_auth_middleware.pyindex 26c27a14..fa13b087 100644--- a/tests/server/test_auth_middleware.py+++ b/tests/server/test_auth_middleware.py@@ -82,3 +82,28 @@ class TestAuthMiddleware:resp = client.get("/v1/models")assert resp.status_code == 200assert client.get("/metrics").status_code == 200++ def test_cors_preflight_exempt(self, client):+ """Regression for #758: browser preflights never carry Authorization,+ so AuthMiddleware must not reject OPTIONS with 401 -- otherwise the+ request never reaches CORSMiddleware and preflight fails outright."""+ resp = client.options(+ "/v1/models",+ headers={+ "Origin": "https://example.com",+ "Access-Control-Request-Method": "GET",+ },+ )+ assert resp.status_code != 401++ @pytest.mark.parametrize(+ "headers",+ [+ {},+ {"Origin": "https://example.com"},+ {"Access-Control-Request-Method": "GET"},+ ],+ )+ def test_non_preflight_options_still_requires_auth(self, client, headers):+ resp = client.options("/v1/models", headers=headers)+ assert resp.status_code == 401diff --git a/tests/server/test_cors_auth_interaction.py b/tests/server/test_cors_auth_interaction.pynew file mode 100644index 00000000..2e675103--- /dev/null+++ b/tests/server/test_cors_auth_interaction.py@@ -0,0 +1,99 @@+"""Regression tests for #758: CORS preflight broken when an API key is set.++CORSMiddleware is the outermost layer so it can both answer real preflights+and decorate AuthMiddleware's 401 responses. Without that ordering, browsers+surface an opaque CORS network failure instead of the actionable auth error.+"""++from __future__ import annotations++from unittest.mock import MagicMock++import pytest++fastapi = pytest.importorskip("fastapi")+from fastapi.testclient import TestClient # noqa: E402++from openjarvis.server.app import create_app # noqa: E402+++def _make_engine():+ engine = MagicMock()+ engine.engine_id = "mock"+ engine.health.return_value = True+ engine.list_models.return_value = ["test-model"]+ return engine+++def _test_config():+ from openjarvis.core.config import JarvisConfig++ cfg = JarvisConfig()+ cfg.analytics.enabled = False+ cfg.traces.enabled = False+ return cfg+++class TestCorsPreflightWithApiKey:+ def test_preflight_gets_cors_headers_not_401(self):+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ cors_origins=["https://example.com"],+ )+ client = TestClient(app)++ resp = client.options(+ "/v1/models",+ headers={+ "Origin": "https://example.com",+ "Access-Control-Request-Method": "GET",+ },+ )++ assert resp.status_code != 401+ assert resp.headers.get("access-control-allow-origin") == "https://example.com"++ def test_actual_request_still_requires_auth(self):+ """The fix must not accidentally exempt real GET/POST requests."""+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ cors_origins=["https://example.com"],+ )+ client = TestClient(app)++ resp = client.get("/v1/models", headers={"Origin": "https://example.com"})+ assert resp.status_code == 401+ assert resp.headers.get("access-control-allow-origin") == "https://example.com"++ def test_plain_options_is_not_an_auth_bypass(self):+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ cors_origins=["https://example.com"],+ )+ client = TestClient(app)++ resp = client.options("/v1/models")+ assert resp.status_code == 401++ def test_disallowed_origin_gets_no_cors_header(self):+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ cors_origins=["https://example.com"],+ )+ client = TestClient(app)++ resp = client.get("/v1/models", headers={"Origin": "https://evil.example"})+ assert resp.status_code == 401+ assert "access-control-allow-origin" not in resp.headers