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
feat(cognito): add Identity Provider CRUD and federated SAML/OIDC auth flow (#329)
Gabriel Prandod67c69593ffc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex beb704dc..e21d4986 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added+- **Cognito federated SAML/OIDC auth flow** — `GET /oauth2/authorize` (redirects to external SAML/OIDC IdP), `POST /saml2/idpresponse` (parses SAML assertion, creates federated user, issues authorization code), and `POST /oauth2/token` now supports `grant_type=authorization_code` for full SSO flow. Also adds `GetIdentityProviderByIdentifier`. Closes #325.++---+## [1.2.13] — 2026-04-14### Addeddiff --git a/ministack/core/router.py b/ministack/core/router.pyindex 04d807c3..48e98290 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -489,6 +489,10 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "lambda"if path_lower.startswith("/oauth2/token"):return "cognito-idp"+ if path_lower.startswith("/oauth2/authorize"):+ return "cognito-idp"+ if path_lower.startswith("/saml2/idpresponse"):+ return "cognito-idp"if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):return "ecs"# smithy-rpc-v2-cbor path: /service/ServiceName/operation/ActionNamediff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex ab57679b..100e5110 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -22,6 +22,8 @@ User Pools operations:AdminResetUserPassword, AdminUserGlobalSignOut,GlobalSignOut, RevokeToken,CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain,+ CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider,+ DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier,GetUserPoolMfaConfig, SetUserPoolMfaConfig,AssociateSoftwareToken, VerifySoftwareToken,TagResource, UntagResource, ListTagsForResource.@@ -35,6 +37,11 @@ Identity Pools operations:UnlinkDeveloperIdentity, UnlinkIdentity,TagResource, UntagResource, ListTagsForResource.+Data-plane endpoints (path-based, form-encoded):+ GET /oauth2/authorize — redirect to external SAML/OIDC IdP+ POST /saml2/idpresponse — receive SAML assertion, create user, issue auth code+ POST /oauth2/token — exchange authorization_code or client_credentials for tokens+Wire protocol:Both services use JSON with X-Amz-Target header.cognito-idp credential scope: cognito-idp@@ -44,15 +51,19 @@ Wire protocol:import base64import copy-import osimport jsonimport logging+import osimport reimport secretsimport stringimport time+import zlibfrom datetime import datetime, timezone-from urllib.parse import parse_qs+from urllib.parse import parse_qs, urlencode+from xml.etree.ElementTree import Element, SubElement, tostring as xml_tostring++from defusedxml.ElementTree import fromstring as safe_xml_parsefrom ministack.core.persistence import load_state, PERSIST_STATEfrom ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid@@ -126,6 +137,14 @@ def well_known_openid_configuration(pool_id: str, region: str | None = None):return 200, {"Content-Type": "application/json"}, json.dumps(doc).encode()REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")+_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))++# SAML XML namespaces+_SAML_NS = {+ "samlp": "urn:oasis:names:tc:SAML:2.0:protocol",+ "saml": "urn:oasis:names:tc:SAML:2.0:assertion",+}# ---------------------------------------------------------------------------# In-memory state — User Pools (cognito-idp)@@ -141,6 +160,7 @@ _user_pools = AccountScopedDict()# _clients: {client_id -> client_dict},# _users: {username -> user_dict},# _groups: {group_name -> group_dict},+# _identity_providers: {provider_name -> provider_dict},# }_pool_domain_map = AccountScopedDict() # domain -> pool_id@@ -161,6 +181,13 @@ _identity_pools = AccountScopedDict()_identity_tags = AccountScopedDict() # identity_pool_id -> {key: value}+# ---------------------------------------------------------------------------+# In-memory state — OAuth2 authorization codes (ephemeral, not persisted)+# ---------------------------------------------------------------------------++_auth_codes = {} # code -> {pool_id, client_id, username, redirect_uri, scopes, state, created_at}+_AUTH_CODE_TTL = 300 # 5 minutes+# ── Persistence ────────────────────────────────────────────@@ -336,6 +363,72 @@ def _merge_attributes(existing: list, updates: list) -> list:return _dict_to_attr_list(d)+# ---------------------------------------------------------------------------+# SAML / OAuth2 helpers+# ---------------------------------------------------------------------------++def _acs_url() -> str:+ """Assertion Consumer Service URL for SAML responses."""+ return f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}/saml2/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")+ req.set("ID", "_" + new_uuid())+ req.set("Version", "2.0")+ req.set("IssueInstant", datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))+ req.set("AssertionConsumerServiceURL", _acs_url())+ req.set("Destination", destination)+ req.set("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")+ issuer = SubElement(req, "{urn:oasis:names:tc:SAML:2.0:assertion}Issuer")+ issuer.text = f"urn:amazon:cognito:sp:{pool_id}"+ xml_bytes = xml_tostring(req, encoding="unicode").encode("utf-8")+ # Raw deflate (strip zlib header/checksum) per SAML HTTP-Redirect binding+ deflated = zlib.compress(xml_bytes)[2:-4]+ return base64.b64encode(deflated).decode()+++def _parse_saml_response(saml_response_b64: str) -> dict:+ """Decode and parse a SAML Response, extract NameID and attributes."""+ xml_bytes = base64.b64decode(saml_response_b64)+ root = safe_xml_parse(xml_bytes)+ name_id_el = root.find(".//{urn:oasis:names:tc:SAML:2.0:assertion}Subject/"+ "{urn:oasis:names:tc:SAML:2.0:assertion}NameID")+ name_id = name_id_el.text if name_id_el is not None else None+ attrs = {}+ for attr_el in root.findall(".//{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement/"+ "{urn:oasis:names:tc:SAML:2.0:assertion}Attribute"):+ attr_name = attr_el.get("Name", "")+ val_el = attr_el.find("{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue")+ if val_el is not None and val_el.text:+ attrs[attr_name] = val_el.text+ return {"name_id": name_id, "attributes": attrs}+++def _find_pool_and_client(client_id: str):+ """Find the pool and client dict by client_id. Returns (pool_id, pool, client) or Nones."""+ for pid, pool in _user_pools.items():+ client = pool["_clients"].get(client_id)+ if client:+ return pid, pool, client+ return None, None, None+++def _cleanup_expired_codes():+ """Remove auth codes older than _AUTH_CODE_TTL."""+ now = time.time()+ expired = [k for k, v in _auth_codes.items() if now - v.get("created_at", 0) > _AUTH_CODE_TTL]+ for k in expired:+ del _auth_codes[k]+++def _get_qp(query_params: dict, key: str, default: str = "") -> str:+ """Extract a single value from query_params (which may have list values)."""+ v = query_params.get(key, default)+ return v[0] if isinstance(v, list) else v++# ---------------------------------------------------------------------------# Entry points — two separate handle_request functions# ---------------------------------------------------------------------------@@ -344,6 +437,14 @@ async def handle_request(method, path, headers, body, query_params):"""Unified entry point — dispatches to IDP or Identity based on target prefix."""target = headers.get("x-amz-target", "")+ # Path-based endpoints (form-encoded or no body — must run before JSON parse)+ if path.startswith("/oauth2/authorize"):+ return _oauth2_authorize(query_params)+ if path.startswith("/saml2/idpresponse"):+ return _saml2_idp_response(body, query_params)+ if path.startswith("/oauth2/token"):+ return _oauth2_token({}, query_params, body)+try:data = json.loads(body) if body else {}except json.JSONDecodeError:@@ -357,10 +458,6 @@ async def handle_request(method, path, headers, body, query_params):action = target.split(".")[-1]return _dispatch_idp(action, data)- # Path-based fallback for REST-style calls (e.g. /oauth2/token)- if path.startswith("/oauth2/token"):- return _oauth2_token(data, query_params, body)-return error_response_json("InvalidAction", f"Unknown Cognito target: {target}", 400)@@ -430,6 +527,7 @@ def _dispatch_idp(action: str, data: dict):"UpdateIdentityProvider": _update_identity_provider,"DeleteIdentityProvider": _delete_identity_provider,"ListIdentityProviders": _list_identity_providers,+ "GetIdentityProviderByIdentifier": _get_identity_provider_by_identifier,# MFA"GetUserPoolMfaConfig": _get_user_pool_mfa_config,"SetUserPoolMfaConfig": _set_user_pool_mfa_config,@@ -529,6 +627,7 @@ def _create_user_pool(data):"_clients": {},"_users": {},"_groups": {},+ "_identity_providers": {},}if data.get("DeviceConfiguration"):pool["DeviceConfiguration"] = data["DeviceConfiguration"]@@ -1612,32 +1711,48 @@ def _describe_user_pool_domain(data):# IDENTITY PROVIDERS# ===========================================================================+VALID_PROVIDER_TYPES = {"SAML", "Facebook", "Google", "LoginWithAmazon", "SignInWithApple", "OIDC"}++def _create_identity_provider(data):pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)if err:return errprovider_name = data.get("ProviderName")+ if not provider_name:+ return error_response_json("InvalidParameterException", "ProviderName is required.", 400)provider_type = data.get("ProviderType")- if not provider_name or not provider_type:- return error_response_json(- "InvalidParameterException", "ProviderName and ProviderType are required.", 400)+ if not provider_type:+ return error_response_json("InvalidParameterException", "ProviderType is required.", 400)+ if provider_type not in VALID_PROVIDER_TYPES:+ return error_response_json("InvalidParameterException", f"Invalid ProviderType: {provider_type}.", 400)providers = pool.setdefault("_identity_providers", {})if provider_name in providers:- return error_response_json(- "DuplicateProviderException",- f"A provider with name {provider_name} already exists.", 400)+ return error_response_json("DuplicateProviderException",+ f"A provider with name {provider_name} already exists.", 400)+ idp_identifiers = data.get("IdpIdentifiers", [])+ # Check identifier uniqueness across all providers in this pool+ existing_ids = set()+ for p in providers.values():+ existing_ids.update(p.get("IdpIdentifiers", []))+ for ident in idp_identifiers:+ if ident in existing_ids:+ return error_response_json("DuplicateProviderException",+ f"IdpIdentifier {ident} is already in use.", 400)+ now = _now_epoch()provider = {"UserPoolId": pid,"ProviderName": provider_name,"ProviderType": provider_type,"ProviderDetails": data.get("ProviderDetails", {}),"AttributeMapping": data.get("AttributeMapping", {}),- "IdpIdentifiers": data.get("IdpIdentifiers", []),- "LastModifiedDate": int(time.time()),- "CreationDate": int(time.time()),+ "IdpIdentifiers": idp_identifiers,+ "CreationDate": now,+ "LastModifiedDate": now,}providers[provider_name] = provider+ logger.info("Cognito: CreateIdentityProvider %s in pool %s", provider_name, pid)return json_response({"IdentityProvider": provider})@@ -1650,9 +1765,8 @@ def _describe_identity_provider(data):providers = pool.get("_identity_providers", {})provider = providers.get(provider_name)if not provider:- return error_response_json(- "ResourceNotFoundException",- f"Identity provider {provider_name} does not exist.", 400)+ return error_response_json("ResourceNotFoundException",+ f"Identity provider {provider_name} does not exist.", 400)return json_response({"IdentityProvider": provider})@@ -1665,16 +1779,25 @@ def _update_identity_provider(data):providers = pool.get("_identity_providers", {})provider = providers.get(provider_name)if not provider:- return error_response_json(- "ResourceNotFoundException",- f"Identity provider {provider_name} does not exist.", 400)+ return error_response_json("ResourceNotFoundException",+ f"Identity provider {provider_name} does not exist.", 400)if "ProviderDetails" in data:provider["ProviderDetails"] = data["ProviderDetails"]if "AttributeMapping" in data:provider["AttributeMapping"] = data["AttributeMapping"]if "IdpIdentifiers" in data:- provider["IdpIdentifiers"] = data["IdpIdentifiers"]- provider["LastModifiedDate"] = int(time.time())+ new_ids = data["IdpIdentifiers"]+ # Check uniqueness against other providers in the pool+ existing_ids = set()+ for name, p in providers.items():+ if name != provider_name:+ existing_ids.update(p.get("IdpIdentifiers", []))+ for ident in new_ids:+ if ident in existing_ids:+ return error_response_json("DuplicateProviderException",+ f"IdpIdentifier {ident} is already in use.", 400)+ provider["IdpIdentifiers"] = new_ids+ provider["LastModifiedDate"] = _now_epoch()return json_response({"IdentityProvider": provider})@@ -1686,10 +1809,10 @@ def _delete_identity_provider(data):provider_name = data.get("ProviderName")providers = pool.get("_identity_providers", {})if provider_name not in providers:- return error_response_json(- "ResourceNotFoundException",- f"Identity provider {provider_name} does not exist.", 400)+ return error_response_json("ResourceNotFoundException",+ f"Identity provider {provider_name} does not exist.", 400)del providers[provider_name]+ logger.info("Cognito: DeleteIdentityProvider %s from pool %s", provider_name, pid)return json_response({})@@ -1699,18 +1822,40 @@ def _list_identity_providers(data):if err:return errproviders = pool.get("_identity_providers", {})- max_results = data.get("MaxResults", 60)- items = list(providers.values())[:max_results]- # ListIdentityProviders returns a lighter shape per AWS docs- out = []- for p in items:- out.append({- "ProviderName": p["ProviderName"],- "ProviderType": p["ProviderType"],- "LastModifiedDate": p["LastModifiedDate"],- "CreationDate": p["CreationDate"],- })- return json_response({"Providers": out})+ max_results = min(data.get("MaxResults", 60), 60)+ next_token = data.get("NextToken")+ sorted_providers = sorted(providers.values(), key=lambda p: p["CreationDate"])+ start = int(next_token) if next_token else 0+ page = sorted_providers[start:start + max_results]+ resp = {+ "Providers": [+ {+ "ProviderName": p["ProviderName"],+ "ProviderType": p["ProviderType"],+ "LastModifiedDate": p["LastModifiedDate"],+ "CreationDate": p["CreationDate"],+ }+ for p in page+ ]+ }+ if start + max_results < len(sorted_providers):+ resp["NextToken"] = str(start + max_results)+ return json_response(resp)+++def _get_identity_provider_by_identifier(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ identifier = data.get("IdpIdentifier")+ if not identifier:+ return error_response_json("InvalidParameterException", "IdpIdentifier is required.", 400)+ for provider in pool.get("_identity_providers", {}).values():+ if identifier in provider.get("IdpIdentifiers", []):+ return json_response({"IdentityProvider": provider})+ return error_response_json("ResourceNotFoundException",+ f"Identity provider with identifier {identifier} does not exist.", 400)# ===========================================================================@@ -1863,11 +2008,203 @@ def _idp_list_tags_for_resource(data):# ===========================================================================-# OAUTH2 TOKEN ENDPOINT (data plane)+# OAUTH2 / SAML DATA-PLANE ENDPOINTS# ===========================================================================+def _oauth2_authorize(query_params):+ """GET /oauth2/authorize — redirect to external IdP (SAML or OIDC)."""+ response_type = _get_qp(query_params, "response_type")+ client_id = _get_qp(query_params, "client_id")+ redirect_uri = _get_qp(query_params, "redirect_uri")+ identity_provider = _get_qp(query_params, "identity_provider")+ state = _get_qp(query_params, "state")+ scope = _get_qp(query_params, "scope", "openid")++ if not client_id:+ return error_response_json("InvalidParameterException", "client_id is required.", 400)++ pool_id, pool, client = _find_pool_and_client(client_id)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {client_id} not found.", 400)++ # Validate redirect_uri against CallbackURLs (skip if empty for dev convenience)+ callback_urls = client.get("CallbackURLs", [])+ if callback_urls and redirect_uri not in callback_urls:+ return error_response_json("InvalidParameterException",+ f"redirect_uri {redirect_uri} is not in CallbackURLs.", 400)++ if not identity_provider:+ return error_response_json("InvalidParameterException", "identity_provider is required.", 400)++ provider = pool.get("_identity_providers", {}).get(identity_provider)+ if not provider:+ return error_response_json("ResourceNotFoundException",+ f"Identity provider {identity_provider} not found.", 400)++ # Store relay context for the callback+ _cleanup_expired_codes()+ relay_key = secrets.token_urlsafe(24)+ _auth_codes[relay_key] = {+ "type": "relay",+ "pool_id": pool_id,+ "client_id": client_id,+ "redirect_uri": redirect_uri,+ "state": state,+ "scope": scope,+ "provider_name": identity_provider,+ "created_at": time.time(),+ }++ provider_type = provider.get("ProviderType", "")+ details = provider.get("ProviderDetails", {})++ if provider_type == "SAML":+ # Resolve IdP SSO URL: IDPSSOEndpoint > MetadataURL+ sso_url = details.get("IDPSSOEndpoint") or details.get("MetadataURL", "")+ if not sso_url:+ return error_response_json("InvalidParameterException",+ "SAML provider has no IDPSSOEndpoint or MetadataURL.", 400)+ saml_request = _build_saml_authn_request(pool_id, sso_url)+ redirect_url = sso_url + ("&" if "?" in sso_url else "?") + urlencode({+ "SAMLRequest": saml_request,+ "RelayState": relay_key,+ })+ elif provider_type == "OIDC":+ # OIDC authorize redirect+ oidc_issuer = details.get("oidc_issuer", "")+ authorize_url = details.get("authorize_url", f"{oidc_issuer}/authorize" if oidc_issuer else "")+ if not authorize_url:+ return error_response_json("InvalidParameterException",+ "OIDC provider has no oidc_issuer or authorize_url.", 400)+ oidc_client_id = details.get("client_id", "")+ 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(),+ "scope": details.get("authorize_scopes", scope),+ "state": relay_key,+ })+ else:+ return error_response_json("InvalidParameterException",+ f"Federated sign-in not supported for {provider_type}.", 400)++ logger.info("Cognito: OAuth2 authorize redirect to %s for provider %s", provider_type, identity_provider)+ return 302, {"Location": redirect_url, "Content-Type": "text/html"}, b""+++def _saml2_idp_response(body: bytes, query_params):+ """POST /saml2/idpresponse — receive SAML assertion, create user, redirect with auth code."""+ # Parse form-encoded body+ form = {}+ if body:+ try:+ parsed = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)+ form = {k: v[0] for k, v in parsed.items()}+ except Exception:+ pass++ saml_response_b64 = form.get("SAMLResponse", "")+ relay_state = form.get("RelayState", "")++ if not saml_response_b64:+ return error_response_json("InvalidParameterException", "SAMLResponse is required.", 400)++ # Look up relay context+ relay = _auth_codes.pop(relay_state, None)+ if not relay or relay.get("type") != "relay":+ return error_response_json("InvalidParameterException", "Invalid or expired RelayState.", 400)++ pool_id = relay["pool_id"]+ client_id = relay["client_id"]+ redirect_uri = relay["redirect_uri"]+ state = relay.get("state", "")+ provider_name = relay["provider_name"]++ pool = _user_pools.get(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:+ return error_response_json("ResourceNotFoundException",+ f"Identity provider {provider_name} not found.", 400)++ # Parse SAML assertion+ try:+ saml_data = _parse_saml_response(saml_response_b64)+ except Exception as e:+ logger.warning("Cognito: failed to parse SAML response: %s", e)+ return error_response_json("InvalidParameterException", f"Failed to parse SAML response: {e}", 400)++ name_id = saml_data.get("name_id")+ if not name_id:+ return error_response_json("InvalidParameterException", "SAML assertion missing NameID.", 400)++ # Apply attribute mapping: IdP claim name → Cognito attribute name+ attr_mapping = provider.get("AttributeMapping", {})+ reverse_mapping = {v: k for k, v in attr_mapping.items()} # IdP claim → Cognito attr+ user_attrs = {}+ for idp_claim, value in saml_data.get("attributes", {}).items():+ cognito_attr = reverse_mapping.get(idp_claim, idp_claim)+ user_attrs[cognito_attr] = value++ # Create or update federated user+ username = f"{provider_name}_{name_id}"+ existing_user = pool["_users"].get(username)+ now = _now_epoch()++ if existing_user:+ # Update attributes+ 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:+ user_attrs["email"] = name_id if "@" in name_id else ""+ 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"])++ # Generate authorization code+ _cleanup_expired_codes()+ code = secrets.token_urlsafe(32)+ _auth_codes[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(),+ }++ # Redirect to app callback+ params = {"code": code}+ if state:+ params["state"] = state+ location = redirect_uri + ("&" if "?" in redirect_uri else "?") + urlencode(params)+ logger.info("Cognito: SAML IdP response — user %s created/updated, redirecting to app", username)+ return 302, {"Location": location, "Content-Type": "text/html"}, b""++def _oauth2_token(data, query_params, raw_body: bytes = b""):- """Stub /oauth2/token endpoint — returns fake tokens for client_credentials flow.+ """/oauth2/token — supports authorization_code and client_credentials grants.Body is application/x-www-form-urlencoded, not JSON."""# Parse form-encoded body first, fall back to query_params@@ -1885,14 +2222,52 @@ def _oauth2_token(data, query_params, raw_body: bytes = b""):v = query_params.get(key, "")return v[0] if isinstance(v, list) else v+ grant_type = _get("grant_type")client_id = _get("client_id")- now = int(time.time())- pool_id = ""- for pid, pool in _user_pools.items():- if client_id in pool["_clients"]:- pool_id = pid- break- access_token = _fake_token(client_id or new_uuid(), pool_id, client_id or "", "access")++ # --- authorization_code grant ---+ if grant_type == "authorization_code":+ code = _get("code")+ redirect_uri = _get("redirect_uri")++ code_data = _auth_codes.pop(code, None)+ if not code_data or code_data.get("type") != "code":+ return error_response_json("InvalidGrantException", "Invalid or expired authorization code.", 400)++ # Validate client and redirect_uri+ if client_id and code_data["client_id"] != client_id:+ return error_response_json("InvalidGrantException", "client_id mismatch.", 400)+ if redirect_uri and code_data["redirect_uri"] != redirect_uri:+ return error_response_json("InvalidGrantException", "redirect_uri mismatch.", 400)++ pool_id = code_data["pool_id"]+ username = code_data["username"]+ sub = code_data["sub"]+ effective_client_id = code_data["client_id"]++ # Fetch user attributes for id_token claims (email, etc.)+ user_attrs = {}+ pool = _user_pools.get(pool_id)+ if pool:+ user = pool["_users"].get(username)+ if user:+ user_attrs = _attr_list_to_dict(user.get("Attributes", []))++ access_token = _fake_token(sub, pool_id, effective_client_id, "access", username)+ id_token = _fake_token(sub, pool_id, effective_client_id, "id", username, user_attrs=user_attrs)+ refresh_token = secrets.token_urlsafe(48)++ return json_response({+ "id_token": id_token,+ "access_token": access_token,+ "refresh_token": refresh_token,+ "token_type": "Bearer",+ "expires_in": 3600,+ })++ # --- client_credentials grant (existing behavior / default) ---+ pool_id, pool, _ = _find_pool_and_client(client_id)+ access_token = _fake_token(client_id or new_uuid(), pool_id or "", client_id or "", "access")return json_response({"access_token": access_token,"token_type": "Bearer",@@ -2160,3 +2535,4 @@ def reset():_pool_domain_map.clear()_identity_pools.clear()_identity_tags.clear()+ _auth_codes.clear()diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 68325efe..0e54eca5 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1,9 +1,12 @@+import base64import ioimport jsonimport osimport time+import urllib.request+import urllib.errorimport zipfile-from urllib.parse import urlparse+from urllib.parse import urlparse, parse_qs as _parse_qs, urlencode as _urlencodeimport pytestfrom botocore.exceptions import ClientErrorimport uuid as _uuid_mod@@ -1100,3 +1103,379 @@ def test_cognito_openid_configuration():assert pool_id in data["issuer"]assert "jwks_uri" in dataassert "token_endpoint" in data+++# ===========================================================================+# Identity Provider CRUD+# ===========================================================================++def test_cognito_create_and_describe_identity_provider(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpCrudPool")["UserPool"]["Id"]+ resp = cognito_idp.create_identity_provider(+ UserPoolId=pid,+ ProviderName="MySAML",+ ProviderType="SAML",+ ProviderDetails={"MetadataURL": "https://idp.example.com/metadata"},+ AttributeMapping={"email": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"},+ IdpIdentifiers=["my-saml"],+ )+ provider = resp["IdentityProvider"]+ assert provider["ProviderName"] == "MySAML"+ assert provider["ProviderType"] == "SAML"+ assert provider["ProviderDetails"]["MetadataURL"] == "https://idp.example.com/metadata"+ assert provider["IdpIdentifiers"] == ["my-saml"]+ assert "CreationDate" in provider+ assert "LastModifiedDate" in provider++ desc = cognito_idp.describe_identity_provider(UserPoolId=pid, ProviderName="MySAML")+ assert desc["IdentityProvider"]["ProviderName"] == "MySAML"+ assert desc["IdentityProvider"]["UserPoolId"] == pid+++def test_cognito_create_identity_provider_duplicate(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpDupPool")["UserPool"]["Id"]+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="Dup", ProviderType="OIDC",+ ProviderDetails={"client_id": "abc", "authorize_scopes": "openid"},+ )+ with pytest.raises(ClientError) as exc:+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="Dup", ProviderType="OIDC",+ ProviderDetails={"client_id": "abc", "authorize_scopes": "openid"},+ )+ assert "DuplicateProviderException" in str(exc.value)+++def test_cognito_update_identity_provider(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpUpdatePool")["UserPool"]["Id"]+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="UpdateMe", ProviderType="SAML",+ ProviderDetails={"MetadataURL": "https://old.example.com/metadata"},+ AttributeMapping={"email": "old-claim"},+ )+ resp = cognito_idp.update_identity_provider(+ UserPoolId=pid, ProviderName="UpdateMe",+ ProviderDetails={"MetadataURL": "https://new.example.com/metadata"},+ AttributeMapping={"email": "new-claim", "name": "name-claim"},+ IdpIdentifiers=["updated-id"],+ )+ updated = resp["IdentityProvider"]+ assert updated["ProviderDetails"]["MetadataURL"] == "https://new.example.com/metadata"+ assert updated["AttributeMapping"]["email"] == "new-claim"+ assert updated["AttributeMapping"]["name"] == "name-claim"+ assert updated["IdpIdentifiers"] == ["updated-id"]+++def test_cognito_delete_identity_provider(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpDeletePool")["UserPool"]["Id"]+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="DeleteMe", ProviderType="OIDC",+ ProviderDetails={"client_id": "x", "authorize_scopes": "openid"},+ )+ cognito_idp.delete_identity_provider(UserPoolId=pid, ProviderName="DeleteMe")++ with pytest.raises(ClientError) as exc:+ cognito_idp.describe_identity_provider(UserPoolId=pid, ProviderName="DeleteMe")+ assert "ResourceNotFoundException" in str(exc.value)+++def test_cognito_list_identity_providers(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpListPool")["UserPool"]["Id"]+ for i in range(3):+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName=f"Idp{i}", ProviderType="SAML",+ ProviderDetails={"MetadataURL": f"https://idp{i}.example.com/metadata"},+ )+ resp = cognito_idp.list_identity_providers(UserPoolId=pid, MaxResults=60)+ names = [p["ProviderName"] for p in resp["Providers"]]+ assert "Idp0" in names+ assert "Idp1" in names+ assert "Idp2" in names+ # Each entry should have the summary fields+ for p in resp["Providers"]:+ assert "ProviderType" in p+ assert "CreationDate" in p+ assert "LastModifiedDate" in p+++def test_cognito_list_identity_providers_pagination(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpPagePool")["UserPool"]["Id"]+ for i in range(5):+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName=f"Page{i}", ProviderType="SAML",+ ProviderDetails={"MetadataURL": f"https://page{i}.example.com/metadata"},+ )+ resp = cognito_idp.list_identity_providers(UserPoolId=pid, MaxResults=2)+ assert len(resp["Providers"]) == 2+ assert "NextToken" in resp+ resp2 = cognito_idp.list_identity_providers(UserPoolId=pid, MaxResults=2, NextToken=resp["NextToken"])+ assert len(resp2["Providers"]) == 2+ all_names = [p["ProviderName"] for p in resp["Providers"] + resp2["Providers"]]+ assert len(set(all_names)) == 4 # no duplicates across pages+++def test_cognito_get_identity_provider_by_identifier(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpByIdPool")["UserPool"]["Id"]+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="ByIdProvider", ProviderType="SAML",+ ProviderDetails={"MetadataURL": "https://byid.example.com/metadata"},+ IdpIdentifiers=["find-me"],+ )+ resp = cognito_idp.get_identity_provider_by_identifier(UserPoolId=pid, IdpIdentifier="find-me")+ assert resp["IdentityProvider"]["ProviderName"] == "ByIdProvider"++ with pytest.raises(ClientError) as exc:+ cognito_idp.get_identity_provider_by_identifier(UserPoolId=pid, IdpIdentifier="not-exist")+ assert "ResourceNotFoundException" in str(exc.value)+++def test_cognito_describe_nonexistent_identity_provider(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="IdpNotFoundPool")["UserPool"]["Id"]+ with pytest.raises(ClientError) as exc:+ cognito_idp.describe_identity_provider(UserPoolId=pid, ProviderName="Ghost")+ assert "ResourceNotFoundException" in str(exc.value)+++# ===========================================================================+# Federated SAML / OAuth2 flow+# ===========================================================================++ENDPOINT = "http://localhost:4566"+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Capture 302 redirects without following them."""+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)+++_no_redirect_opener = urllib.request.build_opener(_NoRedirectHandler)+++def _setup_saml_pool(cognito_idp):+ """Helper: create a pool + client + SAML provider for federated tests."""+ pid = cognito_idp.create_user_pool(PoolName="FedPool")["UserPool"]["Id"]+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pid,+ ClientName="FedApp",+ CallbackURLs=["http://localhost:3000/callback"],+ AllowedOAuthFlows=["code"],+ AllowedOAuthScopes=["openid", "email"],+ SupportedIdentityProviders=["TestSAML"],+ )["UserPoolClient"]+ cognito_idp.create_identity_provider(+ UserPoolId=pid,+ ProviderName="TestSAML",+ ProviderType="SAML",+ ProviderDetails={"IDPSSOEndpoint": "https://idp.example.com/saml/sso"},+ AttributeMapping={+ "email": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",+ "name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",+ },+ )+ return pid, client["ClientId"]+++def _build_mock_saml_response(name_id, attributes=None):+ """Build a minimal SAML Response XML for testing, return base64-encoded."""+ attrs_xml = ""+ if attributes:+ attr_statements = []+ for name, value in attributes.items():+ attr_statements.append(+ f'<saml:Attribute Name="{name}">'+ f'<saml:AttributeValue>{value}</saml:AttributeValue>'+ f'</saml:Attribute>'+ )+ attrs_xml = '<saml:AttributeStatement>' + ''.join(attr_statements) + '</saml:AttributeStatement>'++ xml = (+ '<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"'+ ' xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">'+ '<saml:Assertion>'+ '<saml:Subject>'+ f'<saml:NameID>{name_id}</saml:NameID>'+ '</saml:Subject>'+ f'{attrs_xml}'+ '</saml:Assertion>'+ '</samlp:Response>'+ )+ return base64.b64encode(xml.encode("utf-8")).decode()+++def test_cognito_oauth2_authorize_saml_redirect(cognito_idp):+ """GET /oauth2/authorize should 302 to the SAML IdP with SAMLRequest."""+ pid, cid = _setup_saml_pool(cognito_idp)+ url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=xyz123&scope=openid"+ )+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected redirect, got 200"+ except urllib.error.HTTPError as e:+ assert e.code == 302, f"Expected 302, got {e.code}"+ location = e.headers.get("Location", "")+ assert "idp.example.com" in location+ assert "SAMLRequest=" in location+ assert "RelayState=" in location+++def test_cognito_oauth2_authorize_invalid_client(cognito_idp):+ """GET /oauth2/authorize with unknown client_id returns 400."""+ url = f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id=nonexistent&redirect_uri=http://x&identity_provider=X"+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected error"+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = json.loads(e.read())+ assert "ResourceNotFoundException" in body.get("__type", "")+++def test_cognito_saml_full_flow(cognito_idp):+ """Full SAML flow: authorize → SAML response → token exchange → user created."""+ pid, cid = _setup_saml_pool(cognito_idp)++ # Step 1: GET /oauth2/authorize → extract RelayState from redirect Location+ 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", "")+ parsed_loc = urlparse(location)+ relay_state = _parse_qs(parsed_loc.query).get("RelayState", [""])[0]+ assert relay_state, "RelayState should be in redirect URL"++ # Step 2: POST /saml2/idpresponse with mock SAML assertion+ saml_resp = _build_mock_saml_response(+ name_id="[email protected]",+ attributes={+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "[email protected]",+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "John Doe",+ },+ )+ form_data = _urlencode({"SAMLResponse": saml_resp, "RelayState": relay_state}).encode()+ req2 = urllib.request.Request(+ f"{ENDPOINT}/saml2/idpresponse",+ data=form_data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ _no_redirect_opener.open(req2)+ assert False, "Expected redirect"+ except urllib.error.HTTPError as e2:+ callback_location = e2.headers.get("Location", "")+ assert "localhost:3000/callback" in callback_location+ assert "code=" in callback_location+ assert "state=mystate" in callback_location++ # Extract authorization code+ parsed_cb = urlparse(callback_location)+ auth_code = _parse_qs(parsed_cb.query).get("code", [""])[0]+ assert auth_code, "Authorization code should be in callback URL"++ # Step 3: POST /oauth2/token with authorization_code grant+ token_data = (+ f"grant_type=authorization_code&code={auth_code}"+ f"&client_id={cid}&redirect_uri=http://localhost:3000/callback"+ ).encode()+ req3 = urllib.request.Request(+ f"{ENDPOINT}/oauth2/token",+ data=token_data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ with urllib.request.urlopen(req3) as resp:+ tokens = json.loads(resp.read())+ assert "access_token" in tokens+ assert "id_token" in tokens+ assert "refresh_token" in tokens+ assert tokens["token_type"] == "Bearer"++ # Step 3b: Verify id_token contains email claim+ id_payload_b64 = tokens["id_token"].split(".")[1]+ id_payload_b64 += "=" * (4 - len(id_payload_b64) % 4)+ id_claims = json.loads(base64.urlsafe_b64decode(id_payload_b64))+ assert id_claims.get("email") == "[email protected]", f"Missing email in id_token: {id_claims}"+ assert id_claims.get("token_use") == "id"+ assert "cognito:username" in id_claims++ # Step 4: Verify user was created via AdminGetUser+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert user["Username"] == "[email protected]"+ assert user["UserStatus"] == "EXTERNAL_PROVIDER"+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs.get("email") == "[email protected]"+ assert attrs.get("name") == "John Doe"+++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"+ req = urllib.request.Request(+ f"{ENDPOINT}/oauth2/token",+ data=data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ try:+ urllib.request.urlopen(req)+ assert False, "Expected error"+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = json.loads(e.read())+ assert "InvalidGrantException" in body.get("__type", "")+++def test_cognito_federated_user_idempotent(cognito_idp):+ """Running SAML flow twice with same NameID updates user, doesn't duplicate."""+ pid, cid = _setup_saml_pool(cognito_idp)++ def _do_saml_flow(name_value):+ # Authorize+ url = (+ f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=s&scope=openid"+ )+ try:+ _no_redirect_opener.open(url)+ except urllib.error.HTTPError as e:+ location = e.headers.get("Location", "")+ relay = _parse_qs(urlparse(location).query).get("RelayState", [""])[0]++ # SAML response+ saml = _build_mock_saml_response(+ name_id="[email protected]",+ attributes={+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": name_value,+ },+ )+ form = _urlencode({"SAMLResponse": saml, "RelayState": relay}).encode()+ try:+ _no_redirect_opener.open(urllib.request.Request(+ f"{ENDPOINT}/saml2/idpresponse", data=form,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ ))+ except urllib.error.HTTPError:+ pass++ _do_saml_flow("First Name")+ _do_saml_flow("Updated Name")++ # Should be one user, not two+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs.get("name") == "Updated Name"++ # Count users with this username pattern+ all_users = cognito_idp.list_users(UserPoolId=pid)["Users"]+ repeat_users = [u for u in all_users if u["Username"] == "[email protected]"]+ assert len(repeat_users) == 1