Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(cognito): run saml2/oauth2 idpresponse and oauth2/token reentrantly (#1718)

kjdev543ba8e18fbe
diff --git a/ministack/app.py b/ministack/app.py
index 9092a492..519dc393 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1228,7 +1228,7 @@ async def _handle_cognito_body_request(method: str, path: str, headers: dict, bo
if path in ("/oauth2/login", "/login") and method == "POST":
return _get_module("cognito").handle_login_submit(method, path, headers, body, query_params)
if path == "/oauth2/token" and method == "POST":
- return _get_module("cognito").handle_oauth2_token(method, path, headers, body, query_params)
+ return await _get_module("cognito").handle_oauth2_token(method, path, headers, body, query_params)
if path in _COGNITO_USERINFO_PATHS and method == "POST":
return _get_module("cognito").handle_oauth2_userinfo(method, path, headers, body, query_params)
return None
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 4ab8391f..20c06aaa 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1893,11 +1893,20 @@ def _find_pool_by_client_id(client_id: str):
def _cleanup_expired_relay_codes():
- """Remove SAML/OIDC relay auth codes older than _AUTH_CODE_TTL."""
+ """Remove SAML/OIDC relay auth codes older than _AUTH_CODE_TTL.
+
+ `/saml2/idpresponse` and `/oauth2/idpresponse` run reentrantly, so this can
+ run on multiple threads at once while another thread concurrently inserts
+ or pops from `_auth_codes` — iterating the live dict view would raise
+ "dictionary changed size during iteration". Snapshot with `list(...)`
+ first, and `pop(..., None)` rather than `del` since a key collected into
+ `expired` may already have been consumed by another thread by the time
+ this one gets to remove it.
+ """
now = time.time()
- expired = [k for k, v in _auth_codes.items() if now - v.get("created_at", 0) > _AUTH_CODE_TTL]
+ expired = [k for k, v in list(_auth_codes.items()) if now - v.get("created_at", 0) > _AUTH_CODE_TTL]
for k in expired:
- del _auth_codes[k]
+ _auth_codes.pop(k, None)
def _authenticate_client(headers: dict, form: dict):
@@ -1923,10 +1932,21 @@ def _generate_auth_code() -> str:
def _cleanup_expired_codes():
+ """Remove expired managed-login authorization codes.
+
+ `/oauth2/token` runs reentrantly, so this can run on multiple threads at
+ once while `_issue_auth_code_redirect` (from `/login`, on the event loop)
+ or another `/oauth2/token` call concurrently inserts or pops from
+ `_authorization_codes` — iterating the live dict view would raise
+ "dictionary changed size during iteration". Snapshot with `list(...)`
+ first, and `pop(..., None)` rather than `del` since a key collected into
+ `expired` may already have been consumed by another thread by the time
+ this one gets to remove it.
+ """
now = time.time()
- expired = [code for code, entry in _authorization_codes.items() if entry["expires_at"] < now]
+ expired = [code for code, entry in list(_authorization_codes.items()) if entry["expires_at"] < now]
for code in expired:
- del _authorization_codes[code]
+ _authorization_codes.pop(code, None)
def _verify_pkce(code_verifier: str, code_challenge: str, method: str) -> bool:
@@ -1955,12 +1975,18 @@ async def handle_request(method, path, headers, body, query_params):
# Path-based endpoints (form-encoded or no body — must run before JSON parse)
if path.startswith("/oauth2/authorize"):
return handle_oauth2_authorize(method, path, headers, query_params)
+ # These three routes can invoke PreSignUp/PreTokenGeneration Lambda triggers,
+ # which may call back into ministack over HTTP — run_reentrant gives that
+ # callback its own thread instead of queuing behind this request's thread.
if path.startswith("/saml2/idpresponse"):
- return _saml2_idp_response(body, query_params)
+ return await run_reentrant(_saml2_idp_response, body, query_params,
+ thread_name="ministack-cognito-trigger")
if path.startswith("/oauth2/idpresponse"):
- return _oauth2_idp_response(method, body, query_params)
+ return await run_reentrant(_oauth2_idp_response, method, body, query_params,
+ thread_name="ministack-cognito-trigger")
if path.startswith("/oauth2/token"):
- return _oauth2_token({}, query_params, body, headers)
+ return await run_reentrant(_oauth2_token, {}, query_params, body, headers,
+ thread_name="ministack-cognito-trigger")
try:
data = json.loads(body) if body else {}
@@ -6154,8 +6180,14 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
if client and client.get("ClientSecret") and csec != client["ClientSecret"]:
return _oauth2_error("invalid_client", "Invalid client credentials.")
- # Consume code (one-time use)
- del _authorization_codes[code]
+ # Consume code (one-time use). This handler runs off the loop
+ # (run_reentrant), so two concurrent requests for the same code
+ # can both reach this point after passing validation above — pop()
+ # is the atomic single-use gate; the loser must not proceed past it
+ # even though it already "validated" against the (about-to-be-stale)
+ # entry.
+ if _authorization_codes.pop(code, None) is not entry:
+ return _oauth2_error("invalid_grant", "Invalid or expired authorization code.")
pool_id = entry["pool_id"]
pool = _get_pool_unscoped(pool_id)
@@ -6301,9 +6333,10 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non
})
-def handle_oauth2_token(method, path, headers, body, query_params):
+async def handle_oauth2_token(method, path, headers, body, query_params):
"""Public entry point called from app.py for POST /oauth2/token."""
- return _oauth2_token({}, query_params, body, headers)
+ return await run_reentrant(_oauth2_token, {}, query_params, body, headers,
+ thread_name="ministack-cognito-trigger")
# -- /oauth2/userInfo (GET/POST) ---------------------------------------------
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 2718c745..b18ac928 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2344,6 +2344,73 @@ def test_cognito_saml_presignup_lambda_autoconfirms_invited_user(cognito_idp, la
assert attrs.get("email_verified") == "true"
+def test_cognito_saml_presignup_lambda_reentrant_callback_does_not_deadlock(cognito_idp, lam):
+ """A PreSignUp trigger that calls back into ministack's own Cognito Admin
+ API (e.g. to look up the user as part of a federation-linking flow) must
+ run off the event loop thread, so the nested HTTP callback can be served
+ without queuing behind the trigger's own execution and hitting the Lambda
+ timeout.
+ """
+ handler = (
+ "import json, os, urllib.request\n"
+ "def handler(event, ctx):\n"
+ " req = urllib.request.Request(\n"
+ " os.environ['AWS_ENDPOINT_URL'],\n"
+ " data=json.dumps({\n"
+ " 'UserPoolId': event['userPoolId'],\n"
+ " 'Username': 'marker-user',\n"
+ " }).encode(),\n"
+ " headers={\n"
+ " 'Content-Type': 'application/x-amz-json-1.1',\n"
+ " 'X-Amz-Target': 'AWSCognitoIdentityProviderService.AdminGetUser',\n"
+ " },\n"
+ " method='POST',\n"
+ " )\n"
+ " with urllib.request.urlopen(req, timeout=6) as resp:\n"
+ " json.loads(resp.read())\n"
+ " return event\n"
+ )
+ fn_name = "ministack-presignup-reentrant-callback"
+ lam.create_function(
+ FunctionName=fn_name, Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},
+ Timeout=8,
+ )
+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]
+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"PreSignUp": fn_arn})
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="marker-user", MessageAction="SUPPRESS")
+
+ url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=TestSAML&state=mystate&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(url)
+ assert False, "Expected redirect"
+ except urllib.error.HTTPError as e:
+ location = e.headers.get("Location", "")
+ relay_state = _parse_qs(urlparse(location).query).get("RelayState", [""])[0]
+
+ saml_resp = _build_mock_saml_response(name_id="[email protected]")
+ form_data = _urlencode({"SAMLResponse": saml_resp, "RelayState": relay_state}).encode()
+ req = urllib.request.Request(
+ f"{ENDPOINT}/saml2/idpresponse", data=form_data,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ try:
+ _no_redirect_opener.open(req)
+ assert False, "Expected redirect"
+ except urllib.error.HTTPError as e:
+ assert e.code == 302, f"PreSignUp Lambda's own callback deadlocked or timed out: got {e.code}"
+
+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")
+ assert user["UserStatus"] == "EXTERNAL_PROVIDER"
+
+
# ---------------------------------------------------------------------------
# OIDC federation (external OIDC IdP — e.g. Keycloak in front of Cognito)
# ---------------------------------------------------------------------------
@@ -3877,6 +3944,79 @@ def test_oauth2_token_code_reuse():
assert resp2['error'] == 'invalid_grant'
+def test_oauth2_token_concurrent_code_redemption_is_single_use(monkeypatch):
+ """/oauth2/token runs off the event loop (run_reentrant), so two
+ concurrent requests for the same authorization code can race on the
+ check-then-delete of `_authorization_codes` instead of the interpreter
+ serialising them for free. Exactly one may pass the consume gate; the
+ other must get a clean invalid_grant — never a KeyError from an
+ unguarded double-delete.
+
+ Exercised as a direct, in-process unit test (not over HTTP): the actual
+ race window between validating a code and consuming it is a handful of
+ bytecodes, far too narrow to reproduce reliably by racing HTTP clients
+ against the live server. A barrier inserted at `_find_pool_by_client_id`
+ — the call site that immediately precedes the consume line — forces both
+ threads into that window at the same instant instead of hoping.
+ """
+ import threading
+
+ from ministack.services import cognito as _cognito_mod
+
+ code = "race-test-code-" + secrets.token_hex(8)
+ entry = {
+ "client_id": "race-client",
+ "pool_id": "nonexistent-pool", # never resolves — only the consume gate is under test
+ "redirect_uri": "",
+ "scope": "",
+ "username": "u",
+ "nonce": "",
+ "expires_at": time.time() + 300,
+ "code_challenge": None,
+ }
+ _cognito_mod._authorization_codes[code] = entry
+
+ barrier = threading.Barrier(2)
+ original_lookup = _cognito_mod._find_pool_by_client_id
+
+ def _synced_lookup(client_id):
+ barrier.wait(timeout=5)
+ return original_lookup(client_id)
+
+ monkeypatch.setattr(_cognito_mod, "_find_pool_by_client_id", _synced_lookup)
+
+ form = {"grant_type": "authorization_code", "code": code, "redirect_uri": "", "client_id": "race-client"}
+ raw_body = _urlencode(form).encode()
+ results = [None, None]
+
+ def _redeem(i):
+ try:
+ results[i] = _cognito_mod._oauth2_token({}, {}, raw_body, {})
+ except Exception as e: # noqa: BLE001 — surfaced by the assertion below, not swallowed
+ results[i] = e
+
+ threads = [threading.Thread(target=_redeem, args=(i,)) for i in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert not any(isinstance(r, Exception) for r in results), (
+ f"consume gate must reject the loser cleanly, never crash: {results}"
+ )
+ statuses = sorted(status for status, _, _ in results)
+ # One thread's pop() wins and proceeds (past this test's fake pool, so it
+ # surfaces as the pool-not-found path); the other must see the code
+ # already gone and get a clean invalid_grant. Never two winners, never an
+ # unhandled exception propagating as something other than these two.
+ assert statuses == [400, 400], f"expected two clean 400s (winner + loser), got {results}"
+ bodies = [json.loads(body)["error"] for _, _, body in results]
+ assert sorted(bodies) == ["invalid_grant", "server_error"], (
+ f"expected exactly one consumer (server_error past the gate) and one rejected "
+ f"replay (invalid_grant), got {bodies}"
+ )
+
+
def test_oauth2_token_refresh_token():
cognito_idp = make_client('cognito-idp')
pool_id, client = _setup_pool_with_user(cognito_idp)