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 choice-based sign-in UI for ALLOW_USER_AUTH (#1294)
kjdevb4ea6944f375
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex f8bd6f14..bcf45741 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -38,7 +38,12 @@ Identity Pools operations:TagResource, UntagResource, ListTagsForResource.Data-plane endpoints (path-based, form-encoded):- GET /oauth2/authorize — redirect to external SAML/OIDC IdP+ GET /oauth2/authorize — redirect to external SAML/OIDC IdP, or serve the Hosted UI+ sign-in form (single-page, or multi-step choice-based+ sign-in when the client's ExplicitAuthFlows includes+ ALLOW_USER_AUTH)+ POST /login — process Hosted UI sign-in submissions (single-page or+ choice-based) and redirect with an authorization codePOST /saml2/idpresponse — receive SAML assertion, create user, issue auth codePOST /oauth2/token — exchange authorization_code or client_credentials for tokens@@ -347,6 +352,13 @@ _pending_new_password = {} # token -> {pool_id, client_id, username, redirect_# code_challenge, code_challenge_method, expires_at}_NEW_PASSWORD_SESSION_TTL = 300 # 5 minutes+# Choice-based sign-in (Hosted UI, ALLOW_USER_AUTH) sessions. Plain dict for the+# same reason as `_pending_new_password` above — no SigV4 on /login.+_pending_user_auth = {} # token -> {pool_id, client_id, username, redirect_uri, scope,+ # state, response_type, nonce, code_challenge,+ # code_challenge_method, available_challenges, expires_at}+_USER_AUTH_SESSION_TTL = 300 # 5 minutes+# ---------------------------------------------------------------------------# In-memory state — CUSTOM_AUTH Challenge Sessions# ---------------------------------------------------------------------------@@ -2320,6 +2332,8 @@ _DEFAULT_VERIFICATION_MESSAGE = "Your verification code is {####}."_DEFAULT_VERIFICATION_LINK_MESSAGE = ("Please click the link below to verify your email address. {##Verify Email##}")+_DEFAULT_EMAIL_OTP_SUBJECT = "Your sign-in code"+_DEFAULT_EMAIL_OTP_MESSAGE = "Your sign-in code is {####}."def _cognito_email_enabled() -> bool:@@ -2471,6 +2485,18 @@ def _send_verification_email(pool, username, attr_dict, code, attribute_name="em)+def _send_email_otp(pool, username, email, code):+ """Send the EMAIL_OTP first-factor sign-in code. AWS has no template+ configuration API for this message, so it always uses the built-in text."""+ return _deliver_cognito_email(+ pool, email,+ _DEFAULT_EMAIL_OTP_SUBJECT,+ _expand_template(_DEFAULT_EMAIL_OTP_MESSAGE, username, code),+ type_name="CognitoEmailOtpMessage",+ extra={"Username": username},+ )++# ===========================================================================# USER MANAGEMENT# ===========================================================================@@ -4175,19 +4201,35 @@ def _oauth2_error(error: str, description: str, status: int = 400):return status, {"Content-Type": "application/json"}, body-def _login_page_html(client_id, redirect_uri, scope, state, response_type,- code_challenge="", code_challenge_method="", nonce="",- error_message=""):- esc = html_mod.escape- err_block = ""- if error_message:- err_block = f'<div class="error">{esc(error_message)}</div>'+def _use_choice_based_ui(client) -> bool:+ """True when the client's ExplicitAuthFlows opts into USER_AUTH (choice-based+ sign-in), which drives a multi-step Hosted UI instead of the single-page form."""+ return "ALLOW_USER_AUTH" in client.get("ExplicitAuthFlows", [])+++_SUPPORTED_FIRST_AUTH_FACTORS = ("PASSWORD", "EMAIL_OTP")+++def _available_first_auth_factors(pool):+ """Resolve the first-factor choices for choice-based sign-in from+ Policies.SignInPolicy.AllowedFirstAuthFactors (default ["PASSWORD"])."""+ factors = ((pool.get("Policies") or {}).get("SignInPolicy") or {}).get(+ "AllowedFirstAuthFactors") or ["PASSWORD"]+ factors = [f for f in factors if f in _SUPPORTED_FIRST_AUTH_FACTORS]+ # AWS forbids OTP factors when MFA is required, restricting the choice to passwords.+ if pool.get("MfaConfiguration") == "ON":+ factors = [f for f in factors if f == "PASSWORD"]+ return factors or ["PASSWORD"]+++def _page_shell(title, heading, body_html):+ """Shared page chrome (CSS + card layout) for all Hosted UI login pages."""return f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">-<title>Sign in</title>+<title>{title}</title><style>*{{margin:0;padding:0;box-sizing:border-box}}body{{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;@@ -4200,7 +4242,7 @@ input[type=text],input[type=password]{{width:100%;padding:10px 12px;border:1px sborder-radius:4px;font-size:14px;margin-bottom:16px;outline:none;transition:border-color .15s}}input[type=text]:focus,input[type=password]:focus{{border-color:#0073bb;box-shadow:0 0 0 2px rgba(0,115,187,.2)}}button{{width:100%;padding:10px;background:#0073bb;color:#fff;border:none;border-radius:4px;- font-size:16px;font-weight:500;cursor:pointer;transition:background .15s}}+ font-size:16px;font-weight:500;cursor:pointer;transition:background .15s;margin-bottom:12px}}button:hover{{background:#005a94}}.error{{background:#fce8e6;color:#d13212;border:1px solid #d13212;border-radius:4px;padding:10px;margin-bottom:16px;font-size:13px;text-align:center}}@@ -4209,8 +4251,22 @@ button:hover{{background:#005a94}}</head><body><div class="card">-<h1>Sign in</h1>-{err_block}+<h1>{heading}</h1>+{body_html}+<div class="footer">Powered by ministack</div>+</div>+</body>+</html>"""+++def _login_page_html(client_id, redirect_uri, scope, state, response_type,+ code_challenge="", code_challenge_method="", nonce="",+ error_message=""):+ esc = html_mod.escape+ err_block = ""+ if error_message:+ err_block = f'<div class="error">{esc(error_message)}</div>'+ body = f"""{err_block}<form method="POST" action="/login"><input type="hidden" name="client_id" value="{esc(client_id)}"><input type="hidden" name="redirect_uri" value="{esc(redirect_uri)}">@@ -4225,11 +4281,8 @@ button:hover{{background:#005a94}}<label for="password">Password</label><input type="password" id="password" name="password" autocomplete="current-password" required><button type="submit">Sign in</button>-</form>-<div class="footer">Powered by ministack</div>-</div>-</body>-</html>"""+</form>"""+ return _page_shell("Sign in", "Sign in", body)def _new_password_page_html(np_token, error_message=""):@@ -4237,35 +4290,7 @@ def _new_password_page_html(np_token, error_message=""):err_block = ""if error_message:err_block = f'<div class="error">{esc(error_message)}</div>'- return f"""<!DOCTYPE html>-<html lang="en">-<head>-<meta charset="UTF-8">-<meta name="viewport" content="width=device-width, initial-scale=1.0">-<title>Change password</title>-<style>-*{{margin:0;padding:0;box-sizing:border-box}}-body{{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;- background:#f0f2f5;display:flex;justify-content:center;align-items:center;min-height:100vh}}-.card{{background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.1);- padding:40px;width:400px;max-width:90vw}}-h1{{font-size:24px;font-weight:600;color:#232f3e;margin-bottom:24px;text-align:center}}-label{{display:block;font-size:14px;font-weight:500;color:#545b64;margin-bottom:4px}}-input[type=password]{{width:100%;padding:10px 12px;border:1px solid #aab7b8;- border-radius:4px;font-size:14px;margin-bottom:16px;outline:none;transition:border-color .15s}}-input[type=password]:focus{{border-color:#0073bb;box-shadow:0 0 0 2px rgba(0,115,187,.2)}}-button{{width:100%;padding:10px;background:#0073bb;color:#fff;border:none;border-radius:4px;- font-size:16px;font-weight:500;cursor:pointer;transition:background .15s}}-button:hover{{background:#005a94}}-.error{{background:#fce8e6;color:#d13212;border:1px solid #d13212;border-radius:4px;- padding:10px;margin-bottom:16px;font-size:13px;text-align:center}}-.footer{{text-align:center;margin-top:20px;font-size:12px;color:#879596}}-</style>-</head>-<body>-<div class="card">-<h1>Set a new password</h1>-{err_block}+ body = f"""{err_block}<form method="POST" action="/login"><input type="hidden" name="np_token" value="{esc(np_token)}"><label for="new_password">New password</label>@@ -4273,11 +4298,92 @@ button:hover{{background:#005a94}}<label for="confirm_password">Confirm new password</label><input type="password" id="confirm_password" name="confirm_password" autocomplete="new-password" required><button type="submit">Update password</button>-</form>-<div class="footer">Powered by ministack</div>-</div>-</body>-</html>"""+</form>"""+ return _page_shell("Change password", "Set a new password", body)+++def _username_page_html(client_id, redirect_uri, scope, state, response_type,+ code_challenge="", code_challenge_method="", nonce="",+ error_message=""):+ """Step 1 of choice-based sign-in (ALLOW_USER_AUTH): username only."""+ esc = html_mod.escape+ err_block = ""+ if error_message:+ err_block = f'<div class="error">{esc(error_message)}</div>'+ body = f"""{err_block}+<form method="POST" action="/login">+<input type="hidden" name="auth_flow" value="USER_AUTH">+<input type="hidden" name="client_id" value="{esc(client_id)}">+<input type="hidden" name="redirect_uri" value="{esc(redirect_uri)}">+<input type="hidden" name="scope" value="{esc(scope)}">+<input type="hidden" name="state" value="{esc(state)}">+<input type="hidden" name="response_type" value="{esc(response_type)}">+<input type="hidden" name="code_challenge" value="{esc(code_challenge)}">+<input type="hidden" name="code_challenge_method" value="{esc(code_challenge_method)}">+<input type="hidden" name="nonce" value="{esc(nonce)}">+<label for="username">Username</label>+<input type="text" id="username" name="username" autocomplete="username" required autofocus>+<button type="submit">Next</button>+</form>"""+ return _page_shell("Sign in", "Sign in", body)+++_CHALLENGE_LABELS = {+ "PASSWORD": "Password",+ "EMAIL_OTP": "Email code",+}+++def _select_challenge_page_html(ua_token, available_challenges, error_message=""):+ """Step 2 of choice-based sign-in: pick an authentication method."""+ esc = html_mod.escape+ err_block = ""+ if error_message:+ err_block = f'<div class="error">{esc(error_message)}</div>'+ buttons = "\n".join(+ f'<button type="submit" name="challenge" value="{esc(c)}">'+ f'{esc(_CHALLENGE_LABELS.get(c, c))}</button>'+ for c in available_challenges+ )+ body = f"""{err_block}+<form method="POST" action="/login">+<input type="hidden" name="ua_token" value="{esc(ua_token)}">+{buttons}+</form>"""+ return _page_shell("Sign in", "Choose how to sign in", body)+++def _password_page_html(ua_token, username, error_message=""):+ """Step 3 of choice-based sign-in: password entry."""+ esc = html_mod.escape+ err_block = ""+ if error_message:+ err_block = f'<div class="error">{esc(error_message)}</div>'+ body = f"""{err_block}+<form method="POST" action="/login">+<input type="hidden" name="ua_token" value="{esc(ua_token)}">+<label for="password">Password for {esc(username)}</label>+<input type="password" id="password" name="password" autocomplete="current-password" required autofocus>+<button type="submit">Sign in</button>+</form>"""+ return _page_shell("Sign in", "Sign in", body)+++def _email_otp_page_html(ua_token, error_message=""):+ """Step 3 of choice-based sign-in: EMAIL_OTP code entry. The destination+ email address is intentionally not shown, to avoid user enumeration."""+ esc = html_mod.escape+ err_block = ""+ if error_message:+ err_block = f'<div class="error">{esc(error_message)}</div>'+ body = f"""{err_block}+<form method="POST" action="/login">+<input type="hidden" name="ua_token" value="{esc(ua_token)}">+<label for="code">Enter the code we emailed you</label>+<input type="text" id="code" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus>+<button type="submit">Sign in</button>+</form>"""+ return _page_shell("Sign in", "Enter verification code", body)# -- /oauth2/authorize (GET) ------------------------------------------------@@ -4403,10 +4509,16 @@ def handle_oauth2_authorize(method, path, headers, query_params):if callback_urls and redirect_uri not in callback_urls:return _oauth2_error("invalid_request", f"redirect_uri is not allowed: {redirect_uri}")- html_body = _login_page_html(- client_id, redirect_uri, scope, state, response_type,- code_challenge, code_challenge_method, nonce,- )+ if _use_choice_based_ui(client):+ html_body = _username_page_html(+ client_id, redirect_uri, scope, state, response_type,+ code_challenge, code_challenge_method, nonce,+ )+ else:+ html_body = _login_page_html(+ client_id, redirect_uri, scope, state, response_type,+ code_challenge, code_challenge_method, nonce,+ )return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")@@ -4801,6 +4913,73 @@ def _issue_auth_code_redirect(client_id, pool_id, redirect_uri, scope, username,return 302, {"Location": location, "Cache-Control": "no-store"}, b""+def _hosted_ui_user_status_error(user) -> str:+ """Disabled/unconfirmed checks shared by every Hosted UI first-factor path+ (PASSWORD and EMAIL_OTP alike), applied once a user has been resolved."""+ if not user.get("Enabled", True):+ return "User is disabled."+ if user.get("UserStatus") not in ("CONFIRMED", "FORCE_CHANGE_PASSWORD"):+ return "User is not confirmed."+ return ""+++def _authenticate_hosted_ui_user(pool, username, password):+ """Validate username/password for the Hosted UI login paths.++ Returns (user, error_msg); error_msg is empty on success. "No such user"+ and "wrong password" intentionally share the same error text so the+ Hosted UI never reveals whether a username exists by that path alone;+ the disabled/unconfirmed messages below do distinguish an existing+ account from a nonexistent one, matching the pre-existing single-page+ login behavior this helper was extracted from.+ """+ user, _err = _resolve_user(pool, username)+ if _err:+ return None, "Incorrect username or password."+ status_error = _hosted_ui_user_status_error(user)+ if status_error:+ return None, status_error+ if user.get("_password") != password:+ return None, "Incorrect username or password."+ return user, ""+++def _extract_oauth_form_params(form: dict) -> dict:+ """Pull the OAuth2 authorize-request fields that the Hosted UI carries as hidden+ form fields across its login/username/challenge steps, with their defaults."""+ return {+ "client_id": form.get("client_id", ""),+ "redirect_uri": form.get("redirect_uri", ""),+ "scope": form.get("scope", ""),+ "state": form.get("state", ""),+ "response_type": form.get("response_type", "code"),+ "code_challenge": form.get("code_challenge", ""),+ "code_challenge_method": form.get("code_challenge_method", ""),+ "nonce": form.get("nonce", ""),+ }+++def _start_new_password_session(pool_id, client_id, username, redirect_uri, scope, state,+ response_type, nonce, code_challenge, code_challenge_method) -> str:+ """Create a `_pending_new_password` session for a FORCE_CHANGE_PASSWORD user reached+ via either Hosted UI login path (single-page or choice-based), returning its token."""+ np_token = secrets.token_urlsafe(24)+ _pending_new_password[np_token] = {+ "pool_id": pool_id,+ "client_id": client_id,+ "username": username,+ "redirect_uri": redirect_uri,+ "scope": scope,+ "state": state,+ "response_type": response_type,+ "nonce": nonce,+ "code_challenge": code_challenge,+ "code_challenge_method": code_challenge_method,+ "expires_at": time.time() + _NEW_PASSWORD_SESSION_TTL,+ }+ return np_token++def handle_login_submit(method, path, headers, body, query_params):"""POST /login — process the login form and redirect with auth code."""form: dict = {}@@ -4815,33 +4994,30 @@ def handle_login_submit(method, path, headers, body, query_params):if np_token:return _handle_new_password_submit(np_token, form)+ ua_token = form.get("ua_token", "")+ if ua_token:+ return _handle_user_auth_submit(ua_token, form)++ if form.get("auth_flow") == "USER_AUTH":+ return _handle_user_auth_start(form)+username = form.get("username", "")password = form.get("password", "")- client_id = form.get("client_id", "")- redirect_uri = form.get("redirect_uri", "")- scope = form.get("scope", "")- state = form.get("state", "")- response_type = form.get("response_type", "code")- code_challenge = form.get("code_challenge", "")- code_challenge_method = form.get("code_challenge_method", "")- nonce = form.get("nonce", "")+ oauth = _extract_oauth_form_params(form)+ client_id = oauth["client_id"]+ redirect_uri = oauth["redirect_uri"]+ scope = oauth["scope"]+ state = oauth["state"]+ response_type = oauth["response_type"]+ code_challenge = oauth["code_challenge"]+ code_challenge_method = oauth["code_challenge_method"]+ nonce = oauth["nonce"]pool_id, pool, client = _find_pool_by_client_id(client_id)if not pool:return _oauth2_error("invalid_client", f"Client {client_id} not found.")- # Authenticate user- error_msg = ""- user, _err = _resolve_user(pool, username)- if _err:- user = None- error_msg = "Incorrect username or password."- elif not user.get("Enabled", True):- error_msg = "User is disabled."- elif user.get("UserStatus") not in ("CONFIRMED", "FORCE_CHANGE_PASSWORD"):- error_msg = "User is not confirmed."- elif user.get("_password") != password:- error_msg = "Incorrect username or password."+ user, error_msg = _authenticate_hosted_ui_user(pool, username, password)if error_msg:html_body = _login_page_html(@@ -4852,20 +5028,10 @@ def handle_login_submit(method, path, headers, body, query_params):return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":- np_token = secrets.token_urlsafe(24)- _pending_new_password[np_token] = {- "pool_id": pool_id,- "client_id": client_id,- "username": user["Username"],- "redirect_uri": redirect_uri,- "scope": scope,- "state": state,- "response_type": response_type,- "nonce": nonce,- "code_challenge": code_challenge,- "code_challenge_method": code_challenge_method,- "expires_at": time.time() + _NEW_PASSWORD_SESSION_TTL,- }+ np_token = _start_new_password_session(+ pool_id, client_id, user["Username"], redirect_uri, scope, state,+ response_type, nonce, code_challenge, code_challenge_method,+ )html_body = _new_password_page_html(np_token)return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")@@ -4875,6 +5041,127 @@ def handle_login_submit(method, path, headers, body, query_params):)+_EMAIL_OTP_CODE = "123456"+++def _begin_user_auth_challenge(pool, ua_token, session, challenge):+ """Confirm the chosen first factor for a pending choice-based sign-in+ session and render its page. For EMAIL_OTP, this is also when the code+ is generated and mailed; a missing user or email intentionally leaves+ `otp_code` unset instead of erroring, so the page renders identically+ either way and verification simply fails later (avoids user enumeration).+ """+ session["challenge"] = challenge+ if challenge == "EMAIL_OTP":+ user, _err = _resolve_user(pool, session["username"])+ email = _attr_list_to_dict(user.get("Attributes", [])).get("email") if user else ""+ if user and email:+ session["otp_code"] = _EMAIL_OTP_CODE+ _send_email_otp(pool, session["username"], email, _EMAIL_OTP_CODE)+ return _email_otp_page_html(ua_token)+ return _password_page_html(ua_token, session["username"])+++def _handle_user_auth_start(form):+ """POST /login with `auth_flow=USER_AUTH` — step 1 of choice-based sign-in.++ Only collects the username. Real Cognito's USER_AUTH flow returns+ AvailableChallenges regardless of whether the username exists (to avoid+ user enumeration), so no user lookup happens here.+ """+ username = form.get("username", "")+ oauth = _extract_oauth_form_params(form)+ client_id = oauth["client_id"]++ pool_id, pool, client = _find_pool_by_client_id(client_id)+ if not pool:+ return _oauth2_error("invalid_client", f"Client {client_id} not found.")+ if not _use_choice_based_ui(client):+ return _oauth2_error("invalid_request", "USER_AUTH flow not allowed for this client.")++ available_challenges = _available_first_auth_factors(pool)+ ua_token = secrets.token_urlsafe(24)+ session = {+ "pool_id": pool_id,+ "username": username,+ "available_challenges": available_challenges,+ "challenge": "",+ "expires_at": time.time() + _USER_AUTH_SESSION_TTL,+ **oauth,+ }+ _pending_user_auth[ua_token] = session++ if len(available_challenges) == 1:+ html_body = _begin_user_auth_challenge(pool, ua_token, session, available_challenges[0])+ else:+ html_body = _select_challenge_page_html(ua_token, available_challenges)+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")+++def _handle_user_auth_submit(ua_token, form):+ """POST /login with `ua_token` — steps 2/3 of choice-based sign-in: challenge+ selection and challenge verification (PASSWORD or EMAIL_OTP)."""+ session = _pending_user_auth.get(ua_token)+ if not session or session["expires_at"] < time.time():+ _pending_user_auth.pop(ua_token, None)+ return _oauth2_error("invalid_request", "Session has expired. Please sign in again.")++ pool = _get_pool_unscoped(session["pool_id"])+ if not pool:+ _pending_user_auth.pop(ua_token, None)+ return error_response_json("ResourceNotFoundException",+ f"User pool {session['pool_id']} not found.", 400)++ challenge = session["challenge"]++ if not challenge:+ chosen = form.get("challenge", "")+ if chosen not in session["available_challenges"]:+ html_body = _select_challenge_page_html(+ ua_token, session["available_challenges"],+ error_message="Invalid authentication method.",+ )+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")+ html_body = _begin_user_auth_challenge(pool, ua_token, session, chosen)+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")++ if challenge == "PASSWORD":+ password = form.get("password", "")+ user, error_msg = _authenticate_hosted_ui_user(pool, session["username"], password)+ if error_msg:+ html_body = _password_page_html(ua_token, session["username"], error_message=error_msg)+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")+ else: # EMAIL_OTP+ code = form.get("code", "")+ otp_code = session.get("otp_code")+ if not otp_code or code != otp_code:+ html_body = _email_otp_page_html(ua_token, error_message="Incorrect code.")+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")+ user, _err = _resolve_user(pool, session["username"])+ status_error = _hosted_ui_user_status_error(user) if user else "Incorrect code."+ if status_error:+ html_body = _email_otp_page_html(ua_token, error_message=status_error)+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")++ if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":+ np_token = _start_new_password_session(+ session["pool_id"], session["client_id"], user["Username"],+ session["redirect_uri"], session["scope"], session["state"],+ session["response_type"], session["nonce"],+ session["code_challenge"], session["code_challenge_method"],+ )+ _pending_user_auth.pop(ua_token, None)+ html_body = _new_password_page_html(np_token)+ return 200, {"Content-Type": "text/html; charset=utf-8"}, html_body.encode("utf-8")++ _pending_user_auth.pop(ua_token, None)+ return _issue_auth_code_redirect(+ session["client_id"], session["pool_id"], session["redirect_uri"], session["scope"],+ user["Username"], session["nonce"], session["code_challenge"],+ session["code_challenge_method"], session["state"],+ )++def _handle_new_password_submit(np_token, form):"""POST /login with `np_token` — finalize a FORCE_CHANGE_PASSWORD flow started by theHosted UI login form."""@@ -5504,3 +5791,4 @@ def reset():_refresh_tokens.clear()_challenge_sessions.clear()_pending_new_password.clear()+ _pending_user_auth.clear()diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 987ae679..80ce3c42 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -2456,12 +2456,34 @@ def _setup_pool_with_user(generate_secret=True,force_change_password=False,lambda_config=None,+ explicit_auth_flows=None,+ mfa_configuration=None,+ allowed_first_auth_factors=None,+ user_email='[email protected]',):"""Create a user pool with a confirmed (or FORCE_CHANGE_PASSWORD) user and anOAuth-enabled client."""+ policies = None+ if allowed_first_auth_factors is not None:+ # Passing Policies replaces it wholesale, so keep the default+ # PasswordPolicy alongside the SignInPolicy override.+ policies = {+ "PasswordPolicy": {+ "MinimumLength": 8,+ "RequireUppercase": True,+ "RequireLowercase": True,+ "RequireNumbers": True,+ "RequireSymbols": True,+ "TemporaryPasswordValidityDays": 7,+ },+ "SignInPolicy": {"AllowedFirstAuthFactors": allowed_first_auth_factors},+ }+pool = cognito_idp.create_user_pool(PoolName='OAuth2TestPool',**({"LambdaConfig": lambda_config} if lambda_config else {}),+ **({"MfaConfiguration": mfa_configuration} if mfa_configuration else {}),+ **({"Policies": policies} if policies else {}),)pool_id = pool['UserPool']['Id']@@ -2475,7 +2497,7 @@ def _setup_pool_with_user('CallbackURLs': ['http://localhost:3000/callback'],'LogoutURLs': ['http://localhost:3000/logout'],'DefaultRedirectURI': 'http://localhost:3000/callback',- 'ExplicitAuthFlows': ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ 'ExplicitAuthFlows': explicit_auth_flows or ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],}client_resp = cognito_idp.create_user_pool_client(**client_kwargs)client = client_resp['UserPoolClient']@@ -2485,7 +2507,7 @@ def _setup_pool_with_user(Username='testuser',TemporaryPassword='TempPass1!',UserAttributes=[- {'Name': 'email', 'Value': '[email protected]'},+ {'Name': 'email', 'Value': user_email},{'Name': 'email_verified', 'Value': 'true'},{'Name': 'name', 'Value': 'Test User'},],@@ -2511,6 +2533,14 @@ def _extract_np_token(html):return html[start:end]+def _extract_ua_token(html):+ """Pull the `ua_token` hidden-field value out of a choice-based sign-in form HTML."""+ marker = 'name="ua_token" value="'+ start = html.index(marker) + len(marker)+ end = html.index('"', start)+ return html[start:end]++def _get(url, follow_redirects=True):"""GET request, optionally not following redirects."""req = urllib.request.Request(url, method='GET')@@ -2818,6 +2848,482 @@ def test_oauth2_new_password_submit_invalid_token():assert resp['error'] == 'invalid_request'+# ---------------------------------------------------------------------------+# Tests — /login (choice-based sign-in, ALLOW_USER_AUTH)+# ---------------------------------------------------------------------------++def _authorize_url(client_id):+ return (f'{ENDPOINT}/oauth2/authorize?response_type=code'+ f'&client_id={client_id}'+ f'&redirect_uri=http://localhost:3000/callback'+ f'&scope=openid+email'+ f'&state=abc123')+++def test_oauth2_authorize_without_allow_user_auth_shows_single_page_form():+ """Regression: clients that do NOT opt into ALLOW_USER_AUTH keep the+ existing single-page username+password form."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ status, headers, body = _get(_authorize_url(client_id))+ html = body.decode('utf-8')++ assert status == 200+ assert 'name="username"' in html+ assert 'name="password"' in html+ assert 'auth_flow' not in html+++def test_oauth2_authorize_with_allow_user_auth_shows_username_only_form():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ )+ client_id = client['ClientId']++ status, headers, body = _get(_authorize_url(client_id))+ html = body.decode('utf-8')++ assert status == 200+ assert 'name="username"' in html+ assert 'name="password"' not in html+ assert 'value="USER_AUTH"' in html+++def test_user_auth_two_step_flow_with_mfa_off_redirects_with_code():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ mfa_configuration='OFF',+ )+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')++ # Step 1: username only.+ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'mystate',+ 'response_type': 'code',+ })+ assert status == 200+ html = body.decode('utf-8')+ # MfaConfiguration=OFF skips the challenge-selection step.+ assert 'name="challenge"' not in html+ assert 'name="password"' in html+ ua_token = _extract_ua_token(html)++ # Step 2: password.+ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {'ua_token': ua_token, 'password': 'TestPass1!'},+ follow_redirects=False,+ )+ assert status == 302+ location = headers.get('location', '')+ assert location.startswith('http://localhost:3000/callback')+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)+ assert 'code' in qs+ assert qs['state'] == ['mystate']++ status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': qs['code'][0],+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status == 200+ resp = json.loads(body)+ assert 'access_token' in resp+++def test_user_auth_three_step_flow_with_multiple_factors_shows_challenge_selection():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'mystate',+ 'response_type': 'code',+ })+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="challenge"' in html+ assert 'value="PASSWORD"' in html+ ua_token = _extract_ua_token(html)++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'challenge': 'PASSWORD'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="password"' in html+++def test_user_auth_unknown_username_does_not_reveal_at_step_one():+ """Step 1 must succeed regardless of whether the username exists, to avoid+ user enumeration (matches real Cognito USER_AUTH behavior)."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ mfa_configuration='OFF',+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'no-such-user',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ assert status == 200+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'password': 'whatever'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'Incorrect username or password' in html+++def test_user_auth_wrong_password_shows_error_and_allows_retry():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ mfa_configuration='OFF',+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'password': 'WrongPass!'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'Incorrect username or password' in html+ retry_ua_token = _extract_ua_token(html)+ assert retry_ua_token == ua_token++ # Same ua_token can be retried with the correct password.+ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {'ua_token': ua_token, 'password': 'TestPass1!'},+ follow_redirects=False,+ )+ assert status == 302+ assert 'code' in urllib.parse.parse_qs(+ urllib.parse.urlparse(headers.get('location', '')).query)+++def test_user_auth_invalid_challenge_is_rejected():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'challenge': 'WEB_AUTHN'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'Invalid authentication method' in html+ assert 'name="password"' not in html+++def test_user_auth_expired_session_returns_error():+ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': 'nonexistent-token', 'password': 'x'},+ )+ resp = json.loads(body)++ assert status == 400+ assert resp['error'] == 'invalid_request'+++def test_user_auth_force_change_password_reaches_new_password_form():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ force_change_password=True,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ mfa_configuration='OFF',+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'password': 'TempPass1!'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="new_password"' in html+ assert 'name="confirm_password"' in html+ assert 'np_token' in html+++def test_user_auth_single_email_otp_factor_skips_challenge_selection():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="challenge"' not in html+ assert 'name="code"' in html+ assert 'name="password"' not in html+++def test_user_auth_multiple_factors_shows_both_challenge_options():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ assert status == 200+ html = body.decode('utf-8')+ assert 'value="PASSWORD"' in html+ assert 'value="EMAIL_OTP"' in html+++def test_user_auth_email_otp_flow_sends_email_and_signs_in():+ cognito_idp = make_client('cognito-idp')+ email = f'otp-{_uuid_mod.uuid4().hex[:8]}@example.com'+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ user_email=email,+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'mystate',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'challenge': 'EMAIL_OTP'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="code"' in html+ ua_token = _extract_ua_token(html)++ msgs = _messages_to(email, 'CognitoEmailOtpMessage')+ assert len(msgs) == 1, f'expected 1 OTP email, got {len(msgs)}'++ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {'ua_token': ua_token, 'code': '123456'},+ follow_redirects=False,+ )+ assert status == 302+ location = headers.get('location', '')+ assert location.startswith('http://localhost:3000/callback')+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)+ assert 'code' in qs+ assert qs['state'] == ['mystate']+++def test_user_auth_email_otp_wrong_code_shows_error_and_allows_retry():+ cognito_idp = make_client('cognito-idp')+ email = f'otp-{_uuid_mod.uuid4().hex[:8]}@example.com'+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ user_email=email,+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'challenge': 'EMAIL_OTP'},+ )+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'code': '000000'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'Incorrect code' in html+ retry_ua_token = _extract_ua_token(html)+ assert retry_ua_token == ua_token++ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {'ua_token': ua_token, 'code': '123456'},+ follow_redirects=False,+ )+ assert status == 302+ assert 'code' in urllib.parse.parse_qs(+ urllib.parse.urlparse(headers.get('location', '')).query)+++def test_user_auth_email_otp_unknown_username_shows_same_page_but_never_succeeds():+ """EMAIL_OTP must not reveal whether the username exists: the code-entry+ page renders identically, but no code can ever succeed for it."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'no-such-user',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ ua_token = _extract_ua_token(body.decode('utf-8'))++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'challenge': 'EMAIL_OTP'},+ )+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="code"' in html+ ua_token = _extract_ua_token(html)++ status, headers, body = _post_form(+ f'{ENDPOINT}/login', {'ua_token': ua_token, 'code': '123456'},+ )+ assert status == 200+ assert 'Incorrect code' in body.decode('utf-8')+++def test_user_auth_mfa_on_excludes_email_otp_from_choices():+ """MfaConfiguration is the second-factor setting and is independent of+ AllowedFirstAuthFactors, except that AWS forbids OTP first factors when+ MFA is required — so EMAIL_OTP drops out and only PASSWORD remains."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(+ cognito_idp,+ explicit_auth_flows=['ALLOW_USER_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ mfa_configuration='ON',+ allowed_first_auth_factors=['PASSWORD', 'EMAIL_OTP'],+ )+ client_id = client['ClientId']++ status, headers, body = _post_form(f'{ENDPOINT}/login', {+ 'auth_flow': 'USER_AUTH',+ 'username': 'testuser',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ })+ assert status == 200+ html = body.decode('utf-8')+ assert 'name="challenge"' not in html+ assert 'name="password"' in html++# ---------------------------------------------------------------------------# Tests — /oauth2/token# ---------------------------------------------------------------------------