Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: API key CORS header handling (#14835)

Graham Neubigae5a02b84230
diff --git a/enterprise/server/middleware.py b/enterprise/server/middleware.py
index ab28f11c95..d8ce74dcc9 100644
--- a/enterprise/server/middleware.py
+++ b/enterprise/server/middleware.py
@@ -15,6 +15,7 @@ from server.auth.gitlab_sync import schedule_gitlab_repo_sync
from server.auth.saas_user_auth import SaasUserAuth, token_manager
from server.routes.auth import set_response_cookie
from server.utils.url_utils import get_cookie_domain, get_cookie_samesite
+from starlette.types import ASGIApp, Receive, Scope, Send
from openhands.app_server.user_auth.user_auth import AuthType, UserAuth, get_user_auth
from openhands.app_server.utils.logger import openhands_logger as logger
@@ -229,6 +230,26 @@ _CREDENTIALLESS_PATH_PREFIXES = (
)
+class _OriginStrippingApp:
+ """Hide Origin from inner middleware after outer CORS classifies the request."""
+
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope['type'] != 'http':
+ await self.app(scope, receive, send)
+ return
+
+ inner_scope = dict(scope)
+ inner_scope['headers'] = tuple(
+ (name, value)
+ for name, value in scope['headers']
+ if name.lower() != b'origin'
+ )
+ await self.app(inner_scope, receive, send)
+
+
class ApiKeyAwareCORSMiddleware:
"""CORS dispatcher that loosens the policy for credential-less requests.
@@ -244,9 +265,9 @@ class ApiKeyAwareCORSMiddleware:
credentials enabled.
"""
- def __init__(self, app, allow_origins):
+ def __init__(self, app: ASGIApp, allow_origins: list[str]) -> None:
self._permissive = CORSMiddleware(
- app,
+ _OriginStrippingApp(app),
allow_origins=['*'],
allow_credentials=False,
allow_methods=['*'],
@@ -260,14 +281,14 @@ class ApiKeyAwareCORSMiddleware:
allow_headers=['*'],
)
- async def __call__(self, scope, receive, send):
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
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:
+ def _is_credentialless(scope: Scope) -> bool:
path = scope.get('path', '')
if any(path.startswith(prefix) for prefix in _CREDENTIALLESS_PATH_PREFIXES):
return True
diff --git a/enterprise/tests/unit/test_api_key_aware_cors_middleware.py b/enterprise/tests/unit/test_api_key_aware_cors_middleware.py
index dd82297454..6a74d57902 100644
--- a/enterprise/tests/unit/test_api_key_aware_cors_middleware.py
+++ b/enterprise/tests/unit/test_api_key_aware_cors_middleware.py
@@ -14,16 +14,20 @@ non-allowlisted origin should be accepted with an API key and rejected
without one.
"""
+import logging
+
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from server.middleware import ApiKeyAwareCORSMiddleware
+from openhands.app_server.middleware import LocalhostCORSMiddleware
+
ALLOWED_ORIGIN = 'https://app.all-hands.dev'
-FOREIGN_ORIGIN = 'http://localhost:3000'
+FOREIGN_ORIGIN = 'https://client.example.com'
-def _build_client() -> TestClient:
+def _build_client(with_inner_cors: bool = False) -> TestClient:
app = FastAPI()
@app.get('/api/v1/settings')
@@ -34,6 +38,9 @@ def _build_client() -> TestClient:
def authorize():
return {'device_code': 'd', 'user_code': 'u'}
+ if with_inner_cors:
+ app.add_middleware(LocalhostCORSMiddleware)
+
app.add_middleware(
ApiKeyAwareCORSMiddleware,
allow_origins=[ALLOWED_ORIGIN],
@@ -107,6 +114,27 @@ class TestApiKeyAwareCORSMiddleware:
k.lower() for k in response.headers
}
+ def test_bearer_request_does_not_inherit_inner_cors_headers_or_warnings(
+ self, caplog
+ ):
+ client = _build_client(with_inner_cors=True)
+
+ with caplog.at_level(logging.WARNING, logger='openhands.app_server.middleware'):
+ response = client.get(
+ '/api/v1/settings',
+ headers={
+ 'Origin': FOREIGN_ORIGIN,
+ 'Authorization': 'Bearer test-api-key',
+ },
+ )
+
+ 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
+ }
+ assert 'No CORS origins configured' not in caplog.text
+
@pytest.mark.parametrize(
'auth_header',
['X-Session-API-Key', 'X-Access-Token'],