Skip to content

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

_oauth2_idp_response() and _decode_id_token_unverified() helpers (#642)

Nahuel Nucerab3fc4ba0c559
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24696031..a0d9ab18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## Unreleased
### Fixed
+- **Cognito OIDC federation callback (`/oauth2/idpresponse`)** — federating Cognito to an external OIDC IdP (Keycloak, Auth0, Google, etc.) was half-wired: `/oauth2/authorize?identity_provider=<oidc-provider>` redirected the user to the IdP correctly, but routed the IdP's callback at `/saml2/idpresponse`, which only accepts SAML responses, so the IdP's `code`+`state` callback always 400'd. MiniStack now serves the canonical Cognito `/oauth2/idpresponse` endpoint: it looks up the relay context, exchanges the `code` against the IdP's `token_url` (`grant_type=authorization_code`), decodes the returned `id_token` (without signature verification — consistent with how MiniStack treats SigV4 and SAML signatures on the emulator side), applies `AttributeMapping` to the claims, provisions or refreshes the `{provider}_{sub}` federated user, and 302s the app back to its `redirect_uri` with a MiniStack-issued auth code. SAML federation continues to use `/saml2/idpresponse` unchanged. Reported by @ocr-lasagna.
- **Step Functions JSONata `Arguments` for `aws-sdk` Task states** — Task states with `QueryLanguage: "JSONata"` now evaluate `Arguments` before dispatching service integrations and evaluate success/Catch `Output` with `$states.input`, `$states.result`, and `$states.errorOutput`. This lets per-state JSONata workflows pass required SDK parameters locally instead of invoking services with an empty JSONPath-style payload. Contributed by @jayjanssen.
- **Step Functions JSONata coverage for Pass and Choice states** — Pass states now evaluate `Output` (previously the field was accepted and silently ignored, passing input through unchanged). Choice states now evaluate per-branch `Condition` and route accordingly (previously every `{% ... %}` condition was treated as falsy, so workflows always fell through to `Default`), and apply per-branch `Output` on the matched rule. The evaluator gained `< <= > >= + - * / % & and or in $count $length $not $string $number`, paren grouping, unary minus, and proper left-associative arithmetic — covering the JSONata operators used in real workflows. Reported by @youngkwangk.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index c7b6856e..3735f5e3 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -668,6 +668,11 @@ def _acs_url() -> str:
return f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}/saml2/idpresponse"
+def _oidc_callback_url() -> str:
+ """OIDC callback URL — external OIDC IdPs redirect back here with `code`+`state`."""
+ return f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}/oauth2/idpresponse"
+
+
def _build_saml_authn_request(pool_id: str, destination: str) -> str:
"""Build a minimal SAML AuthnRequest, deflate + base64-encode for HTTP-Redirect binding."""
req = Element("{urn:oasis:names:tc:SAML:2.0:protocol}AuthnRequest")
@@ -796,6 +801,8 @@ async def handle_request(method, path, headers, body, query_params):
return handle_oauth2_authorize(method, path, headers, query_params)
if path.startswith("/saml2/idpresponse"):
return _saml2_idp_response(body, query_params)
+ if path.startswith("/oauth2/idpresponse"):
+ return _oauth2_idp_response(method, body, query_params)
if path.startswith("/oauth2/token"):
return _oauth2_token({}, query_params, body, headers)
@@ -2542,7 +2549,7 @@ def _oauth2_authorize_federation(query_params):
redirect_url = authorize_url + ("&" if "?" in authorize_url else "?") + urlencode({
"response_type": response_type or "code",
"client_id": oidc_client_id,
- "redirect_uri": _acs_url(),
+ "redirect_uri": _oidc_callback_url(),
"scope": details.get("authorize_scopes", scope),
"state": relay_key,
})
@@ -2714,6 +2721,210 @@ def _saml2_idp_response(body: bytes, query_params):
return 302, {"Location": location, "Content-Type": "text/html"}, b""
+# -- /oauth2/idpresponse (GET/POST) -----------------------------------------
+
+def _decode_id_token_unverified(id_token: str) -> dict:
+ """Decode a JWT id_token payload without verifying its signature.
+
+ Matches MiniStack's wider stance on emulator-side crypto checks: we don't
+ verify SigV4 on AWS requests and we don't verify SAML response signatures
+ on `/saml2/idpresponse`, so we don't verify OIDC id_token signatures here
+ either. The threat model for a local emulator is developer testing, not
+ token forgery, and adding a JWKS fetch + RS256 verify would be inconsistent
+ with the rest of the codebase. Documented gap from real AWS Cognito.
+ """
+ parts = id_token.split(".")
+ if len(parts) < 2:
+ raise ValueError("id_token is not a JWT (expected at least header.payload)")
+ payload_b64 = parts[1]
+ payload_b64 += "=" * (-len(payload_b64) % 4) # base64url padding
+ payload_bytes = base64.urlsafe_b64decode(payload_b64.encode("ascii"))
+ return json.loads(payload_bytes.decode("utf-8"))
+
+
+def _oauth2_idp_response(method, body, query_params):
+ """GET/POST /oauth2/idpresponse — external OIDC IdP callback.
+
+ Mirrors `_saml2_idp_response` for the OIDC `authorization_code` flow:
+ the IdP redirects back to MiniStack with `code` and `state` in the query
+ string (or POST body, depending on the IdP's `response_mode`). MiniStack
+ exchanges the code for tokens at the IdP's `token_url`, decodes the
+ returned id_token (no signature verification — see
+ `_decode_id_token_unverified`), provisions or refreshes the federated
+ user, and redirects to the app's `redirect_uri` with a MiniStack-issued
+ authorization code so the app's existing `/oauth2/token` flow continues
+ to work.
+ """
+ import urllib.error
+ import urllib.request
+
+ # Pull `code` + `state` from query string first, then POST form body.
+ code = _qp(query_params, "code")
+ state = _qp(query_params, "state")
+ if (not code or not state) and body and method == "POST":
+ try:
+ form = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)
+ code = code or (form.get("code", [""])[0])
+ state = state or (form.get("state", [""])[0])
+ except Exception:
+ pass
+
+ if not code:
+ return error_response_json("InvalidParameterException", "code is required.", 400)
+ if not state:
+ return error_response_json("InvalidParameterException", "state is required.", 400)
+
+ relay = _auth_codes.pop(state, None)
+ if not relay or relay.get("type") != "relay":
+ return error_response_json("InvalidParameterException", "Invalid or expired state.", 400)
+
+ pool_id = relay["pool_id"]
+ client_id = relay["client_id"]
+ redirect_uri = relay["redirect_uri"]
+ app_state = relay.get("state", "")
+ provider_name = relay["provider_name"]
+
+ pool = _get_pool_unscoped(pool_id)
+ if not pool:
+ return error_response_json("ResourceNotFoundException", f"User pool {pool_id} not found.", 400)
+
+ provider = pool.get("_identity_providers", {}).get(provider_name)
+ if not provider or provider.get("ProviderType", "") != "OIDC":
+ return error_response_json("ResourceNotFoundException",
+ f"OIDC provider {provider_name} not found.", 400)
+
+ details = provider.get("ProviderDetails", {})
+ oidc_issuer = details.get("oidc_issuer", "")
+ token_url = details.get("token_url") or (f"{oidc_issuer}/token" if oidc_issuer else "")
+ if not token_url:
+ return error_response_json("InvalidParameterException",
+ "OIDC provider has no token_url or oidc_issuer.", 400)
+
+ oidc_client_id = details.get("client_id", "")
+ oidc_client_secret = details.get("client_secret", "")
+
+ # Exchange code for tokens at the IdP's token endpoint.
+ token_body = urlencode({
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": _oidc_callback_url(),
+ "client_id": oidc_client_id,
+ "client_secret": oidc_client_secret,
+ }).encode("ascii")
+ req = urllib.request.Request(
+ token_url,
+ data=token_body,
+ headers={"Content-Type": "application/x-www-form-urlencoded",
+ "Accept": "application/json"},
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ token_payload = resp.read()
+ except urllib.error.HTTPError as exc:
+ logger.warning("Cognito: OIDC token exchange failed: HTTP %s — %s",
+ exc.code, exc.reason)
+ return error_response_json("InvalidParameterException",
+ f"OIDC token exchange failed: HTTP {exc.code}", 400)
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ logger.warning("Cognito: OIDC token exchange failed: %s", exc)
+ return error_response_json("InvalidParameterException",
+ f"OIDC token exchange failed: {exc}", 400)
+
+ try:
+ token_data = json.loads(token_payload.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError) as exc:
+ return error_response_json("InvalidParameterException",
+ f"OIDC token endpoint returned non-JSON: {exc}", 400)
+
+ id_token = token_data.get("id_token", "")
+ access_token = token_data.get("access_token", "")
+ if not id_token:
+ return error_response_json("InvalidParameterException",
+ "OIDC token response missing id_token.", 400)
+
+ try:
+ claims = _decode_id_token_unverified(id_token)
+ except (ValueError, json.JSONDecodeError, base64.binascii.Error) as exc:
+ return error_response_json("InvalidParameterException",
+ f"Could not decode id_token: {exc}", 400)
+
+ # Apply attribute mapping (IdP claim → Cognito attribute), same shape
+ # as the SAML branch.
+ attr_mapping = provider.get("AttributeMapping", {})
+ reverse_mapping = {v: k for k, v in attr_mapping.items()}
+ user_attrs = {}
+ for idp_claim, value in claims.items():
+ if idp_claim in ("iss", "aud", "exp", "iat", "nbf", "jti", "azp", "auth_time"):
+ continue
+ if not isinstance(value, (str, int, float, bool)):
+ continue
+ cognito_attr = reverse_mapping.get(idp_claim, idp_claim)
+ user_attrs[cognito_attr] = str(value)
+
+ # Stable identifier: prefer `sub` from id_token, fall back to `email` or
+ # a generated UUID so users can be re-found on subsequent logins.
+ name_id = (claims.get("sub")
+ or claims.get("email")
+ or user_attrs.get("email")
+ or "")
+ if not name_id:
+ return error_response_json("InvalidParameterException",
+ "OIDC id_token has no `sub` or `email` claim.", 400)
+
+ username = f"{provider_name}_{name_id}"
+ existing_user = pool["_users"].get(username)
+ now = _now_epoch()
+
+ if existing_user:
+ existing_dict = _attr_list_to_dict(existing_user.get("Attributes", []))
+ existing_dict.update(user_attrs)
+ existing_user["Attributes"] = _dict_to_attr_list(existing_dict)
+ existing_user["UserLastModifiedDate"] = now
+ sub = existing_dict.get("sub", new_uuid())
+ else:
+ sub = new_uuid()
+ user_attrs["sub"] = sub
+ if "email" not in user_attrs and "@" in name_id:
+ user_attrs["email"] = name_id
+ user = {
+ "Username": username,
+ "Attributes": _dict_to_attr_list(user_attrs),
+ "UserCreateDate": now,
+ "UserLastModifiedDate": now,
+ "Enabled": True,
+ "UserStatus": "EXTERNAL_PROVIDER",
+ "MFAOptions": [],
+ "_password": "",
+ "_groups": [],
+ "_tokens": [],
+ }
+ pool["_users"][username] = user
+ pool["EstimatedNumberOfUsers"] = len(pool["_users"])
+
+ # Issue MiniStack auth code so the app's /oauth2/token call works.
+ _cleanup_expired_relay_codes()
+ ms_code = secrets.token_urlsafe(32)
+ _auth_codes[ms_code] = {
+ "type": "code",
+ "pool_id": pool_id,
+ "client_id": client_id,
+ "username": username,
+ "sub": sub,
+ "redirect_uri": redirect_uri,
+ "scopes": relay.get("scope", "openid"),
+ "created_at": time.time(),
+ "_oidc_access_token": access_token, # kept for /oauth2/userInfo passthrough
+ }
+
+ params = {"code": ms_code}
+ if app_state:
+ params["state"] = app_state
+ location = redirect_uri + ("&" if "?" in redirect_uri else "?") + urlencode(params)
+ logger.info("Cognito: OIDC IdP response — user %s created/updated, redirecting to app", username)
+ return 302, {"Location": location, "Content-Type": "text/html"}, b""
+
+
# -- /login (POST) ----------------------------------------------------------
def handle_login_submit(method, path, headers, body, query_params):
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 2c62ccf7..f73be343 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1475,6 +1475,214 @@ def test_cognito_saml_full_flow(cognito_idp):
assert attrs.get("name") == "John Doe"
+# ---------------------------------------------------------------------------
+# OIDC federation (external OIDC IdP — e.g. Keycloak in front of Cognito)
+# ---------------------------------------------------------------------------
+
+def _b64url(data: bytes) -> str:
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
+
+
+def _unsigned_id_token(claims: dict) -> str:
+ """Build a JWS-Compact id_token with header.payload.signature.
+ Signature is a dummy `notsigned` string — MiniStack doesn't verify."""
+ header = _b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode())
+ payload = _b64url(json.dumps(claims).encode())
+ return f"{header}.{payload}.notsigned"
+
+
+def _start_fake_oidc_idp(claims):
+ """Spin up a local HTTP server acting as an OIDC IdP's token endpoint.
+
+ Returns (token_url, recorded_request, stop_fn). recorded_request is mutated
+ in place when the IdP receives the token exchange POST so tests can assert
+ on what MiniStack actually sent on the wire.
+ """
+ import http.server
+ import threading
+
+ recorded = {}
+
+ class _Handler(http.server.BaseHTTPRequestHandler):
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", "0"))
+ body_bytes = self.rfile.read(length)
+ recorded["path"] = self.path
+ recorded["headers"] = dict(self.headers)
+ recorded["body"] = body_bytes.decode("utf-8")
+ recorded["form"] = {
+ k: v[0] for k, v in _parse_qs(recorded["body"]).items()
+ }
+ payload = json.dumps({
+ "access_token": "fake-access-token",
+ "id_token": _unsigned_id_token(claims),
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ }).encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *args, **kwargs):
+ pass
+
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Handler)
+ port = srv.server_address[1]
+ thread = threading.Thread(target=srv.serve_forever, daemon=True)
+ thread.start()
+ token_url = f"http://127.0.0.1:{port}/token"
+
+ def stop():
+ srv.shutdown()
+ srv.server_close()
+ thread.join(timeout=2)
+
+ return token_url, recorded, stop
+
+
+def _setup_oidc_pool(cognito_idp, token_url):
+ pid = cognito_idp.create_user_pool(PoolName="OIDCFedPool")["UserPool"]["Id"]
+ client = cognito_idp.create_user_pool_client(
+ UserPoolId=pid,
+ ClientName="OIDCApp",
+ CallbackURLs=["http://localhost:3000/callback"],
+ AllowedOAuthFlows=["code"],
+ AllowedOAuthScopes=["openid", "email"],
+ SupportedIdentityProviders=["TestOIDC"],
+ )["UserPoolClient"]
+ cognito_idp.create_identity_provider(
+ UserPoolId=pid,
+ ProviderName="TestOIDC",
+ ProviderType="OIDC",
+ ProviderDetails={
+ "oidc_issuer": "https://idp.example.com",
+ "authorize_url": "https://idp.example.com/authorize",
+ "token_url": token_url,
+ "client_id": "oidc-client-id",
+ "client_secret": "oidc-client-secret",
+ "authorize_scopes": "openid email profile",
+ },
+ AttributeMapping={"email": "email", "name": "name"},
+ )
+ return pid, client["ClientId"]
+
+
+def test_cognito_oauth2_authorize_oidc_redirect(cognito_idp):
+ """GET /oauth2/authorize with an OIDC identity_provider 302s to the IdP
+ with redirect_uri pointing at MiniStack's /oauth2/idpresponse."""
+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "ignored"})
+ try:
+ _pid, cid = _setup_oidc_pool(cognito_idp, token_url)
+ url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=TestOIDC&state=mystate&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(url)
+ assert False, "Expected 302"
+ except urllib.error.HTTPError as e:
+ assert e.code == 302
+ location = e.headers.get("Location", "")
+ assert "idp.example.com/authorize" in location
+ qs = _parse_qs(urlparse(location).query)
+ assert qs["client_id"] == ["oidc-client-id"]
+ # The redirect_uri MS hands to the IdP must point at MS's OIDC
+ # callback, not the SAML one (regression guard for the original bug).
+ assert qs["redirect_uri"] == [f"{ENDPOINT}/oauth2/idpresponse"]
+ assert qs["state"] # relay key present
+ finally:
+ stop()
+
+
+def test_cognito_oidc_full_flow(cognito_idp):
+ """End-to-end OIDC federation: authorize → IdP callback → token exchange
+ against fake IdP → user provisioned → app redirect with MS auth code."""
+ claims = {
+ "sub": "user-9001",
+ "email": "[email protected]",
+ "name": "Alice External",
+ }
+ token_url, recorded, stop = _start_fake_oidc_idp(claims)
+ try:
+ pid, cid = _setup_oidc_pool(cognito_idp, token_url)
+
+ # Step 1: kick off authorize, grab the relay state from the IdP redirect.
+ authorize_url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=TestOIDC&state=appstate&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(authorize_url)
+ assert False, "Expected 302"
+ except urllib.error.HTTPError as e:
+ idp_redirect = e.headers.get("Location", "")
+ relay_state = _parse_qs(urlparse(idp_redirect).query)["state"][0]
+
+ # Step 2: simulate the OIDC IdP calling back with code+state.
+ cb_url = (
+ f"{ENDPOINT}/oauth2/idpresponse?"
+ f"code=idp-issued-code&state={relay_state}"
+ )
+ try:
+ _no_redirect_opener.open(cb_url)
+ assert False, "Expected 302 back to the app"
+ except urllib.error.HTTPError as e:
+ callback_location = e.headers.get("Location", "")
+
+ # Step 3: MS must have called the IdP's token endpoint with the right
+ # grant_type / code / redirect_uri / client credentials.
+ assert recorded.get("path") == "/token"
+ form = recorded["form"]
+ assert form["grant_type"] == "authorization_code"
+ assert form["code"] == "idp-issued-code"
+ assert form["redirect_uri"] == f"{ENDPOINT}/oauth2/idpresponse"
+ assert form["client_id"] == "oidc-client-id"
+ assert form["client_secret"] == "oidc-client-secret"
+
+ # Step 4: MS must redirect to the app callback with a MS-issued code
+ # and the original app state.
+ assert "localhost:3000/callback" in callback_location
+ cb_qs = _parse_qs(urlparse(callback_location).query)
+ assert cb_qs["state"] == ["appstate"]
+ ms_code = cb_qs["code"][0]
+ assert ms_code
+
+ # Step 5: the federated user was provisioned under the OIDC provider
+ # namespace, with the id_token claims mapped through AttributeMapping.
+ federated_username = "TestOIDC_user-9001"
+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username=federated_username)
+ assert user["UserStatus"] == "EXTERNAL_PROVIDER"
+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}
+ assert attrs["email"] == "[email protected]"
+ assert attrs["name"] == "Alice External"
+ finally:
+ stop()
+
+
+def test_cognito_oidc_callback_invalid_state(cognito_idp):
+ """`/oauth2/idpresponse` with an unknown state returns 400 — relay codes
+ are single-use, expired, and tied to a prior /oauth2/authorize call."""
+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "ignored"})
+ try:
+ _setup_oidc_pool(cognito_idp, token_url)
+ cb_url = f"{ENDPOINT}/oauth2/idpresponse?code=x&state=nonexistent"
+ try:
+ _no_redirect_opener.open(cb_url)
+ assert False, "Expected 400"
+ except urllib.error.HTTPError as e:
+ assert e.code == 400
+ body = json.loads(e.read())
+ assert "InvalidParameterException" in body.get("__type", "")
+ finally:
+ stop()
+
+
def test_cognito_oauth2_token_invalid_code():
"""POST /oauth2/token with invalid code returns 400."""
data = b"grant_type=authorization_code&code=invalid_code&client_id=x"