Skip to content

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

fix(cognito): honour PreventUserExistenceErrors across the auth flows (#1576)

Frederic H-Fe04060e5e4f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8584f59..5d8cb6ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,11 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Fixed
+- **Cognito — `PreventUserExistenceErrors=ENABLED` now hides an unknown user** — an app client created with the setting still answered `UserNotFoundException` from the flows a browser reaches, so any sign-in or password-reset form backed by MiniStack told an attacker which addresses have an account. The setting was accepted, stored and echoed back by `DescribeUserPoolClient`, so the client looked correctly configured while nothing read it. The flows AWS names for the setting — `USER_PASSWORD_AUTH`, `USER_SRP_AUTH` and `ADMIN_USER_PASSWORD_AUTH` — now answer `NotAuthorizedException` with the wrong-password message, at `RespondToAuthChallenge` as well as at `InitiateAuth`, which is what closes SRP: its `InitiateAuth` returns a `PASSWORD_VERIFIER` challenge without resolving the user, so the leak sat one step later, in the step every browser SDK makes. `ForgotPassword` and `ResendConfirmationCode` answer a normal `CodeDeliveryDetails` while delivering nothing and changing no state, and `ConfirmForgotPassword` answers `CodeMismatchException`. The `Destination` those two report is now masked as AWS reports it (`j****@e****`) on the real-user path too, since a full address there would have restored the same oracle in another field. `LEGACY` clients are unchanged, and the admin *directory* operations such as `AdminGetUser` keep reporting `UserNotFoundException` — only the admin auth flow is covered, as AWS documents. `CUSTOM_AUTH` is untouched: AWS handles it by passing `UserNotFound: true` to the challenge Lambda, which MiniStack does not model yet. Reported by @fhfournier.
+
## [1.5.4] — 2026-08-31
### Added
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index f58c3372..21cf2360 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1176,6 +1176,79 @@ def _resolve_user(pool: dict, username: str):
)
+def _hides_user_existence(pool: dict, client_id: str) -> bool:
+ """
+ Whether this app client must not reveal that a user is unknown.
+
+ With PreventUserExistenceErrors=ENABLED, real Cognito makes an unknown
+ username indistinguishable from a wrong password across the flows it names:
+ USER_PASSWORD_AUTH, USER_SRP_AUTH and ADMIN_USER_PASSWORD_AUTH answer
+ NotAuthorizedException, ForgotPassword and ResendConfirmationCode answer a
+ normal CodeDeliveryDetails, and ConfirmForgotPassword answers
+ CodeMismatchException.
+
+ The setting is a property of the app client, so it covers the admin
+ *authentication* flow as well — AWS lists ADMIN_USER_PASSWORD_AUTH
+ explicitly. It does not cover the directory operations: AdminGetUser and
+ friends keep reporting UserNotFoundException.
+
+ Two flows are deliberately untouched, as AWS handles them by other means:
+ CUSTOM_AUTH, where Cognito instead invokes the challenge Lambda with
+ UserNotFound=true, and the USER_AUTH choice-based flow, which the setting
+ does not affect.
+ """
+ client = (pool.get("_clients") or {}).get(client_id) or {}
+ return client.get("PreventUserExistenceErrors", "ENABLED") == "ENABLED"
+
+
+def _hidden_user_error(pool: dict, client_id: str, err):
+ """
+ `err` unless this client hides user existence, in which case the generic
+ auth failure that a wrong password also produces.
+
+ Used by every branch of the auth flows AWS names for the setting —
+ USER_PASSWORD_AUTH, USER_SRP_AUTH and ADMIN_USER_PASSWORD_AUTH — including
+ the RespondToAuthChallenge steps that continue them, because that is where
+ an SRP sign-in resolves the user: masking only InitiateAuth would leave the
+ browser flow leaking.
+ """
+ if _hides_user_existence(pool, client_id):
+ return error_response_json(
+ "NotAuthorizedException", "Incorrect username or password.", 400,
+ )
+ return err
+
+
+def _masked_destination(address: str) -> str:
+ """
+ Mask a delivery destination the way Cognito reports it: j****@e****.
+
+ Applied to BOTH the real and the unknown-user path, which is what makes the
+ two indistinguishable: returning the full address for a real user and a mask
+ for an unknown one would just move the enumeration oracle into this field.
+ AWS masks it in either case, and drops the domain suffix as well.
+
+ For a user who does not exist there is no stored address to mask, so the
+ requested username is masked instead — the same substitution AWS documents
+ for ForgotPassword, whose simulated destination is "determined by the input
+ username format".
+ """
+ if not address or "@" not in address:
+ return "****"
+ local, _, domain = address.partition("@")
+ return f"{local[:1]}****@{domain[:1]}****"
+
+
+def _code_delivery_response(destination: str):
+ return json_response({
+ "CodeDeliveryDetails": {
+ "Destination": destination,
+ "DeliveryMedium": "EMAIL",
+ "AttributeName": "email",
+ }
+ })
+
+
def _user_out(user: dict) -> dict:
"""Serialise a user dict for API responses."""
return {
@@ -3076,19 +3149,15 @@ def _resend_confirmation_code(data):
user = pool["_users"].get(username)
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)
code = user.get("_confirmation_code") or "123456"
user["_confirmation_code"] = code
attrs = _attr_list_to_dict(user.get("Attributes", []))
_send_verification_email(pool, username, attrs, code)
- return json_response({
- "CodeDeliveryDetails": {
- "Destination": attrs.get("email", ""),
- "DeliveryMedium": "EMAIL",
- "AttributeName": "email",
- }
- })
+ return _code_delivery_response(_masked_destination(attrs.get("email") or username))
def _admin_user_global_sign_out(data):
@@ -3261,7 +3330,7 @@ def _admin_initiate_auth(data):
password = auth_params.get("PASSWORD")
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
if not user.get("Enabled", True):
return error_response_json("NotAuthorizedException", "User is disabled.", 400)
refused = _password_signin_refused(user)
@@ -3441,7 +3510,7 @@ def _admin_respond_to_auth_challenge(data):
user, err = _resolve_user(pool, username)
if err:
del _challenge_sessions[token]
- return err
+ return _hidden_user_error(pool, cid, err)
refused = _password_signin_refused(user)
if refused:
return refused
@@ -3466,7 +3535,7 @@ def _admin_respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
refused = _password_signin_refused(user)
if refused:
return refused
@@ -3482,7 +3551,7 @@ def _admin_respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -3491,7 +3560,7 @@ def _admin_respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
# Accept any TOTP code in emulator — no real TOTP validation
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -3502,7 +3571,7 @@ def _admin_respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -3587,7 +3656,7 @@ def _initiate_auth(data):
password = auth_params.get("PASSWORD")
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
if not user.get("Enabled", True):
return error_response_json("NotAuthorizedException", "User is disabled.", 400)
refused = _password_signin_refused(user)
@@ -3773,7 +3842,7 @@ def _respond_to_auth_challenge(data):
user, err = _resolve_user(pool, username)
if err:
del _challenge_sessions[token]
- return err
+ return _hidden_user_error(pool, cid, err)
refused = _password_signin_refused(user)
if refused:
return refused
@@ -3797,7 +3866,7 @@ def _respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
refused = _password_signin_refused(user)
if refused:
return refused
@@ -3814,7 +3883,7 @@ def _respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
refused = _password_signin_refused(user)
if refused:
return refused
@@ -3830,7 +3899,7 @@ def _respond_to_auth_challenge(data):
client_metadata = data.get("ClientMetadata", {})
user, _err = _resolve_user(pool, username)
if _err:
- return _err
+ return _hidden_user_error(pool, cid, _err)
# Accept any TOTP code in emulator
return json_response({"AuthenticationResult": _build_auth_result(
pid, cid, user, client_metadata=client_metadata)})
@@ -3994,19 +4063,17 @@ def _forgot_password(data):
user, _err = _resolve_user(pool, username)
if _err:
+ if _hides_user_existence(pool, cid):
+ # 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
code = "654321"
user["_reset_code"] = code
attrs = _attr_list_to_dict(user.get("Attributes", []))
_send_verification_email(pool, username, attrs, code, attribute_name="password")
- return json_response({
- "CodeDeliveryDetails": {
- "Destination": attrs.get("email", ""),
- "DeliveryMedium": "EMAIL",
- "AttributeName": "email",
- }
- })
+ return _code_delivery_response(_masked_destination(attrs.get("email") or username))
def _confirm_forgot_password(data):
@@ -4024,6 +4091,13 @@ def _confirm_forgot_password(data):
user, _err = _resolve_user(pool, username)
if _err:
+ if _hides_user_existence(pool, cid):
+ # An unknown username looks like a bad code, which is what a caller
+ # would see for a real user given the wrong code.
+ return error_response_json(
+ "CodeMismatchException",
+ "Invalid verification code provided, please try again.", 400,
+ )
return _err
# Accept any confirmation code in emulation (real AWS validates against issued code)
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 220207ce..efa1809a 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -7902,3 +7902,172 @@ def test_cognito_user_pool_keeps_mfa_and_attribute_update_settings(cognito_idp):
assert "SoftwareTokenMfaConfiguration" not in cognito_idp.get_user_pool_mfa_config(
UserPoolId=other
)
+
+
+def _pool_with_client(cognito_idp, prevent):
+ """A pool plus an app client with a given PreventUserExistenceErrors value."""
+ pid = cognito_idp.create_user_pool(PoolName="ExistencePool")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid,
+ ClientName="existence",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH",
+ "ALLOW_USER_SRP_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ PreventUserExistenceErrors=prevent,
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(
+ UserPoolId=pid, Username="[email protected]", MessageAction="SUPPRESS",
+ )
+ cognito_idp.admin_set_user_password(
+ UserPoolId=pid, Username="[email protected]",
+ Password="Correct1!", Permanent=True,
+ )
+ return pid, cid
+
+
+def test_cognito_prevent_user_existence_errors_masks_initiate_auth(cognito_idp):
+ """An unknown username must be indistinguishable from a wrong password."""
+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+
+ def failure(username):
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": username, "PASSWORD": "Wrong1!"},
+ )
+ err = exc.value.response["Error"]
+ return err["Code"], err["Message"]
+
+ unknown = failure("[email protected]")
+ known = failure("[email protected]")
+
+ assert unknown == known, "the two failures must not be distinguishable"
+ assert unknown[0] == "NotAuthorizedException"
+ # And the message must not name the address that was probed.
+ assert "[email protected]" not in unknown[1]
+
+
+def test_cognito_prevent_user_existence_errors_legacy_still_reports(cognito_idp):
+ """LEGACY keeps the distinct error, which is what AWS does."""
+ _pid, cid = _pool_with_client(cognito_idp, "LEGACY")
+
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "[email protected]", "PASSWORD": "Wrong1!"},
+ )
+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
+
+
+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")
+
+ resp = cognito_idp.forgot_password(ClientId=cid, Username="[email protected]")
+ delivery = resp["CodeDeliveryDetails"]
+ assert delivery["DeliveryMedium"] == "EMAIL"
+ # The destination is masked, so it cannot be used to confirm the address.
+ assert delivery["Destination"] != "[email protected]"
+ assert "***" in delivery["Destination"]
+
+
+def test_cognito_prevent_user_existence_errors_masks_resend_confirmation(cognito_idp):
+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+
+ resp = cognito_idp.resend_confirmation_code(
+ ClientId=cid, Username="[email protected]",
+ )
+ assert resp["CodeDeliveryDetails"]["DeliveryMedium"] == "EMAIL"
+
+
+def test_cognito_prevent_user_existence_errors_masks_confirm_forgot_password(cognito_idp):
+ """An unknown username looks like a bad code."""
+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.confirm_forgot_password(
+ ClientId=cid, Username="[email protected]",
+ ConfirmationCode="000000", Password="Another1!",
+ )
+ 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.
+
+ Masking only the unknown-user path would leave the oracle in place: a full
+ address for a real user and a mask for an unknown one is still a yes/no
+ answer. The two usernames below mask to the same string, so an identical
+ response proves the field is a function of the request alone.
+ """
+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+ real = "[email protected]" # exists
+ unknown = "[email protected]" # does not — same mask: k***@e***.test
+
+ for call in ("forgot_password", "resend_confirmation_code"):
+ send = getattr(cognito_idp, call)
+ a = send(ClientId=cid, Username=real)["CodeDeliveryDetails"]
+ b = send(ClientId=cid, Username=unknown)["CodeDeliveryDetails"]
+ assert a == b, f"{call} distinguishes the two users: {a} vs {b}"
+ assert a["Destination"] == "k****@e****"
+ assert real not in a["Destination"]
+
+
+def test_cognito_prevent_user_existence_errors_admin_directory_still_reports(cognito_idp):
+ """The setting covers the admin auth flow, not the admin directory reads.
+
+ AWS names ADMIN_USER_PASSWORD_AUTH among the flows it masks, so
+ AdminInitiateAuth must fail the same way for an unknown user as for a wrong
+ password. AdminGetUser is not an auth flow and keeps reporting the truth,
+ which provisioning scripts branch on.
+ """
+ pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")
+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
+
+ def admin_failure(username):
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid, AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": username, "PASSWORD": "Wrong1!"},
+ )
+ err = exc.value.response["Error"]
+ return err["Code"], err["Message"]
+
+ assert admin_failure("[email protected]") == admin_failure("[email protected]")
+ assert admin_failure("[email protected]")[0] == "NotAuthorizedException"
+
+
+def test_cognito_prevent_user_existence_errors_masks_srp_challenge(cognito_idp):
+ """USER_SRP_AUTH must not leak at RespondToAuthChallenge.
+
+ This is the flow a browser SDK uses. InitiateAuth answers a
+ PASSWORD_VERIFIER challenge without resolving the user at all, so masking
+ InitiateAuth alone would leave the whole browser sign-in leaking one step
+ later, where the password proof is checked.
+ """
+ _pid, cid = _pool_with_client(cognito_idp, "ENABLED")
+
+ def srp_failure(username):
+ started = cognito_idp.initiate_auth(
+ ClientId=cid, AuthFlow="USER_SRP_AUTH",
+ AuthParameters={"USERNAME": username, "SRP_A": "ab" * 32},
+ )
+ assert started["ChallengeName"] == "PASSWORD_VERIFIER"
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.respond_to_auth_challenge(
+ ClientId=cid, ChallengeName="PASSWORD_VERIFIER",
+ Session=started["Session"],
+ ChallengeResponses={
+ "USERNAME": username,
+ "PASSWORD_CLAIM_SIGNATURE": "sig",
+ "PASSWORD_CLAIM_SECRET_BLOCK": "blk",
+ "TIMESTAMP": "Mon Aug 31 00:00:00 UTC 2026",
+ },
+ )
+ err = exc.value.response["Error"]
+ return err["Code"], err["Message"]
+
+ assert srp_failure("[email protected]") == (
+ "NotAuthorizedException", "Incorrect username or password.")