Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Add CORS headers to Cognito OAuth2 / OIDC endpoints (#591)
Christopher Özbek2e81c466f74d
diff --git a/ministack/app.py b/ministack/app.pyindex ec340bce..fefcb252 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -662,7 +662,11 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_response = await _handle_cognito_get_request(method, path, headers, query_params)if response is not None:- return response+ # Cognito's OAuth2/OIDC endpoints (Hosted UI, /oauth2/*, /.well-known/*)+ # are typically called by browser-based OIDC clients and must therefore+ # carry the same `Access-Control-Allow-Origin: *` that every other data+ # plane response gets via _with_data_plane_headers.+ return _with_data_plane_headers(response, request_id)response = await _handle_ses_messages_request(method, path, headers, query_params)if response is not None:@@ -764,11 +768,12 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):return 200, {"Content-Type": "application/json"}, json.dumps({"applied": applied}).encode()-async def _handle_post_body_shortcuts(method: str, path: str, headers: dict, body: bytes, query_params: dict):+async def _handle_post_body_shortcuts(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):"""Handle body-dependent routes before the generic service router."""response = await _handle_cognito_body_request(method, path, headers, body, query_params)if response is not None:- return response+ # See _handle_pre_body_request: browser-based OIDC clients need CORS.+ return _with_data_plane_headers(response, request_id)return await _handle_admin_config_request(path, method, body)@@ -1436,7 +1441,7 @@ async def app(scope, receive, send):body = await _read_request_body(receive, method, headers)- if await _send_if_handled(send, await _handle_post_body_shortcuts(method, path, headers, body, query_params)):+ if await _send_if_handled(send, await _handle_post_body_shortcuts(method, path, headers, body, query_params, request_id)):returnif await _send_if_handled(diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 037e019e..c597ed1f 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1119,6 +1119,47 @@ def test_cognito_openid_configuration():assert "token_endpoint" in data+def test_cognito_browser_endpoints_send_cors_headers():+ """Cognito's OAuth2/OIDC endpoints must send `Access-Control-Allow-Origin`+ so browser-based OIDC clients can fetch them. Regression for the bug+ where the dispatcher in app.py returned raw response tuples for+ /.well-known/*, /oauth2/*, /login and /logout, bypassing the+ `_with_data_plane_headers` wrapper that every other data-plane response+ goes through."""+ import urllib.request++ from conftest import make_client+ cognito = make_client("cognito-idp")+ pool_id = cognito.create_user_pool(PoolName="cors-pool")["UserPool"]["Id"]++ # Public well-known endpoints — fetched cross-origin during OIDC discovery.+ for path in (+ f"/{pool_id}/.well-known/openid-configuration",+ f"/{pool_id}/.well-known/jwks.json",+ ):+ with urllib.request.urlopen(f"http://localhost:4566{path}") as r:+ assert r.headers.get("Access-Control-Allow-Origin") == "*", (+ f"missing CORS header on {path}"+ )++ # Token endpoint — POSTed cross-origin by the OIDC client. We don't care+ # about the body (an empty form yields a 4xx) — only that the CORS header+ # is present on the response.+ req = urllib.request.Request(+ "http://localhost:4566/oauth2/token",+ data=b"grant_type=authorization_code",+ method="POST",+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ resp = urllib.request.urlopen(req)+ except urllib.error.HTTPError as e:+ resp = e+ assert resp.headers.get("Access-Control-Allow-Origin") == "*", (+ "missing CORS header on /oauth2/token"+ )++# ===========================================================================# Identity Provider CRUD# ===========================================================================