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
fix(cognito): honor AliasAttributes and UsernameAttributes on user lookup (#647)
Robbie Mackay92c7eb8d37c8
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 85181db9..6c9afc1e 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -616,20 +616,44 @@ def _resolve_pool(pool_id: str):def _resolve_user(pool: dict, username: str):+ if username is None:+ return None, error_response_json(+ "UserNotFoundException", "User does not exist.", 400,+ )+user = pool["_users"].get(username)- if not user:- # Real AWS also accepts the user's 'sub' UUID as Username.+ if user:+ return user, None++ # Real AWS also accepts the user's 'sub' UUID as Username.+ for u in pool["_users"].values():+ attrs = _attr_list_to_dict(u.get("Attributes", []))+ if attrs.get("sub") == username:+ return u, None++ # AliasAttributes (email, phone_number, preferred_username) and+ # UsernameAttributes (email, phone_number) let users sign in / be looked+ # up via those attribute values. Real Cognito requires email/phone aliases+ # to be verified (email_verified/phone_number_verified == "true") before+ # the alias resolves; preferred_username has no verification requirement.+ alias_attrs = set(pool.get("AliasAttributes") or []) | set(+ pool.get("UsernameAttributes") or []+ )+ if alias_attrs:for u in pool["_users"].values():attrs = _attr_list_to_dict(u.get("Attributes", []))- if attrs.get("sub") == username:- user = u- break- if not user:- return None, error_response_json(- "UserNotFoundException",- f"User {username} does not exist.", 400,- )- return user, None+ for alias in alias_attrs:+ if attrs.get(alias) != username:+ continue+ if alias in ("email", "phone_number"):+ if str(attrs.get(f"{alias}_verified", "")).lower() != "true":+ continue+ return u, None++ return None, error_response_json(+ "UserNotFoundException",+ f"User {username} does not exist.", 400,+ )def _user_out(user: dict) -> dict:@@ -1766,9 +1790,9 @@ def _admin_initiate_auth(data):if auth_flow in ("ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"):username = auth_params.get("USERNAME")password = auth_params.get("PASSWORD")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errif not user.get("Enabled", True):return error_response_json("NotAuthorizedException", "User is disabled.", 400)if user.get("_password") and user["_password"] != password:@@ -1821,9 +1845,9 @@ def _admin_respond_to_auth_challenge(data):if challenge_name == "NEW_PASSWORD_REQUIRED":username = responses.get("USERNAME")new_password = responses.get("NEW_PASSWORD")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errif new_password:user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"@@ -1832,25 +1856,25 @@ def _admin_respond_to_auth_challenge(data):if challenge_name == "SMS_MFA":username = responses.get("USERNAME")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errreturn json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})if challenge_name == "SOFTWARE_TOKEN_MFA":username = responses.get("USERNAME")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _err# Accept any TOTP code in emulator — no real TOTP validationreturn json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})if challenge_name == "MFA_SETUP":# Triggered when pool MFA=ON but user hasn't enrolled yetusername = responses.get("USERNAME")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errreturn json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)@@ -1876,9 +1900,9 @@ def _initiate_auth(data):if auth_flow in ("USER_PASSWORD_AUTH",):username = auth_params.get("USERNAME")password = auth_params.get("PASSWORD")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errif not user.get("Enabled", True):return error_response_json("NotAuthorizedException", "User is disabled.", 400)if user.get("_password") and user["_password"] != password:@@ -1949,9 +1973,9 @@ def _respond_to_auth_challenge(data):if challenge_name in ("NEW_PASSWORD_REQUIRED", "PASSWORD_VERIFIER"):username = responses.get("USERNAME")new_password = responses.get("NEW_PASSWORD") or responses.get("PASSWORD")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errif new_password:user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"@@ -1960,9 +1984,9 @@ def _respond_to_auth_challenge(data):if challenge_name in ("SOFTWARE_TOKEN_MFA", "MFA_SETUP"):username = responses.get("USERNAME")- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _err# Accept any TOTP code in emulatorreturn json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})@@ -2058,9 +2082,9 @@ def _confirm_sign_up(data):if not pool:return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, err = _resolve_user(pool, username)+ if err:+ return err# Accept any code in emulationuser["UserStatus"] = "CONFIRMED"@@ -2080,9 +2104,9 @@ def _forgot_password(data):if not pool:return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _errcode = "654321"user["_reset_code"] = code@@ -2110,9 +2134,9 @@ def _confirm_forgot_password(data):if not pool:return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)- user = pool["_users"].get(username)- if not user:- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ user, _err = _resolve_user(pool, username)+ if _err:+ return _err# Accept any confirmation code in emulation (real AWS validates against issued code)pw_err = _validate_password(pool, new_password)@@ -3179,8 +3203,9 @@ def handle_login_submit(method, path, headers, body, query_params):# Authenticate usererror_msg = ""- user = pool["_users"].get(username)- if not user:+ user, _err = _resolve_user(pool, username)+ if _err:+ user = Noneerror_msg = "Incorrect username or password."elif not user.get("Enabled", True):error_msg = "User is disabled."diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 370c1ac9..e38b5781 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -2720,6 +2720,124 @@ def test_auth_codes_survive_warm_boot(_enable_persistence):mod.reset()+def test_cognito_alias_attributes_lookup_by_email(cognito_idp):+ """AliasAttributes=['email'] lets users be looked up by email as Username."""+ pid = cognito_idp.create_user_pool(+ PoolName="AliasEmailPool",+ AliasAttributes=["email"],+ AutoVerifiedAttributes=["email"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="alias-email-user",+ UserAttributes=[+ {"Name": "email", "Value": "[email protected]"},+ {"Name": "email_verified", "Value": "true"},+ ],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert user["Username"] == "alias-email-user"+++def test_cognito_alias_attributes_lookup_by_preferred_username(cognito_idp):+ """preferred_username alias doesn't require verification."""+ pid = cognito_idp.create_user_pool(+ PoolName="AliasPreferredPool",+ AliasAttributes=["preferred_username"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="alias-pref-user",+ UserAttributes=[{"Name": "preferred_username", "Value": "alice_pref"}],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="alice_pref")+ assert user["Username"] == "alias-pref-user"+++def test_cognito_alias_attributes_unverified_email_not_found(cognito_idp):+ """Unverified email aliases should NOT resolve when email_verified=false."""+ pid = cognito_idp.create_user_pool(+ PoolName="AliasUnverifiedPool",+ AliasAttributes=["email"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="alias-unverified",+ UserAttributes=[+ {"Name": "email", "Value": "[email protected]"},+ {"Name": "email_verified", "Value": "false"},+ ],+ )+ with pytest.raises(ClientError) as ex:+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert ex.value.response["Error"]["Code"] == "UserNotFoundException"+++def test_cognito_alias_attributes_email_without_verified_flag_not_found(cognito_idp):+ """Absent email_verified means alias is not resolvable (matches Cognito docs)."""+ pid = cognito_idp.create_user_pool(+ PoolName="AliasMissingVerifiedPool",+ AliasAttributes=["email"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="alias-missing-verified",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ with pytest.raises(ClientError) as ex:+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert ex.value.response["Error"]["Code"] == "UserNotFoundException"+++def test_cognito_alias_attributes_auth_with_email(cognito_idp):+ """InitiateAuth USER_PASSWORD_AUTH accepts the email alias as USERNAME."""+ pid = cognito_idp.create_user_pool(+ PoolName="AliasAuthPool",+ AliasAttributes=["email"],+ )["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid,+ ClientName="AliasAuthClient",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="alias-auth-user",+ UserAttributes=[+ {"Name": "email", "Value": "[email protected]"},+ {"Name": "email_verified", "Value": "true"},+ ],+ )+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="alias-auth-user",+ Password="StrongPass1!", Permanent=True,+ )+ resp = cognito_idp.initiate_auth(+ ClientId=cid,+ AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "[email protected]", "PASSWORD": "StrongPass1!"},+ )+ assert "AuthenticationResult" in resp+++def test_cognito_username_attributes_lookup_by_email(cognito_idp):+ """UsernameAttributes also enables email-based lookup."""+ pid = cognito_idp.create_user_pool(+ PoolName="UsernameAttrsPool",+ UsernameAttributes=["email"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="dave-sub-uuid",+ UserAttributes=[+ {"Name": "email", "Value": "[email protected]"},+ {"Name": "email_verified", "Value": "true"},+ ],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert user["Username"] == "dave-sub-uuid"++def test_auth_codes_dict_types_are_plain_builtin_dict():"""`_auth_codes` and `_authorization_codes` must remain plain `dict`instances. They're looked up by random unguessable token from a public