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): verify app client secret hashes (#1989)
Adrian-Ryan Acala5eef3be4c831
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec23b5bd..ed0cfdf2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **Cognito — app client secret hashes** — clients created with `GenerateSecret=true` require a valid `SecretHash` on signup, confirmation and password recovery, and `SECRET_HASH` on authentication and challenge responses. Missing or incorrect hashes return `NotAuthorizedException` before user changes, email delivery or Lambda triggers. Clients without a secret reject a supplied hash on self-service and initial authentication calls, while refresh and challenge responses ignore it, as on AWS. Refresh authentication verifies the token owner's username, or `sub` when the pool uses `UsernameAttributes`, and custom challenge sessions cannot be answered through a different client. The checks apply in both `AUTH` modes.### Added- **Aurora DSQL — partial indexes** — `CREATE INDEX ASYNC ... WHERE predicate` was refused `0A000` although the service supports it since 2026-09-15; the predicate now reaches the backend and builds a real partial index (unique partial indexes scope uniqueness to the rows they cover). A predicate calling a volatile function fails at submit with `42P17` "functions in index predicate must be marked IMMUTABLE", and a subquery with `0A000`, instead of coming back as a failed job; both are checked in the order the live service uses (eu-central-1, 2026-10-04). Contributed by @vivedo.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 4dcd7c1a..761f3653 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2253,9 +2253,96 @@ def _pin_unsigned_idp_scope(data: dict) -> None:set_request_region(region)+_SECRET_HASH_PARAMETERS = {+ "SignUp": "",+ "ConfirmSignUp": "",+ "ResendConfirmationCode": "",+ "ForgotPassword": "",+ "ConfirmForgotPassword": "",+ "InitiateAuth": "AuthParameters",+ "AdminInitiateAuth": "AuthParameters",+ "RespondToAuthChallenge": "ChallengeResponses",+ "AdminRespondToAuthChallenge": "ChallengeResponses",+}+++def _validate_client_secret_hash(action: str, data: dict):+ """Authenticate confidential app clients before user changes or triggers.++ This is Cognito's app-client contract, independent of IAM's AUTH flag.+ Refresh authentication uses the token owner's username (or sub for a+ UsernameAttributes pool), rather than the alias used at initial sign-in.+ """+ parameter = _SECRET_HASH_PARAMETERS.get(action)+ if parameter is None:+ return None+ cid = data.get("ClientId")+ if action.startswith("Admin"):+ pool = _user_pools.get(data.get("UserPoolId"))+ else:+ pool, _pid = _pool_for_client(cid)+ client = (pool or {}).get("_clients", {}).get(cid)+ if not client:+ # Let the operation retain its own missing-pool/client errors.+ return None++ params = data.get(parameter, {}) if parameter else data+ if parameter == "ChallengeResponses":+ session = _challenge_sessions.get(data.get("Session"))+ if session and (session["client_id"] != cid or session["pool_id"] != pool["Id"]):+ return error_response_json("NotAuthorizedException", "Invalid session for the user.", 400)++ username = params.get("USERNAME" if parameter else "Username")+ refreshing = parameter == "AuthParameters" and data.get("AuthFlow") in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN")+ if refreshing:+ # AWS rejects invalid refresh tokens before examining their secret hash.+ user, error = _refresh_auth_user(pool, pool["Id"], cid, params.get("REFRESH_TOKEN", ""))+ if error:+ return error+ username = (+ _attr_list_to_dict(user.get("Attributes", [])).get("sub")+ if pool.get("UsernameAttributes") else user["Username"]+ )++ supplied = params.get("SECRET_HASH" if parameter else "SecretHash")+ if not client.get("ClientSecret"):+ # AWS ignores an extra hash on refresh and challenge responses, but+ # rejects it on initial authentication and the self-service APIs.+ if refreshing or parameter == "ChallengeResponses":+ return None+ if supplied:+ return error_response_json(+ "InvalidParameterException",+ f"App client {cid} is not configured for secret but secret hash was received", 400,+ )+ return None+ if not supplied:+ return error_response_json(+ "NotAuthorizedException",+ f"Client {cid} is configured with secret but SECRET_HASH was not received", 400,+ )+ if isinstance(username, str) and isinstance(supplied, str) and supplied.isascii():+ try:+ expected = base64.b64encode(hmac.new(+ client["ClientSecret"].encode("utf-8"),+ (username + cid).encode("utf-8"), hashlib.sha256,+ ).digest())+ except UnicodeEncodeError:+ pass+ else:+ if hmac.compare_digest(expected, supplied.encode("ascii")):+ return None+ return error_response_json(+ "NotAuthorizedException", f"Unable to verify secret hash for client {cid}", 400,+ )++def _run_idp_handler(handler, action: str, data: dict):if action in _UNSIGNED_IDP_ACTIONS:_pin_unsigned_idp_scope(data)+ error = _validate_client_secret_hash(action, data)+ if error:+ return errorreturn handler(data)@@ -3757,6 +3844,8 @@ def _admin_respond_to_auth_challenge(data):pool, err = _resolve_pool(pid)if err:return err+ if cid not in pool["_clients"]:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)challenge_name = data.get("ChallengeName", "")responses = data.get("ChallengeResponses", {})@@ -3893,10 +3982,8 @@ def _pool_for_client(cid):return None, None-def _refresh_auth_result(pool, pid, cid, refresh_token):- """Shared REFRESH_TOKEN_AUTH core. Returns (auth_result_dict, error_response);- exactly one is non-None. Used by InitiateAuth's REFRESH_TOKEN_AUTH branch and- by GetTokensFromRefreshToken so both mint tokens identically."""+def _refresh_auth_user(pool, pid, cid, refresh_token):+ """Resolve a refresh-token owner without issuing tokens or invoking triggers."""if not refresh_token:return None, error_response_json("NotAuthorizedException", "Refresh token is missing.", 400)try:@@ -3916,6 +4003,16 @@ def _refresh_auth_result(pool, pid, cid, refresh_token):if _refresh_token_revoked(refresh_token, user):return None, error_response_json("NotAuthorizedException","Refresh Token has been revoked", 400)+ return user, None+++def _refresh_auth_result(pool, pid, cid, refresh_token):+ """Shared REFRESH_TOKEN_AUTH core. Returns (auth_result_dict, error_response);+ exactly one is non-None. Used by InitiateAuth's REFRESH_TOKEN_AUTH branch and+ by GetTokensFromRefreshToken so both mint tokens identically."""+ user, err = _refresh_auth_user(pool, pid, cid, refresh_token)+ if err:+ return None, errresult = _build_auth_result(pid, cid, user, trigger_source="TokenGeneration_RefreshTokens")result.pop("RefreshToken", None) # AWS doesn't return a new refresh token herereturn result, Nonediff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex fbda1837..c511f1f6 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1,5 +1,6 @@"""Cognito tests — user pools, identity pools, OAuth2/OIDC flows, auth-code persistence."""+import asyncioimport base64import datetimeimport hashlib@@ -15,6 +16,7 @@ import urllib.requestimport uuid as _uuid_modimport zipfileimport zlib+from unittest.mock import Mockfrom urllib.parse import parse_qs as _parse_qsfrom urllib.parse import urlencode as _urlencodefrom urllib.parse import urlparse@@ -4899,14 +4901,16 @@ def test_cognito_pretoken_trigger_source_by_auth_flow(cognito_idp, lam):# InitiateAuth (USER_PASSWORD_AUTH) -> TokenGeneration_Authenticationauth = cognito_idp.initiate_auth(ClientId=client_id, AuthFlow="USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!"},+ AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},)["AuthenticationResult"]assert _decode_jwt_claims(auth["AccessToken"])["seen_trigger_source"] == "TokenGeneration_Authentication"# REFRESH_TOKEN_AUTH (InitiateAuth) -> TokenGeneration_RefreshTokensrefreshed = cognito_idp.initiate_auth(ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH",- AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"]},+ AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"],+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},)["AuthenticationResult"]assert _decode_jwt_claims(refreshed["AccessToken"])["seen_trigger_source"] == "TokenGeneration_RefreshTokens"@@ -4981,7 +4985,8 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):# here, so the trigger must see none, even though the caller passed one.auth = cognito_idp.initiate_auth(ClientId=client_id, AuthFlow="USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!"},+ AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},ClientMetadata={"orgId": "org-password"},)["AuthenticationResult"]assert _decode_jwt_claims(auth["AccessToken"])["seen_org_id"] == ""@@ -4989,7 +4994,8 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):# InitiateAuth(REFRESH_TOKEN_AUTH) — same exclusion.refreshed = cognito_idp.initiate_auth(ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH",- AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"]},+ AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"],+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},ClientMetadata={"orgId": "org-refresh"},)["AuthenticationResult"]assert _decode_jwt_claims(refreshed["AccessToken"])["seen_org_id"] == ""@@ -4997,7 +5003,8 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):# AdminInitiateAuth(ADMIN_USER_PASSWORD_AUTH) — same exclusion.admin_auth = cognito_idp.admin_initiate_auth(UserPoolId=pool_id, ClientId=client_id, AuthFlow="ADMIN_USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!"},+ AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},ClientMetadata={"orgId": "org-admin-password"},)["AuthenticationResult"]assert _decode_jwt_claims(admin_auth["AccessToken"])["seen_org_id"] == ""@@ -5005,7 +5012,8 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):# AdminInitiateAuth(REFRESH_TOKEN_AUTH) — same exclusion.admin_refreshed = cognito_idp.admin_initiate_auth(UserPoolId=pool_id, ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH",- AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"]},+ AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"],+ "SECRET_HASH": _cognito_secret_hash(client, "testuser")},ClientMetadata={"orgId": "org-admin-refresh"},)["AuthenticationResult"]assert _decode_jwt_claims(admin_refreshed["AccessToken"])["seen_org_id"] == ""@@ -5024,12 +5032,14 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):UserPoolId=pool_id, Username="newpwduser", Password="TempPass1!", Permanent=False)challenge = cognito_idp.initiate_auth(ClientId=client_id, AuthFlow="USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "newpwduser", "PASSWORD": "TempPass1!"},+ AuthParameters={"USERNAME": "newpwduser", "PASSWORD": "TempPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "newpwduser")},)assert challenge["ChallengeName"] == "NEW_PASSWORD_REQUIRED"respond_result = cognito_idp.respond_to_auth_challenge(ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED", Session=challenge["Session"],- ChallengeResponses={"USERNAME": "newpwduser", "NEW_PASSWORD": "FinalPass1!"},+ ChallengeResponses={"USERNAME": "newpwduser", "NEW_PASSWORD": "FinalPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "newpwduser")},ClientMetadata={"orgId": "org-new-password"},)["AuthenticationResult"]assert _decode_jwt_claims(respond_result["AccessToken"])["seen_org_id"] == "org-new-password"@@ -5040,13 +5050,15 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):UserPoolId=pool_id, Username="adminnewpwduser", Password="TempPass1!", Permanent=False)admin_challenge = cognito_idp.admin_initiate_auth(UserPoolId=pool_id, ClientId=client_id, AuthFlow="ADMIN_USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "adminnewpwduser", "PASSWORD": "TempPass1!"},+ AuthParameters={"USERNAME": "adminnewpwduser", "PASSWORD": "TempPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "adminnewpwduser")},)assert admin_challenge["ChallengeName"] == "NEW_PASSWORD_REQUIRED"admin_respond_result = cognito_idp.admin_respond_to_auth_challenge(UserPoolId=pool_id, ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED",Session=admin_challenge["Session"],- ChallengeResponses={"USERNAME": "adminnewpwduser", "NEW_PASSWORD": "FinalPass1!"},+ ChallengeResponses={"USERNAME": "adminnewpwduser", "NEW_PASSWORD": "FinalPass1!",+ "SECRET_HASH": _cognito_secret_hash(client, "adminnewpwduser")},ClientMetadata={"orgId": "org-admin-new-password"},)["AuthenticationResult"]assert _decode_jwt_claims(admin_respond_result["AccessToken"])["seen_org_id"] == "org-admin-new-password"@@ -9206,3 +9218,406 @@ def test_cognito_federation_access_token_pretoken_event_has_user_attributes(cognaccess = _decode_jwt_claims(tokens["access_token"])assert access["seen_sub"] == access["sub"]assert access["seen_groups"] == "admins"+++# App-client secrets are independent of the stack's IAM AUTH switch.++def _cognito_secret_hash(client, username):+ digest = hmac.new(+ client["ClientSecret"].encode(),+ (username + client["ClientId"]).encode(),+ hashlib.sha256,+ ).digest()+ return base64.b64encode(digest).decode()+++_SECRET_HASH_OPERATIONS = (+ "SignUp", "ConfirmSignUp", "ResendConfirmationCode", "ForgotPassword",+ "ConfirmForgotPassword", "InitiateAuth", "AdminInitiateAuth",+ "RespondToAuthChallenge", "AdminRespondToAuthChallenge",+)++[email protected]("action", _SECRET_HASH_OPERATIONS)[email protected]("hash_kind", [+ "missing", "wrong", "unicode-surrogate", "no-secret-client", "no-secret-with-hash",+])+def test_cognito_secret_hash_dispatch_prevents_side_effects(monkeypatch, action, hash_kind):+ """Refusal precedes user/token changes, code delivery, and Lambda callbacks."""+ from ministack.core.responses import AccountRegionScopedDict++ mod = _cognito_module()+ # These stores belong to the test process, never the running server.+ monkeypatch.setattr(mod, "_user_pools", AccountRegionScopedDict())+ monkeypatch.setattr(mod, "_refresh_tokens", {})+ monkeypatch.setattr(mod, "_challenge_sessions", {})+ monkeypatch.setattr(mod, "_revoked_tokens", set())+ pid = json.loads(mod._create_user_pool({"PoolName": "SecretHashDispatch"})[2])["UserPool"]["Id"]+ client = json.loads(mod._create_user_pool_client({+ "UserPoolId": pid, "ClientName": "app", "GenerateSecret": not hash_kind.startswith("no-secret"),+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH"],+ })[2])["UserPoolClient"]+ cid = client["ClientId"]+ mod._admin_create_user({+ "UserPoolId": pid, "Username": "existing", "TemporaryPassword": "Correct1!",+ "MessageAction": "SUPPRESS", "UserAttributes": [{"Name": "email", "Value": "[email protected]"}],+ })+ mod._admin_set_user_password({+ "UserPoolId": pid, "Username": "existing", "Password": "Correct1!", "Permanent": True,+ })+ payload = {"ClientId": cid}+ if action.endswith("InitiateAuth"):+ payload.update({+ "AuthFlow": "ADMIN_USER_PASSWORD_AUTH" if action.startswith("Admin") else "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "existing", "PASSWORD": "Correct1!"},+ })+ hash_container, hash_key = payload["AuthParameters"], "SECRET_HASH"+ elif action.endswith("RespondToAuthChallenge"):+ mod._user_pools[pid]["_users"]["existing"]["UserStatus"] = "FORCE_CHANGE_PASSWORD"+ payload.update({+ "ChallengeName": "NEW_PASSWORD_REQUIRED", "Session": "test-session",+ "ChallengeResponses": {"USERNAME": "existing", "NEW_PASSWORD": "Changed1!"},+ })+ hash_container, hash_key = payload["ChallengeResponses"], "SECRET_HASH"+ else:+ payload["Username"] = "new-user" if action == "SignUp" else "existing"+ if action in ("SignUp", "ConfirmForgotPassword"):+ payload["Password"] = "Changed1!"+ if action in ("ConfirmSignUp", "ConfirmForgotPassword"):+ payload["ConfirmationCode"] = "123456"+ hash_container, hash_key = payload, "SecretHash"+ if action.startswith("Admin"):+ payload["UserPoolId"] = pid+ if hash_kind == "wrong":+ # A valid base64 HMAC for a different username must still fail.+ hash_container[hash_key] = _cognito_secret_hash(client, "some-other-user")+ elif hash_kind == "unicode-surrogate":+ # json.loads accepts escaped lone surrogates on the raw API path.+ hash_container[hash_key] = "\ud800"+ elif hash_kind == "no-secret-with-hash":+ hash_container[hash_key] = "unneeded-secret-hash"+ callbacks = []+ for name in ("_send_verification_email", "_apply_presignup_trigger", "_apply_pretoken_trigger"):+ spy = Mock(wraps=getattr(mod, name))+ monkeypatch.setattr(mod, name, spy)+ callbacks.append(spy)+ def snapshot():+ return {+ key: value.to_dict() if hasattr(value, "to_dict") else value+ for key, value in mod.get_state().items()+ }++ before = snapshot()+ status, _, body = asyncio.run(mod._dispatch_idp(action, payload))+ if hash_kind == "no-secret-client" or (+ hash_kind == "no-secret-with-hash" and action.endswith("RespondToAuthChallenge")+ ):+ assert status == 200, json.loads(body)+ return+ assert snapshot() == before+ for spy in callbacks:+ spy.assert_not_called()+ assert status == 400+ error = json.loads(body)+ if hash_kind == "no-secret-with-hash":+ assert error["__type"].split("#")[-1] == "InvalidParameterException"+ assert error["message"] == f"App client {cid} is not configured for secret but secret hash was received"+ return+ assert error["__type"].split("#")[-1] == "NotAuthorizedException"+ assert error["message"] == (+ f"Client {cid} is configured with secret but SECRET_HASH was not received"+ if hash_kind == "missing" else f"Unable to verify secret hash for client {cid}"+ )+++def _secret_hash_pool(cognito_idp, **pool_options):+ pid = cognito_idp.create_user_pool(PoolName="SecretHashPool", **pool_options)["UserPool"]["Id"]+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="secret-app", GenerateSecret=True,+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH",+ "ALLOW_USER_SRP_AUTH", "ALLOW_CUSTOM_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]+ return pid, client+++def _secret_hash_user(cognito_idp, pid, username="canonical-user", permanent=True):+ user = cognito_idp.admin_create_user(+ UserPoolId=pid, Username=username, TemporaryPassword="Correct1!", MessageAction="SUPPRESS",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"},+ {"Name": "email_verified", "Value": "true"}],+ )["User"]+ if permanent:+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username=user["Username"], Password="Correct1!", Permanent=True,+ )+ return user+++def test_cognito_secret_hash_self_service(cognito_idp):+ pid, client = _secret_hash_pool(cognito_idp)+ params = {"ClientId": client["ClientId"], "Username": "signup-user",+ "SecretHash": _cognito_secret_hash(client, "signup-user")}+ signup = cognito_idp.sign_up(+ **params, Password="Correct1!", UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ assert signup["UserConfirmed"] is False+ assert "CodeDeliveryDetails" in cognito_idp.resend_confirmation_code(**params)+ cognito_idp.confirm_sign_up(**params, ConfirmationCode="123456")+ assert cognito_idp.admin_get_user(UserPoolId=pid, Username="signup-user")["UserStatus"] == "CONFIRMED"+ assert "CodeDeliveryDetails" in cognito_idp.forgot_password(**params)+ cognito_idp.confirm_forgot_password(**params, ConfirmationCode="654321", Password="Changed1!")+ auth = cognito_idp.initiate_auth(+ ClientId=client["ClientId"], AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "signup-user", "PASSWORD": "Changed1!",+ "SECRET_HASH": params["SecretHash"]},+ )+ assert cognito_idp.get_user(AccessToken=auth["AuthenticationResult"]["AccessToken"])["Username"] == "signup-user"++[email protected]("admin", [False, True])[email protected]("login", ["canonical-user", "[email protected]"])+def test_cognito_secret_hash_password_uses_submitted_alias(cognito_idp, admin, login):+ pid, client = _secret_hash_pool(cognito_idp, AliasAttributes=["email"])+ _secret_hash_user(cognito_idp, pid)+ kwargs = {+ "ClientId": client["ClientId"],+ "AuthFlow": "ADMIN_USER_PASSWORD_AUTH" if admin else "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": login, "PASSWORD": "Correct1!",+ "SECRET_HASH": _cognito_secret_hash(client, login)},+ }+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ if admin:+ kwargs["UserPoolId"] = pid+ result = initiate(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+ if login != "canonical-user":+ kwargs["AuthParameters"]["SECRET_HASH"] = _cognito_secret_hash(client, "canonical-user")+ with pytest.raises(ClientError) as exc:+ initiate(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ assert exc.value.response["Error"]["Message"] == f"Unable to verify secret hash for client {client['ClientId']}"++[email protected]("admin", [False, True])+def test_cognito_secret_hash_new_password_challenge(cognito_idp, admin):+ pid, client = _secret_hash_pool(cognito_idp)+ _secret_hash_user(cognito_idp, pid, permanent=False)+ cid = client["ClientId"]+ digest = _cognito_secret_hash(client, "canonical-user")+ kwargs = {"ClientId": cid,+ "AuthFlow": "ADMIN_USER_PASSWORD_AUTH" if admin else "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "canonical-user", "PASSWORD": "Correct1!", "SECRET_HASH": digest}}+ if admin:+ kwargs["UserPoolId"] = pid+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ challenge = initiate(**kwargs)+ assert challenge["ChallengeName"] == "NEW_PASSWORD_REQUIRED"+ respond = cognito_idp.admin_respond_to_auth_challenge if admin else cognito_idp.respond_to_auth_challenge+ kwargs = {"ClientId": cid, "ChallengeName": "NEW_PASSWORD_REQUIRED", "Session": challenge["Session"],+ "ChallengeResponses": {"USERNAME": "canonical-user", "NEW_PASSWORD": "Changed1!"}}+ if admin:+ kwargs["UserPoolId"] = pid+ for invalid_hash in (None, _cognito_secret_hash(client, "someone-else")):+ if invalid_hash:+ kwargs["ChallengeResponses"]["SECRET_HASH"] = invalid_hash+ with pytest.raises(ClientError) as exc:+ respond(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ assert cognito_idp.admin_get_user(UserPoolId=pid, Username="canonical-user")["UserStatus"] == "FORCE_CHANGE_PASSWORD"+ kwargs["ChallengeResponses"]["SECRET_HASH"] = digest+ result = respond(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"++[email protected]("admin", [False, True])[email protected]("username_attributes", [False, True], ids=["username-sign-in", "email-sign-in"])[email protected]("flow", ["REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"])+def test_cognito_secret_hash_refresh_uses_token_owner(cognito_idp, admin, username_attributes, flow):+ options = {"UsernameAttributes": ["email"]} if username_attributes else {"AliasAttributes": ["email"]}+ pid, client = _secret_hash_pool(cognito_idp, **options)+ user = _secret_hash_user(cognito_idp, pid, username="[email protected]" if username_attributes else "canonical-user")+ cid = client["ClientId"]+ tokens = cognito_idp.initiate_auth(+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "[email protected]", "PASSWORD": "Correct1!",+ "SECRET_HASH": _cognito_secret_hash(client, "[email protected]")},+ )["AuthenticationResult"]+ attrs = {a["Name"]: a["Value"] for a in user["Attributes"]}+ hash_username = attrs["sub"] if username_attributes else user["Username"]+ kwargs = {"ClientId": cid, "AuthFlow": flow,+ "AuthParameters": {"REFRESH_TOKEN": tokens["RefreshToken"]}}+ if admin:+ kwargs["UserPoolId"] = pid+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ for invalid_hash in (None, _cognito_secret_hash(client, "[email protected]")):+ if invalid_hash:+ kwargs["AuthParameters"]["SECRET_HASH"] = invalid_hash+ with pytest.raises(ClientError) as exc:+ initiate(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ kwargs["AuthParameters"]["SECRET_HASH"] = _cognito_secret_hash(client, hash_username)+ # An extraneous USERNAME cannot override the owner of the refresh token.+ kwargs["AuthParameters"]["USERNAME"] = "unrelated-user"+ refreshed = initiate(**kwargs)["AuthenticationResult"]+ assert "RefreshToken" not in refreshed+ assert cognito_idp.get_user(AccessToken=refreshed["AccessToken"])["Username"] == user["Username"]++[email protected]("admin", [False, True])+def test_cognito_secret_hash_srp_proof(cognito_idp, admin):+ pid, client = _secret_hash_pool(cognito_idp, AliasAttributes=["email"])+ _secret_hash_user(cognito_idp, pid)+ cid = client["ClientId"]+ a, big_a = _srp_a()+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ kwargs = {"ClientId": cid, "AuthFlow": "USER_SRP_AUTH",+ "AuthParameters": {"USERNAME": "[email protected]", "SRP_A": format(big_a, "x"),+ "SECRET_HASH": _cognito_secret_hash(client, "[email protected]")}}+ if admin:+ kwargs["UserPoolId"] = pid+ challenge = initiate(**kwargs)+ assert challenge["ChallengeName"] == "PASSWORD_VERIFIER"+ responses = _srp_responses(pid, challenge["ChallengeParameters"], "Correct1!", a, big_a)+ assert responses["USERNAME"] == "canonical-user"+ kwargs = {"ClientId": cid, "ChallengeName": "PASSWORD_VERIFIER", "ChallengeResponses": responses}+ if admin:+ kwargs["UserPoolId"] = pid+ respond = cognito_idp.admin_respond_to_auth_challenge if admin else cognito_idp.respond_to_auth_challenge+ with pytest.raises(ClientError) as exc:+ respond(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ responses["SECRET_HASH"] = _cognito_secret_hash(client, "canonical-user")+ result = respond(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"++[email protected]("admin", [False, True])+def test_cognito_secret_hash_custom_challenge(cognito_idp, lam, admin):+ pid, client = _secret_hash_pool(cognito_idp)+ _secret_hash_user(cognito_idp, pid)+ suffix = _uuid_mod.uuid4().hex[:8]+ define_arn = _create_lambda(lam, f"secret-define-{suffix}", (+ "def handler(event, ctx):\n"+ " session = event['request']['session']\n"+ " if session and session[-1].get('challengeResult'):\n"+ " event['response']['issueTokens'] = True\n"+ " else:\n"+ " event['response']['challengeName'] = 'CUSTOM_CHALLENGE'\n"+ " return event\n"+ ))+ verify_arn = _create_lambda(lam, f"secret-verify-{suffix}", (+ "def handler(event, ctx):\n"+ " event['response']['answerCorrect'] = event['request']['challengeAnswer'] == 'correct-answer'\n"+ " return event\n"+ ))+ cognito_idp.update_user_pool(UserPoolId=pid, LambdaConfig={+ "DefineAuthChallenge": define_arn, "VerifyAuthChallengeResponse": verify_arn,+ })+ cid = client["ClientId"]+ digest = _cognito_secret_hash(client, "canonical-user")+ kwargs = {"ClientId": cid, "AuthFlow": "CUSTOM_AUTH", "AuthParameters": {"USERNAME": "canonical-user"}}+ if admin:+ kwargs["UserPoolId"] = pid+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ for invalid_hash in (None, _cognito_secret_hash(client, "someone-else")):+ if invalid_hash:+ kwargs["AuthParameters"]["SECRET_HASH"] = invalid_hash+ with pytest.raises(ClientError) as exc:+ initiate(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ kwargs["AuthParameters"]["SECRET_HASH"] = digest+ challenge = initiate(**kwargs)+ assert challenge["ChallengeName"] == "CUSTOM_CHALLENGE"+ kwargs = {"ClientId": cid, "ChallengeName": "CUSTOM_CHALLENGE", "Session": challenge["Session"],+ "ChallengeResponses": {"USERNAME": "canonical-user", "ANSWER": "correct-answer"}}+ if admin:+ kwargs["UserPoolId"] = pid+ respond = cognito_idp.admin_respond_to_auth_challenge if admin else cognito_idp.respond_to_auth_challenge+ public_client_id = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="public-custom-app", GenerateSecret=False,+ ExplicitAuthFlows=["ALLOW_CUSTOM_AUTH"],+ )["UserPoolClient"]["ClientId"]+ mismatches = [(public_client_id, None), (public_client_id, "public-client-dummy-hash")]+ if admin:+ mismatches.append(("unknownclient123456789", None))+ for other_client_id, other_hash in mismatches:+ other_responses = dict(kwargs["ChallengeResponses"])+ if other_hash:+ other_responses["SECRET_HASH"] = other_hash+ other_request = {**kwargs, "ClientId": other_client_id, "ChallengeResponses": other_responses}+ with pytest.raises(ClientError) as exc:+ respond(**other_request)+ expected_error = (+ {"Code": "ResourceNotFoundException", "Message": f"Client {other_client_id} not found."}+ if other_client_id != public_client_id else+ {"Code": "NotAuthorizedException", "Message": "Invalid session for the user."}+ )+ assert exc.value.response["Error"] == expected_error+ for invalid_hash in (None, _cognito_secret_hash(client, "someone-else")):+ if invalid_hash:+ kwargs["ChallengeResponses"]["SECRET_HASH"] = invalid_hash+ with pytest.raises(ClientError) as exc:+ respond(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ kwargs["ChallengeResponses"]["SECRET_HASH"] = digest+ result = respond(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+++def test_cognito_secret_hash_admin_sms_challenge(cognito_idp):+ """Existing admin SMS handling must also require the app-client proof."""+ pid, client = _secret_hash_pool(cognito_idp)+ _secret_hash_user(cognito_idp, pid)+ responses = {"USERNAME": "canonical-user", "SMS_MFA_CODE": "123456"}+ kwargs = {"UserPoolId": pid, "ClientId": client["ClientId"], "ChallengeName": "SMS_MFA",+ "ChallengeResponses": responses, "Session": "local-sms-session-long-enough"}+ for invalid_hash in (None, _cognito_secret_hash(client, "someone-else")):+ if invalid_hash:+ responses["SECRET_HASH"] = invalid_hash+ with pytest.raises(ClientError) as exc:+ cognito_idp.admin_respond_to_auth_challenge(**kwargs)+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+ responses["SECRET_HASH"] = _cognito_secret_hash(client, "canonical-user")+ result = cognito_idp.admin_respond_to_auth_challenge(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"++[email protected]("admin", [False, True])[email protected]("include_hash", [False, True], ids=["missing-hash", "wrong-hash"])+def test_cognito_secret_hash_invalid_refresh_preserves_token_error(cognito_idp, admin, include_hash):+ """Malformed refresh tokens retain their error before app-client verification."""+ pid, client = _secret_hash_pool(cognito_idp)+ _secret_hash_user(cognito_idp, pid)+ kwargs = {"ClientId": client["ClientId"], "AuthFlow": "REFRESH_TOKEN_AUTH",+ "AuthParameters": {"REFRESH_TOKEN": "not-a-refresh-token"}}+ if include_hash:+ kwargs["AuthParameters"]["SECRET_HASH"] = _cognito_secret_hash(client, "someone-else")+ if admin:+ kwargs["UserPoolId"] = pid+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ with pytest.raises(ClientError) as exc:+ initiate(**kwargs)+ assert exc.value.response["Error"] == {+ "Code": "NotAuthorizedException", "Message": "Invalid Refresh Token",+ }++[email protected]("admin", [False, True])+def test_cognito_secret_hash_no_secret_refresh_ignores_supplied_hash(cognito_idp, admin):+ pid = cognito_idp.create_user_pool(PoolName="PublicRefreshHashPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="public-refresh-app", GenerateSecret=False,+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ _secret_hash_user(cognito_idp, pid)+ tokens = cognito_idp.initiate_auth(+ ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "canonical-user", "PASSWORD": "Correct1!"},+ )["AuthenticationResult"]+ kwargs = {"ClientId": cid, "AuthFlow": "REFRESH_TOKEN_AUTH",+ "AuthParameters": {"REFRESH_TOKEN": tokens["RefreshToken"], "SECRET_HASH": "ignored-wrong-hash"}}+ if admin:+ kwargs["UserPoolId"] = pid+ initiate = cognito_idp.admin_initiate_auth if admin else cognito_idp.initiate_auth+ result = initiate(**kwargs)["AuthenticationResult"]+ assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"