Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: permissive CORS for API-key requests (#14473)

Hiep Le8350c498aa65
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index 9e09422bcb..385f83827d 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -13,7 +13,6 @@ if not os.getenv('OPENHANDS_CONFIG_CLS'):
os.environ['SERVE_FRONTEND'] = 'false'
from fastapi import Request, status # noqa: E402
-from fastapi.middleware.cors import CORSMiddleware # noqa: E402
from fastapi.responses import JSONResponse # noqa: E402
from server.auth.auth_error import ExpiredError, NoCredentialsError # noqa: E402
from server.auth.constants import ( # noqa: E402
@@ -26,7 +25,10 @@ from server.auth.constants import ( # noqa: E402
)
from server.constants import PERMITTED_CORS_ORIGINS # noqa: E402
from server.logger import logger # noqa: E402
-from server.middleware import SetAuthCookieMiddleware # noqa: E402
+from server.middleware import ( # noqa: E402
+ ApiKeyAwareCORSMiddleware,
+ SetAuthCookieMiddleware,
+)
from server.rate_limit import setup_rate_limit_handler # noqa: E402
from server.routes.api_keys import api_router as api_keys_router # noqa: E402
from server.routes.auth import api_router, oauth_router # noqa: E402
@@ -167,11 +169,8 @@ base_app.include_router(email_router) # Add routes for email management
base_app.add_middleware(
- CORSMiddleware,
+ ApiKeyAwareCORSMiddleware,
allow_origins=PERMITTED_CORS_ORIGINS,
- allow_credentials=True,
- allow_methods=['*'],
- allow_headers=['*'],
)
base_app.add_middleware(CacheControlMiddleware)
base_app.middleware('http')(SetAuthCookieMiddleware())
diff --git a/enterprise/server/middleware.py b/enterprise/server/middleware.py
index d3c08829ef..be7d2e158f 100644
--- a/enterprise/server/middleware.py
+++ b/enterprise/server/middleware.py
@@ -2,6 +2,7 @@ from typing import Callable, cast
import jwt
from fastapi import Request, Response, status
+from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from server.auth.auth_error import (
AuthError,
@@ -195,6 +196,81 @@ class SetAuthCookieMiddleware:
logger.debug('Error logging out')
+_CREDENTIALLESS_PATH_PREFIXES = (
+ # RFC 8628 device authorization endpoints β€” unauthenticated by design,
+ # called cross-origin from clients that are exchanging device codes for
+ # API keys.
+ '/oauth/device/authorize',
+ '/oauth/device/token',
+)
+
+
+class ApiKeyAwareCORSMiddleware:
+ """CORS dispatcher that loosens the policy for credential-less requests.
+
+ Requests that authenticate via API key (``Authorization: Bearer …``,
+ ``X-Session-API-Key``, or ``X-Access-Token``) or that target a known
+ unauthenticated cross-origin endpoint (RFC 8628 device flow) get
+ ``Access-Control-Allow-Origin: *`` with credentials disabled β€” the
+ wildcard is safe because the browser cannot attach cookies when
+ credentials are off, so the only way to authenticate is the explicit
+ key (or no auth, for public endpoints).
+
+ Cookie/session requests keep the strict origin allowlist with
+ credentials enabled.
+ """
+
+ def __init__(self, app, allow_origins):
+ self._permissive = CORSMiddleware(
+ app,
+ allow_origins=['*'],
+ allow_credentials=False,
+ allow_methods=['*'],
+ allow_headers=['*'],
+ )
+ self._strict = CORSMiddleware(
+ app,
+ allow_origins=allow_origins,
+ allow_credentials=True,
+ allow_methods=['*'],
+ allow_headers=['*'],
+ )
+
+ async def __call__(self, scope, receive, send):
+ if scope['type'] == 'http' and self._is_credentialless(scope):
+ await self._permissive(scope, receive, send)
+ else:
+ await self._strict(scope, receive, send)
+
+ @staticmethod
+ def _is_credentialless(scope) -> bool:
+ path = scope.get('path', '')
+ if any(path.startswith(prefix) for prefix in _CREDENTIALLESS_PATH_PREFIXES):
+ return True
+ if scope['method'] == 'OPTIONS':
+ # Preflight: the auth header hasn't been sent yet, so look at the
+ # headers the browser is asking permission to send. Parse the
+ # comma-separated list into a set so we match whole header names
+ # only β€” otherwise something like ``x-my-authorization-token``
+ # would substring-match ``authorization``.
+ for name, value in scope['headers']:
+ if name == b'access-control-request-headers':
+ requested_headers = {
+ h.strip() for h in value.decode('latin-1').lower().split(',')
+ }
+ return bool(
+ requested_headers
+ & {'authorization', 'x-session-api-key', 'x-access-token'}
+ )
+ return False
+ for name, value in scope['headers']:
+ if name == b'authorization' and value[:7].lower() == b'bearer ':
+ return True
+ if name in (b'x-session-api-key', b'x-access-token'):
+ return True
+ return False
+
+
class PostHogSessionMiddleware:
"""Extract the PostHog session ID from the incoming request header.
diff --git a/enterprise/tests/unit/test_api_key_aware_cors_middleware.py b/enterprise/tests/unit/test_api_key_aware_cors_middleware.py
new file mode 100644
index 0000000000..dd82297454
--- /dev/null
+++ b/enterprise/tests/unit/test_api_key_aware_cors_middleware.py
@@ -0,0 +1,189 @@
+"""Behavioral tests for ApiKeyAwareCORSMiddleware.
+
+The middleware splits incoming requests into two CORS regimes:
+
+ * API-key requests (Authorization: Bearer …, X-Session-API-Key,
+ X-Access-Token) and RFC 8628 device-flow paths get a permissive
+ policy: ``Access-Control-Allow-Origin: *`` with credentials disabled.
+ * Cookie / anonymous requests keep the strict origin allowlist with
+ credentials enabled.
+
+These tests exercise the dispatch matrix from a browser's perspective
+using Starlette's TestClient: a preflight + a real request from a
+non-allowlisted origin should be accepted with an API key and rejected
+without one.
+"""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from server.middleware import ApiKeyAwareCORSMiddleware
+
+ALLOWED_ORIGIN = 'https://app.all-hands.dev'
+FOREIGN_ORIGIN = 'http://localhost:3000'
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+
+ @app.get('/api/v1/settings')
+ def settings():
+ return {'ok': True}
+
+ @app.post('/oauth/device/authorize')
+ def authorize():
+ return {'device_code': 'd', 'user_code': 'u'}
+
+ app.add_middleware(
+ ApiKeyAwareCORSMiddleware,
+ allow_origins=[ALLOWED_ORIGIN],
+ )
+ return TestClient(app)
+
+
+class TestApiKeyAwareCORSMiddleware:
+ def test_api_key_preflight_from_foreign_origin_gets_wildcard_without_credentials(
+ self,
+ ):
+ # Arrange β€” a preflight that advertises `authorization` is heading
+ # for an API-key call from a non-allowlisted origin.
+ client = _build_client()
+
+ # Act
+ response = client.options(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Access-Control-Request-Method': 'GET',
+ 'Access-Control-Request-Headers': 'authorization, x-org-id',
+ },
+ )
+
+ # Assert
+ assert response.status_code == 200
+ assert response.headers.get('access-control-allow-origin') == '*'
+ # With wildcard origin, credentials MUST NOT be set β€” otherwise
+ # browsers reject the response. The middleware must omit it.
+ assert 'access-control-allow-credentials' not in {
+ k.lower() for k in response.headers
+ }
+
+ def test_cookie_preflight_from_foreign_origin_is_blocked(self):
+ # Arrange β€” a preflight without API-key headers is treated as a
+ # cookie/anonymous request and must hit the strict allowlist.
+ client = _build_client()
+
+ # Act
+ response = client.options(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Access-Control-Request-Method': 'GET',
+ 'Access-Control-Request-Headers': 'content-type',
+ },
+ )
+
+ # Assert β€” no allow-origin header means the browser will block.
+ assert response.headers.get('access-control-allow-origin') is None
+
+ def test_bearer_request_from_foreign_origin_returns_wildcard_cors(self):
+ # Arrange β€” actual GET (not preflight) with a Bearer token.
+ client = _build_client()
+
+ # Act
+ response = client.get(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Authorization': 'Bearer test-api-key',
+ },
+ )
+
+ # Assert β€” request succeeds and carries permissive CORS without
+ # credentials.
+ assert response.status_code == 200
+ assert response.headers.get('access-control-allow-origin') == '*'
+ assert 'access-control-allow-credentials' not in {
+ k.lower() for k in response.headers
+ }
+
+ @pytest.mark.parametrize(
+ 'auth_header',
+ ['X-Session-API-Key', 'X-Access-Token'],
+ )
+ def test_alternate_api_key_headers_return_wildcard_cors(self, auth_header):
+ # Arrange β€” the middleware also recognises MCP session keys and
+ # access tokens; both should route through the permissive path.
+ client = _build_client()
+
+ # Act
+ response = client.get(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ auth_header: 'test-key',
+ },
+ )
+
+ # Assert
+ assert response.status_code == 200
+ assert response.headers.get('access-control-allow-origin') == '*'
+ assert 'access-control-allow-credentials' not in {
+ k.lower() for k in response.headers
+ }
+
+ def test_cookie_request_from_allowed_origin_preserves_strict_cors(self):
+ # Arrange β€” the SaaS web UI calls the API from the allowlisted
+ # origin with cookies; that path must keep credentials enabled and
+ # echo the specific origin (never wildcard).
+ client = _build_client()
+
+ # Act
+ response = client.get(
+ '/api/v1/settings',
+ headers={'Origin': ALLOWED_ORIGIN},
+ )
+
+ # Assert
+ assert response.status_code == 200
+ assert response.headers.get('access-control-allow-origin') == ALLOWED_ORIGIN
+ assert response.headers.get('access-control-allow-credentials') == 'true'
+
+ def test_preflight_with_lookalike_header_does_not_match_authorization(self):
+ # Arrange β€” a custom header whose name contains "authorization" as
+ # a substring (e.g. ``x-my-authorization-token``) must NOT be
+ # treated as an API-key request. This guards against the
+ # substring-matching regression flagged in code review.
+ client = _build_client()
+
+ # Act
+ response = client.options(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Access-Control-Request-Method': 'GET',
+ 'Access-Control-Request-Headers': 'x-my-authorization-token',
+ },
+ )
+
+ # Assert β€” strict path means no allow-origin header for foreign origin.
+ assert response.headers.get('access-control-allow-origin') is None
+
+ def test_device_flow_path_is_permissive_without_api_key_header(self):
+ # Arrange β€” RFC 8628 endpoints are unauthenticated by design; they
+ # still need wildcard CORS so cross-origin clients can exchange
+ # device codes for API keys.
+ client = _build_client()
+
+ # Act
+ response = client.options(
+ '/oauth/device/authorize',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Access-Control-Request-Method': 'POST',
+ 'Access-Control-Request-Headers': 'content-type',
+ },
+ )
+
+ # Assert
+ assert response.headers.get('access-control-allow-origin') == '*'