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): answer unknown users as AWS does (#2349)
iot-rocket8c9a9c7ca25b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6bfdb46b..b44057a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.### Fixed+- **Cognito — unknown users** — calls for a user who does not exist answered `User <name> does not exist.`; they now answer `User does not exist.` as AWS does, and with `PreventUserExistenceErrors` `LEGACY` `ForgotPassword`, `ConfirmForgotPassword`, `ResendConfirmationCode` and `ConfirmSignUp` answer `Username/client id combination not found.`. With `ENABLED`, `ConfirmSignUp` answers `CodeMismatchException` instead of revealing that the user does not exist. Contributed by @iot-rocket.- **CloudFormation — S3 bucket CORS, Block Public Access and website** — `AWS::S3::Bucket` applied only `VersioningConfiguration` and `NotificationConfiguration` and dropped `CorsConfiguration`, `PublicAccessBlockConfiguration` and `WebsiteConfiguration`, so `GetBucketCors`, `GetPublicAccessBlock` and `GetBucketWebsite` found no configuration after a stack create; the three are now stored on create, replaced on update and deleted when an update removes them. Contributed by @iot-rocket.- **S3 — access point Block Public Access** — requests through an access point alias or ARN followed the bucket's Block Public Access settings alone, so a public ACL sent through an access point with the default settings was accepted. An access point's settings other than `BlockPublicPolicy` now count as the bucket's for requests through it, and its `BlockPublicAcls` refuses a public canned ACL, grant header or ACL body with 403 `AccessDenied`. Contributed by @iot-rocket.- **Lambda — Node.js HTTPS to a TLS gateway in the local executor** — with `USE_SSL=1` a Node function's `https` requests to the gateway went out as plain HTTP to its TLS port and the built-in SDK v3 clients always spoke HTTP, so custom resource callbacks and SDK calls failed with `socket hang up`; they now keep TLS on the gateway port, and `https.request` or `https.get` with a URL plus options no longer throws `ERR_INVALID_ARG_TYPE`. Contributed by @iot-rocket.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 40b6509a..8a19fbf8 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -1406,7 +1406,7 @@ def _resolve_user(pool: dict, username: str):return None, error_response_json("UserNotFoundException",- f"User {username} does not exist.", 400,+ "User does not exist.", 400,)@@ -1418,7 +1418,7 @@ def _hides_user_existence(pool: dict, client_id: str) -> bool:username indistinguishable from a wrong password across the flows it names:USER_PASSWORD_AUTH, USER_SRP_AUTH and ADMIN_USER_PASSWORD_AUTH answerNotAuthorizedException, ForgotPassword and ResendConfirmationCode answer a- normal CodeDeliveryDetails, and ConfirmForgotPassword answers+ normal CodeDeliveryDetails, and ConfirmForgotPassword and ConfirmSignUp answerCodeMismatchException.The setting is a property of the app client, so it covers the admin@@ -1453,6 +1453,11 @@ def _hidden_user_error(pool: dict, client_id: str, err):return err+def _client_user_not_found():+ """The UserNotFoundException of the sign-up confirmation and password recovery calls."""+ return error_response_json("UserNotFoundException", "Username/client id combination not found.", 400)++def _masked_destination(address: str) -> str:"""Mask a delivery destination the way Cognito reports it: j****@e****.@@ -3957,7 +3962,7 @@ def _resend_confirmation_code(data):if not user:if _hides_user_existence(pool, cid):return _code_delivery_response(_masked_destination(username))- return error_response_json("UserNotFoundException", "User does not exist.", 400)+ return _client_user_not_found()code = user.get("_confirmation_code") or "123456"user["_confirmation_code"] = code@@ -5116,7 +5121,12 @@ def _confirm_sign_up(data):user, err = _resolve_user(pool, username)if err:- return err+ if _hides_user_existence(pool, cid):+ return error_response_json(+ "CodeMismatchException",+ "Invalid verification code provided, please try again.", 400,+ )+ return _client_user_not_found()# Codes are checked under AUTH=true (_confirmation_code_error).user.pop("_confirmation_code", None)@@ -5143,7 +5153,7 @@ def _forgot_password(data):# Answer as though a code had been sent. Nothing is delivered and no# state changes; only the response shape is preserved.return _code_delivery_response(_masked_destination(username))- return _err+ return _client_user_not_found()code = "654321"user["_reset_code"] = code@@ -5174,7 +5184,7 @@ def _confirm_forgot_password(data):"CodeMismatchException","Invalid verification code provided, please try again.", 400,)- return _err+ return _client_user_not_found()# Codes are checked under AUTH=true (_confirmation_code_error).pw_err = _validate_password(pool, new_password)diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 49c4c8e3..1b9f39e9 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -10693,6 +10693,35 @@ def test_cognito_prevent_user_existence_errors_legacy_still_reports(cognito_idp)assert exc.value.response["Error"]["Code"] == "UserNotFoundException"[email protected]("call,params,message", [+ ("initiate_auth", {"AuthFlow": "USER_PASSWORD_AUTH"}, "User does not exist."),+ ("admin_initiate_auth", {"AuthFlow": "ADMIN_USER_PASSWORD_AUTH"}, "User does not exist."),+ ("admin_get_user", {}, "User does not exist."),+ ("forgot_password", {}, "Username/client id combination not found."),+ ("confirm_forgot_password", {"ConfirmationCode": "000000", "Password": "Another1!"},+ "Username/client id combination not found."),+ ("resend_confirmation_code", {}, "Username/client id combination not found."),+ ("confirm_sign_up", {"ConfirmationCode": "000000"}, "Username/client id combination not found."),+])+def test_cognito_prevent_user_existence_errors_legacy_messages(cognito_idp, call, params, message):+ """LEGACY names no username: user calls say the user does not exist, code calls the client combination."""+ pid, cid = _pool_with_client(cognito_idp, "LEGACY")+ username = "[email protected]"+ if "AuthFlow" in params:+ params = {**params, "AuthParameters": {"USERNAME": username, "PASSWORD": "Wrong1!"}}+ else:+ params = {**params, "Username": username}+ if call.startswith("admin_"):+ params["UserPoolId"] = pid+ if call != "admin_get_user":+ params["ClientId"] = cid++ with pytest.raises(ClientError) as exc:+ getattr(cognito_idp, call)(**params)+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"+ assert exc.value.response["Error"]["Message"] == message++def test_cognito_prevent_user_existence_errors_masks_forgot_password(cognito_idp):"""ForgotPassword answers as though a code was sent."""_pid, cid = _pool_with_client(cognito_idp, "ENABLED")@@ -10726,6 +10755,15 @@ def test_cognito_prevent_user_existence_errors_masks_confirm_forgot_password(cogassert exc.value.response["Error"]["Code"] == "CodeMismatchException"+def test_cognito_prevent_user_existence_errors_masks_confirm_sign_up(cognito_idp):+ """ConfirmSignUp for an unknown username looks like a bad code too."""+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")++ with pytest.raises(ClientError) as exc:+ cognito_idp.confirm_sign_up(ClientId=cid, Username="[email protected]", ConfirmationCode="000000")+ assert exc.value.response["Error"]["Code"] == "CodeMismatchException"++def test_cognito_prevent_user_existence_errors_delivery_details_identical(cognito_idp):"""The masked destination must carry no trace of whether the user exists.