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): admin handlers key on the resolved Username (#1514)
Lukas Döllerer134d5b878069
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f32c3ba4..ce2f8387 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **SNS — `GetPlatformApplicationAttributes` / `SetPlatformApplicationAttributes`** — a platform application could be created and deleted but never read back or updated: both actions answered `400 InvalidAction`, so `terraform plan` on an `aws_sns_platform_application` failed at refresh (`reading SNS Platform Application (...): Unknown action: GetPlatformApplicationAttributes`) and the resource could never reach a clean state. Both now answer with the documented shapes — `Get` returns the attribute map as `entry` key/value pairs, `Set` merges the supplied entries (`PlatformCredential`, `PlatformPrincipal`, the `Event*` topic ARNs, `*FeedbackRoleArn`, `Enabled`, ...) and returns only `ResponseMetadata` — with `InvalidParameter` (400) for a missing `PlatformApplicationArn` or `Attributes` and `NotFound` (404) for an unknown application. `CreatePlatformApplication` also seeds `Enabled=true`, as AWS reports for a newly created application.### Fixed+- **Cognito — group membership records the resolved Username** — `AdminAddUserToGroup` stored the caller-supplied name in the group's member list, but the list is read back as `_users` keys. In a pool with `UsernameAttributes = ["email"]` that name is an email alias, not the key, so `ListUsersInGroup` returned an empty list for a group that had just accepted the user, `AdminRemoveUserFromGroup` did not match the entry it had added, and `DeleteGroup` left the group on the user's own group list. Both operations now key on the resolved Username.+- **Cognito — `AdminDeleteUser` deletes the user an email alias resolves to** — in a pool with `UsernameAttributes = ["email"]`, `AdminCreateUser` stores the user under a generated UUID Username and keeps the email as an alias attribute, as real Cognito does. `AdminDeleteUser` resolved the alias correctly but then deleted by the caller-supplied name, which is not the key, so the call raised `KeyError` and answered `500 InternalError` while the user survived. A seed or test fixture that deletes and creates the same user therefore failed with `UsernameExistsException` on every run after the first. The delete now uses the resolved Username.- **S3 — a presigned upload no longer drops the `x-amz-*` headers it was signed with** — a presigned URL is sent by a caller who has only the URL and a body, so SigV4 lets the `x-amz-*` headers an operation asked for be hoisted into the query string, where the signature covers them exactly as a signed header would. SDKs presign that way and real S3 applies those params as the headers they stand for. MiniStack only ever read headers, so a presigned `PutObject` carrying user metadata in its query string answered `200` and stored the object with no metadata at all. Hoisted `x-amz-*` params are now folded back into the request headers before routing (user metadata, storage class, tagging, ACL, SSE and copy source) while an explicitly sent header still wins over its hoisted twin, and the SigV4 signing params are never mistaken for one. Contributed by @dennmart.- **CloudFormation — `Fn::Sub` honors the `${!Literal}` escape** — the leading `!` was not recognized, so the name fell through every lookup and rendered as `!Literal` with the braces consumed; `${!Literal}` now renders as the literal `${Literal}` and no longer registers a dependency on a resource of that name. An `AWS::IoT::Policy` pinned to `${!iot:Connection.Thing.ThingName}` deployed with a document matching nothing, so the policy denied every connect, publish and subscribe while the stack still reported `CREATE_COMPLETE`. Reported by @iot-rocket.### Addeddiff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 81dc6d81..fa3c64ca 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2640,7 +2640,9 @@ def _admin_delete_user(data):user, err = _resolve_user(pool, username)if err:return err- del pool["_users"][username]+ # Delete by the resolved Username. In a UsernameAttributes pool the caller+ # can pass an alias (email), which is not the "_users" key.+ del pool["_users"][user["Username"]]pool["EstimatedNumberOfUsers"] = len(pool["_users"])return json_response({})@@ -2880,7 +2882,7 @@ def _admin_add_user_to_group(data):return error_response_json("ResourceNotFoundException", f"Group {group_name} not found.", 400)if group_name not in user.get("_groups", []):user.setdefault("_groups", []).append(group_name)- pool["_groups"][group_name].setdefault("_members", []).append(username)+ pool["_groups"][group_name].setdefault("_members", []).append(user["Username"])return json_response({})@@ -2898,8 +2900,8 @@ def _admin_remove_user_from_group(data):user["_groups"].remove(group_name)if group_name in pool["_groups"]:members = pool["_groups"][group_name].get("_members", [])- if username in members:- members.remove(username)+ if user["Username"] in members:+ members.remove(user["Username"])return json_response({})diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex d5bda1de..abf1d4fe 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -4695,6 +4695,54 @@ def test_cognito_username_attributes_lookup_by_email(cognito_idp):assert user["Username"] == real_username+def test_cognito_admin_delete_user_by_email_alias(cognito_idp):+ """AdminDeleteUser must delete the user that the alias resolves to. In a+ UsernameAttributes pool the "_users" key is a generated UUID, so a delete+ keyed on the caller-supplied email raised KeyError and the user survived.+ A delete-then-create seed then failed with UsernameExistsException."""+ pid = cognito_idp.create_user_pool(+ PoolName="DeleteAliasPool",+ UsernameAttributes=["email"],+ )["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="[email protected]")++ cognito_idp.admin_delete_user(UserPoolId=pid, Username="[email protected]")++ with pytest.raises(ClientError) as exc:+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"+ assert cognito_idp.list_users(UserPoolId=pid)["Users"] == []++ # The pool accepts the same email again.+ cognito_idp.admin_create_user(UserPoolId=pid, Username="[email protected]")+++def test_cognito_admin_group_membership_by_email_alias(cognito_idp):+ """Group membership must record the resolved Username. Storing the+ caller-supplied alias made ListUsersInGroup drop the member, because it+ looks members up as "_users" keys."""+ pid = cognito_idp.create_user_pool(+ PoolName="GroupAliasPool",+ UsernameAttributes=["email"],+ )["UserPool"]["Id"]+ real_username = cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="[email protected]",+ )["User"]["Username"]+ cognito_idp.create_group(UserPoolId=pid, GroupName="admins")++ cognito_idp.admin_add_user_to_group(+ UserPoolId=pid, Username="[email protected]", GroupName="admins",+ )+ members = cognito_idp.list_users_in_group(UserPoolId=pid, GroupName="admins")["Users"]+ assert [u["Username"] for u in members] == [real_username]++ cognito_idp.admin_remove_user_from_group(+ UserPoolId=pid, Username="[email protected]", GroupName="admins",+ )+ assert cognito_idp.list_users_in_group(UserPoolId=pid, GroupName="admins")["Users"] == []++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