Skip to content

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

fix(cognito): auto-generate UUID Username for UsernameAttributes pools (#1194)

kjdev4541eb203c33
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index cd988179..d84ac981 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -838,19 +838,22 @@ def _resolve_user(pool: dict, username: str):
# 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 []
- )
+ # up via those attribute values. Real Cognito requires email/phone
+ # AliasAttributes to be verified (email_verified/phone_number_verified ==
+ # "true") before the alias resolves; preferred_username has no
+ # verification requirement. UsernameAttributes is different: it's the
+ # pool's actual sign-in identifier (AdminCreateUser stores the given
+ # value there without auto-verifying it), so it resolves unverified too.
+ username_attrs = set(pool.get("UsernameAttributes") or [])
+ alias_only_attrs = set(pool.get("AliasAttributes") or []) - username_attrs
+ alias_attrs = username_attrs | alias_only_attrs
if alias_attrs:
for u in pool["_users"].values():
attrs = _attr_list_to_dict(u.get("Attributes", []))
for alias in alias_attrs:
if attrs.get(alias) != username:
continue
- if alias in ("email", "phone_number"):
+ if alias in alias_only_attrs and alias in ("email", "phone_number"):
if str(attrs.get(f"{alias}_verified", "")).lower() != "true":
continue
return u, None
@@ -2148,6 +2151,23 @@ def _send_verification_email(pool, username, attr_dict, code, attribute_name="em
# USER MANAGEMENT
# ===========================================================================
+def _username_alias_attribute(pool: dict, username: str):
+ """Return which UsernameAttributes alias ("email"/"phone_number") the
+ given Username value should be registered as, or None if the pool
+ doesn't use UsernameAttributes. Real Cognito never uses the caller-
+ supplied value as the actual Username in this mode: it auto-generates a
+ UUID Username and stores the supplied value as the alias attribute.
+ """
+ username_attrs = set(pool.get("UsernameAttributes") or [])
+ if "email" in username_attrs and "phone_number" in username_attrs:
+ return "phone_number" if username.startswith("+") else "email"
+ if "email" in username_attrs:
+ return "email"
+ if "phone_number" in username_attrs:
+ return "phone_number"
+ return None
+
+
def _admin_create_user(data):
pid = data.get("UserPoolId")
pool, err = _resolve_pool(pid)
@@ -2158,8 +2178,12 @@ def _admin_create_user(data):
if not username:
return error_response_json("InvalidParameterException", "Username is required.", 400)
+ alias_attr = _username_alias_attribute(pool, username)
message_action = (data.get("MessageAction") or "").upper()
- existing = pool["_users"].get(username)
+ if alias_attr:
+ existing, _ = _resolve_user(pool, username)
+ else:
+ existing = pool["_users"].get(username)
if message_action == "RESEND":
if not existing:
return error_response_json(
@@ -2168,7 +2192,9 @@ def _admin_create_user(data):
existing["UserLastModifiedDate"] = _now_epoch()
attr_dict = _attr_list_to_dict(existing.get("Attributes", []))
if _wants_email_delivery(data):
- _send_invitation_email(pool, username, existing.get("_password", ""), attr_dict)
+ _send_invitation_email(
+ pool, existing["Username"], existing.get("_password", ""), attr_dict,
+ )
return json_response({"User": _user_out(existing)})
if existing:
@@ -2187,10 +2213,15 @@ def _admin_create_user(data):
attr_dict = _attr_list_to_dict(attrs)
if "sub" not in attr_dict:
attr_dict["sub"] = new_uuid()
+ if alias_attr:
+ attr_dict.setdefault(alias_attr, username)
+ real_username = new_uuid()
+ else:
+ real_username = username
attrs = _dict_to_attr_list(attr_dict)
user = {
- "Username": username,
+ "Username": real_username,
"Attributes": attrs,
"UserCreateDate": now,
"UserLastModifiedDate": now,
@@ -2201,12 +2232,12 @@ def _admin_create_user(data):
"_groups": [],
"_tokens": [],
}
- pool["_users"][username] = user
+ pool["_users"][real_username] = user
pool["EstimatedNumberOfUsers"] = len(pool["_users"])
- logger.info("Cognito: AdminCreateUser %s in pool %s", username, pid)
+ logger.info("Cognito: AdminCreateUser %s in pool %s", real_username, pid)
if message_action != "SUPPRESS" and _wants_email_delivery(data):
- _send_invitation_email(pool, username, temp_password, attr_dict)
+ _send_invitation_email(pool, real_username, temp_password, attr_dict)
return json_response({"User": _user_out(user)})
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 4e990d63..46e9f05e 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2989,15 +2989,12 @@ def test_oauth2_login_username_attributes_email_alias_completes_token_exchange()
client_id = client['ClientId']
client_secret = client['ClientSecret']
- real_username = 'alice-sub-uuid'
- cognito_idp.admin_create_user(
+ create_resp = cognito_idp.admin_create_user(
UserPoolId=pool_id,
- Username=real_username,
- UserAttributes=[
- {'Name': 'email', 'Value': '[email protected]'},
- {'Name': 'email_verified', 'Value': 'true'},
- ],
+ Username='[email protected]',
)
+ real_username = create_resp['User']['Username']
+ assert real_username != '[email protected]'
cognito_idp.admin_set_user_password(
UserPoolId=pool_id, Username=real_username, Password='TestPass1!', Permanent=True,
)
@@ -3038,6 +3035,101 @@ def test_oauth2_login_username_attributes_email_alias_completes_token_exchange()
_login_and_exchange(real_username, 'real-state')
+def test_oauth2_login_after_email_change_completes_token_exchange():
+ """Regression for #006 + #007 combined: with UsernameAttributes=["email"],
+ the real Username is an immutable UUID and email is just a mutable alias.
+ After AdminUpdateUserAttributes changes the email, logging in via the
+ Hosted UI with the *new* email must still complete the authorization
+ code exchange, and the old email must no longer resolve."""
+ cognito_idp = make_client('cognito-idp')
+ pool = cognito_idp.create_user_pool(
+ PoolName='UsernameAttrsEmailChangePool',
+ UsernameAttributes=['email'],
+ )
+ pool_id = pool['UserPool']['Id']
+
+ client_resp = cognito_idp.create_user_pool_client(
+ UserPoolId=pool_id,
+ ClientName='oauth2-test-client',
+ GenerateSecret=True,
+ AllowedOAuthFlows=['code'],
+ AllowedOAuthScopes=['openid', 'email', 'profile'],
+ AllowedOAuthFlowsUserPoolClient=True,
+ CallbackURLs=['http://localhost:3000/callback'],
+ LogoutURLs=['http://localhost:3000/logout'],
+ DefaultRedirectURI='http://localhost:3000/callback',
+ ExplicitAuthFlows=['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],
+ )
+ client = client_resp['UserPoolClient']
+ client_id = client['ClientId']
+ client_secret = client['ClientSecret']
+
+ create_resp = cognito_idp.admin_create_user(
+ UserPoolId=pool_id,
+ Username='[email protected]',
+ )
+ real_username = create_resp['User']['Username']
+ assert _uuid_mod.UUID(real_username)
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pool_id, Username=real_username, Password='TestPass1!', Permanent=True,
+ )
+
+ # Changing the email must not change the real Username (it stays UUID).
+ cognito_idp.admin_update_user_attributes(
+ UserPoolId=pool_id,
+ Username=real_username,
+ UserAttributes=[{'Name': 'email', 'Value': '[email protected]'}],
+ )
+ unchanged = cognito_idp.admin_get_user(UserPoolId=pool_id, Username=real_username)
+ assert unchanged['Username'] == real_username
+
+ status, headers, body = _post_form(
+ f'{ENDPOINT}/login',
+ {
+ 'username': '[email protected]',
+ 'password': 'TestPass1!',
+ 'client_id': client_id,
+ 'redirect_uri': 'http://localhost:3000/callback',
+ 'scope': 'openid email',
+ 'state': 'new-email-state',
+ 'response_type': 'code',
+ },
+ follow_redirects=False,
+ )
+ assert status == 302
+ location = headers.get('location', '')
+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)
+ code = qs['code'][0]
+
+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ '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
+
+ # The old email must no longer resolve to the user.
+ status, headers, body = _post_form(
+ f'{ENDPOINT}/login',
+ {
+ 'username': '[email protected]',
+ 'password': 'TestPass1!',
+ 'client_id': client_id,
+ 'redirect_uri': 'http://localhost:3000/callback',
+ 'scope': 'openid email',
+ 'state': 'old-email-state',
+ 'response_type': 'code',
+ },
+ follow_redirects=False,
+ )
+ assert status == 200
+ assert b'Incorrect username or password' in body
+
+
# ---------------------------------------------------------------------------
# Tests — /oauth2/userInfo
# ---------------------------------------------------------------------------
@@ -3621,21 +3713,24 @@ def test_cognito_alias_attributes_auth_with_email(cognito_idp):
def test_cognito_username_attributes_lookup_by_email(cognito_idp):
- """UsernameAttributes also enables email-based lookup."""
+ """UsernameAttributes also enables email-based lookup. Real Cognito
+ never uses the supplied value as the actual Username in this mode: it
+ auto-generates a UUID Username and stores the value as the email
+ attribute instead."""
pid = cognito_idp.create_user_pool(
PoolName="UsernameAttrsPool",
UsernameAttributes=["email"],
)["UserPool"]["Id"]
- cognito_idp.admin_create_user(
+ create_resp = cognito_idp.admin_create_user(
UserPoolId=pid,
- Username="dave-sub-uuid",
- UserAttributes=[
- {"Name": "email", "Value": "[email protected]"},
- {"Name": "email_verified", "Value": "true"},
- ],
+ Username="[email protected]",
)
+ real_username = create_resp["User"]["Username"]
+ assert real_username != "[email protected]"
+ assert _uuid_mod.UUID(real_username)
+
user = cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")
- assert user["Username"] == "dave-sub-uuid"
+ assert user["Username"] == real_username
def test_auth_codes_dict_types_are_plain_builtin_dict():