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): enable CUSTOM_AUTH by default; enforce ExplicitAuthFlows and confirmation codes under AUTH=true (#2150)
iot-rocket404621b80554
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac302dcc..3c22be07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Cognito — confirmation codes are checked under `AUTH=true`** — `ConfirmSignUp` and `ConfirmForgotPassword` accepted any code, and `ConfirmForgotPassword` changed the password even when no reset was requested; with `AUTH=true` they take only the issued code (`123456` for sign-up and `654321` for a password reset, as before), answer a wrong one with `CodeMismatchException` and a code that was never issued with `ExpiredCodeException`, and `ConfirmSignUp` refuses a user who is not `UNCONFIRMED` with `NotAuthorizedException`, as AWS does. Contributed by @iot-rocket.+- **Cognito — `ExplicitAuthFlows` is enforced for the password flows under `AUTH=true`** — with `AUTH=true` a client that lists its auth flows now refuses `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` unless the list enables them (the legacy `USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` names included), with the `InvalidParameterException` AWS returns. Contributed by @iot-rocket.+- **Cognito — `CUSTOM_AUTH` on clients without `ALLOW_` flows** — a client created without `ExplicitAuthFlows`, or with only the legacy names, refused `CUSTOM_AUTH`; it is now enabled, as on AWS, and a client whose `ALLOW_` list leaves it out answers `CUSTOM_AUTH is not enabled for the client.` as AWS does. Contributed by @iot-rocket.+- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.+- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.+- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 82251d88..7c2e9244 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2400,11 +2400,40 @@ def _validate_client_secret_hash(action: str, data: dict):)+# AuthFlow -> (the ExplicitAuthFlows entries that enable it, the refusal without one)+_PASSWORD_AUTH_FLOWS = {+ "USER_PASSWORD_AUTH": ({"ALLOW_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH"},+ "USER_PASSWORD_AUTH flow not enabled for this client"),+ "ADMIN_USER_PASSWORD_AUTH": ({"ALLOW_ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"},+ "Auth flow not enabled for this client"),+ "ADMIN_NO_SRP_AUTH": ({"ALLOW_ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"},+ "Auth flow not enabled for this client"),+}+++def _auth_flow_error(action: str, data: dict):+ """InvalidParameterException for a password flow the app client's ExplicitAuthFlows leaves out, or None."""+ flow = data.get("AuthFlow")+ if (not isinstance(flow, str) or not action.endswith("InitiateAuth")+ or action.startswith("Admin") != flow.startswith("ADMIN_")):+ return None+ enabling = _PASSWORD_AUTH_FLOWS.get(flow)+ if not enabling:+ return None+ cid = data.get("ClientId")+ pool = _user_pools.get(data.get("UserPoolId")) if action.startswith("Admin") else _pool_for_client(cid)[0]+ flows = set(((pool or {}).get("_clients", {}).get(cid) or {}).get("ExplicitAuthFlows") or [])+ if flows and not flows & enabling[0]:+ return error_response_json("InvalidParameterException", enabling[1], 400)+ return None++def _run_idp_handler(handler, action: str, data: dict):if action in _UNSIGNED_IDP_ACTIONS:_pin_unsigned_idp_scope(data)from ministack.app import AUTH- error = (_validate_client_secret_hash(action, data) or _access_token_error(data)) if AUTH else None+ error = (_validate_client_secret_hash(action, data) or _auth_flow_error(action, data)+ or _access_token_error(data) or _confirmation_code_error(action, data)) if AUTH else Noneif error:return errorreturn handler(data)@@ -4013,9 +4042,10 @@ def _admin_initiate_auth(data):if auth_flow == "CUSTOM_AUTH":# Validate ExplicitAuthFlowsclient = pool["_clients"].get(cid, {})- if "ALLOW_CUSTOM_AUTH" not in client.get("ExplicitAuthFlows", []):+ flows = client.get("ExplicitAuthFlows", [])+ if any(f.startswith("ALLOW_") for f in flows) and "ALLOW_CUSTOM_AUTH" not in flows:return error_response_json("InvalidParameterException",- "CUSTOM_AUTH flow not allowed for this client.", 400)+ "CUSTOM_AUTH is not enabled for the client.", 400)# Get usernameusername = auth_params.get("USERNAME")@@ -4321,9 +4351,10 @@ def _initiate_auth(data):if auth_flow == "CUSTOM_AUTH":# Validate ExplicitAuthFlowsclient = pool["_clients"].get(cid, {})- if "ALLOW_CUSTOM_AUTH" not in client.get("ExplicitAuthFlows", []):+ flows = client.get("ExplicitAuthFlows", [])+ if any(f.startswith("ALLOW_") for f in flows) and "ALLOW_CUSTOM_AUTH" not in flows:return error_response_json("InvalidParameterException",- "CUSTOM_AUTH flow not allowed for this client.", 400)+ "CUSTOM_AUTH is not enabled for the client.", 400)# Get usernameusername = auth_params.get("USERNAME")@@ -4639,6 +4670,33 @@ def _sign_up(data):return json_response(resp)+def _code_error(issued, code):+ """ExpiredCodeException when no code was issued, CodeMismatchException for another code, else None."""+ if not issued:+ return error_response_json(+ "ExpiredCodeException", "Invalid code provided, please request a code again.", 400)+ if code != issued:+ return error_response_json(+ "CodeMismatchException", "Invalid verification code provided, please try again.", 400)+ return None+++def _confirmation_code_error(action: str, data: dict):+ """The error for a ConfirmSignUp or ConfirmForgotPassword the issued code does not allow, or None."""+ if action not in ("ConfirmSignUp", "ConfirmForgotPassword"):+ return None+ pool, _pid = _pool_for_client(data.get("ClientId"))+ user = _resolve_user(pool, data.get("Username"))[0] if pool else None+ if not user:+ return None+ if action == "ConfirmForgotPassword":+ return _code_error(user.get("_reset_code"), data.get("ConfirmationCode"))+ if user.get("UserStatus") != "UNCONFIRMED":+ return error_response_json(+ "NotAuthorizedException", f"User cannot be confirmed. Current status is {user.get('UserStatus')}", 400)+ return _code_error(user.get("_confirmation_code"), data.get("ConfirmationCode"))++def _confirm_sign_up(data):cid = data.get("ClientId")username = data.get("Username")@@ -4656,7 +4714,8 @@ def _confirm_sign_up(data):if err:return err- # Accept any code in emulation+ # Codes are checked under AUTH=true (_confirmation_code_error).+ user.pop("_confirmation_code", None)user["UserStatus"] = "CONFIRMED"user["UserLastModifiedDate"] = _now_epoch()return json_response({})@@ -4713,10 +4772,11 @@ def _confirm_forgot_password(data):)return _err- # Accept any confirmation code in emulation (real AWS validates against issued code)+ # Codes are checked under AUTH=true (_confirmation_code_error).pw_err = _validate_password(pool, new_password)if pw_err:return pw_err+ user.pop("_reset_code", None)user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"user["UserLastModifiedDate"] = _now_epoch()diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 00a22583..f76db8f0 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -459,6 +459,50 @@ def test_cognito_forgot_password_and_confirm(cognito_idp):)assert "AuthenticationResult" in auth++def test_cognito_confirmation_codes_checked_under_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=True)+ pid, cid, _ = _password_client_with_users(call, "alice", "bob")+ mismatch = ("CodeMismatchException", "Invalid verification code provided, please try again.")+ expired = ("ExpiredCodeException", "Invalid code provided, please request a code again.")++ call("SignUp", ClientId=cid, Username="carol", Password="Passw0rd!")+ assert call("ConfirmSignUp", ClientId=cid, Username="carol", ConfirmationCode="000000") == mismatch+ assert call("AdminGetUser", UserPoolId=pid, Username="carol")["UserStatus"] == "UNCONFIRMED"+ assert call("ConfirmSignUp", ClientId=cid, Username="carol", ConfirmationCode="123456") == {}+ call("AdminCreateUser", UserPoolId=pid, Username="dave", TemporaryPassword="Passw0rd!", MessageAction="SUPPRESS")+ for name, status in (("carol", "CONFIRMED"), ("alice", "CONFIRMED"), ("dave", "FORCE_CHANGE_PASSWORD")):+ assert call("ConfirmSignUp", ClientId=cid, Username=name, ConfirmationCode="123456") == (+ "NotAuthorizedException", f"User cannot be confirmed. Current status is {status}")++ def reset(name, code, password="Passw0rd!2"):+ return call("ConfirmForgotPassword", ClientId=cid, Username=name, ConfirmationCode=code, Password=password)++ def sign_in(name, password):+ return call("InitiateAuth", ClientId=cid, AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": name, "PASSWORD": password})++ assert reset("alice", "654321") == expired+ assert "AuthenticationResult" in sign_in("alice", "Passw0rd!")+ call("ForgotPassword", ClientId=cid, Username="bob")+ assert reset("bob", "000000") == mismatch+ assert reset("bob", "000000", password="weak") == mismatch+ assert "AuthenticationResult" in sign_in("bob", "Passw0rd!")+ assert reset("bob", "654321") == {}+ assert "AuthenticationResult" in sign_in("bob", "Passw0rd!2")+ assert reset("bob", "654321") == expired+++def test_cognito_confirmation_codes_not_checked_without_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=False)+ pid, cid, _ = _password_client_with_users(call, "alice")+ call("SignUp", ClientId=cid, Username="carol", Password="Passw0rd!")+ assert call("ConfirmSignUp", ClientId=cid, Username="carol", ConfirmationCode="000000") == {}+ assert call("AdminGetUser", UserPoolId=pid, Username="carol")["UserStatus"] == "CONFIRMED"+ assert call("ConfirmForgotPassword", ClientId=cid, Username="alice", ConfirmationCode="000000",+ Password="Passw0rd!2") == {}++def test_cognito_admin_update_user_attributes(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="UpdateAttrPool")["UserPool"]["Id"]cognito_idp.admin_create_user(@@ -6949,6 +6993,67 @@ def test_custom_auth_client_missing_explicit_flow(cognito_idp):AuthParameters={"USERNAME": "[email protected]"},)assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+ assert exc.value.response["Error"]["Message"] == "CUSTOM_AUTH is not enabled for the client."++[email protected]("flows", [None, ["ADMIN_NO_SRP_AUTH"], ["USER_PASSWORD_AUTH"]])+def test_custom_auth_enabled_without_allow_entries(cognito_idp, flows):+ """A client without ALLOW_ entries in ExplicitAuthFlows keeps CUSTOM_AUTH enabled."""+ pid = cognito_idp.create_user_pool(PoolName="CustomAuthDefaultPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="app", **({"ExplicitAuthFlows": flows} if flows else {}),+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="alice", MessageAction="SUPPRESS")+ answer = cognito_idp.initiate_auth(ClientId=cid, AuthFlow="CUSTOM_AUTH", AuthParameters={"USERNAME": "alice"})+ assert answer["ResponseMetadata"]["HTTPStatusCode"] == 200+++_FLOW_REFUSALS = {+ "USER_PASSWORD_AUTH": "USER_PASSWORD_AUTH flow not enabled for this client",+ "ADMIN_USER_PASSWORD_AUTH": "Auth flow not enabled for this client",+ "ADMIN_NO_SRP_AUTH": "Auth flow not enabled for this client",+ "CUSTOM_AUTH": "CUSTOM_AUTH is not enabled for the client.",+}+++def _sign_in_with_each_flow(call, flows):+ """{auth flow: the InitiateAuth / AdminInitiateAuth answer} on a new client with these ExplicitAuthFlows."""+ pid = call("CreateUserPool", PoolName="AuthFlowsPool")["UserPool"]["Id"]+ call("AdminCreateUser", UserPoolId=pid, Username="alice", MessageAction="SUPPRESS")+ call("AdminSetUserPassword", UserPoolId=pid, Username="alice", Password="Passw0rd!", Permanent=True)+ cid = call("CreateUserPoolClient", UserPoolId=pid, ClientName="app",+ ExplicitAuthFlows=flows)["UserPoolClient"]["ClientId"]+ password = {"USERNAME": "alice", "PASSWORD": "Passw0rd!"}+ return {flow: call("AdminInitiateAuth" if flow.startswith("ADMIN") else "InitiateAuth",+ UserPoolId=pid, ClientId=cid, AuthFlow=flow,+ AuthParameters={"USERNAME": "alice"} if flow == "CUSTOM_AUTH" else password)+ for flow in _FLOW_REFUSALS}++[email protected]("flows, enabled", [+ (["ALLOW_REFRESH_TOKEN_AUTH"], set()),+ (["ALLOW_USER_PASSWORD_AUTH"], {"USER_PASSWORD_AUTH"}),+ (["ALLOW_ADMIN_USER_PASSWORD_AUTH"], {"ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"}),+ (["ALLOW_CUSTOM_AUTH"], {"CUSTOM_AUTH"}),+ (["ADMIN_NO_SRP_AUTH"], {"ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH", "CUSTOM_AUTH"}),+ (["USER_PASSWORD_AUTH"], {"USER_PASSWORD_AUTH", "CUSTOM_AUTH"}),+ ([], set(_FLOW_REFUSALS)),+])+def test_cognito_explicit_auth_flows_enable_each_flow_under_auth(monkeypatch, flows, enabled):+ _, call = _idp_in_process(monkeypatch, auth=True)+ for flow, answer in _sign_in_with_each_flow(call, flows).items():+ if flow in enabled:+ assert not isinstance(answer, tuple), (flow, answer)+ else:+ assert answer == ("InvalidParameterException", _FLOW_REFUSALS[flow]), flow+++def test_cognito_password_flows_not_checked_without_auth(monkeypatch):+ _, call = _idp_in_process(monkeypatch, auth=False)+ answers = _sign_in_with_each_flow(call, ["ALLOW_REFRESH_TOKEN_AUTH"])+ assert answers.pop("CUSTOM_AUTH") == ("InvalidParameterException", _FLOW_REFUSALS["CUSTOM_AUTH"])+ for answer in answers.values():+ assert "AuthenticationResult" in answer# ── Test 6: RespondToAuthChallenge — missing Session ─────────────────────────@@ -10135,7 +10240,13 @@ def test_cognito_secret_hash_dispatch_prevents_side_effects(monkeypatch, action,if action in ("SignUp", "ConfirmForgotPassword"):payload["Password"] = "Changed1!"if action in ("ConfirmSignUp", "ConfirmForgotPassword"):- payload["ConfirmationCode"] = "123456"+ payload["ConfirmationCode"] = "123456" if action == "ConfirmSignUp" else "654321"+ # A user the code was issued to, so only the secret decides.+ existing = mod._user_pools[pid]["_users"]["existing"]+ if action == "ConfirmSignUp":+ existing.update(UserStatus="UNCONFIRMED", _confirmation_code="123456")+ else:+ existing["_reset_code"] = "654321"hash_container, hash_key = payload, "SecretHash"if action.startswith("Admin"):payload["UserPoolId"] = pid