Skip to content

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

fix(cognito): send the pre token generation event fields AWS sends (#2350)

iot-rocketc5b9e1620b83
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b44057a7..3af50913 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 — pre token generation event fields** — the event always said `"version": "1"`, a `NEW_PASSWORD_REQUIRED` answer was `TokenGeneration_Authentication` and a `client_credentials` grant had an empty `userName`; the event now carries `"1"`, `"2"` or `"3"` for `V1_0`, `V2_0` and `V3_0`, `TokenGeneration_NewPasswordChallenge` and `ClientCredentials`, as AWS sends them. Contributed by @iot-rocket.
- **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.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 8a19fbf8..ddb7dd6f 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1081,11 +1081,12 @@ def _build_pretoken_event(pool_id: str, client_id: str, username: str,
)
return {
- "version": "1",
+ # The trigger's major version: "1", "2" or "3"
+ "version": version.split("_")[0].lstrip("V"),
"triggerSource": trigger_source,
"region": _pool_region(pool_id),
"userPoolId": pool_id,
- "userName": username or "",
+ "userName": "ClientCredentials" if trigger_source == "TokenGeneration_ClientCredentials" else username or "",
"callerContext": {
"awsSdkVersion": "ministack",
"clientId": client_id or "",
@@ -4581,7 +4582,8 @@ def _admin_respond_to_auth_challenge(data):
user["UserLastModifiedDate"] = _now_epoch()
_record_auth_event(pool, user, data, "PasswordChange", "Pass")
return json_response({"AuthenticationResult": _build_auth_result(
- pid, cid, user, client_metadata=client_metadata)})
+ pid, cid, user, trigger_source="TokenGeneration_NewPasswordChallenge",
+ client_metadata=client_metadata)})
if challenge_name == "SMS_MFA":
username = responses.get("USERNAME")
@@ -4905,7 +4907,8 @@ def _respond_to_auth_challenge(data):
user["UserLastModifiedDate"] = _now_epoch()
_record_auth_event(pool, user, data, "PasswordChange", "Pass")
return json_response({"AuthenticationResult": _build_auth_result(
- pid, cid, user, client_metadata=client_metadata)})
+ pid, cid, user, trigger_source="TokenGeneration_NewPasswordChallenge",
+ client_metadata=client_metadata)})
if challenge_name in ("SOFTWARE_TOKEN_MFA", "MFA_SETUP"):
username = responses.get("USERNAME")
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 1b9f39e9..a15f3bb1 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -6549,6 +6549,67 @@ def test_cognito_pretoken_lambda_failure_fail_open(cognito_idp, lam):
assert access["client_id"] == cid # token still issued
[email protected]("version", ["V1_0", "V2_0", "V3_0"])
+def test_cognito_pretoken_event_names_its_version(cognito_idp, lam, version):
+ """The event carries the trigger's major version, the new-password source and the M2M user name."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " seen = {'ev_version': event['version'], 'ev_source': event['triggerSource'],\n"
+ " 'ev_user': event['userName']}\n"
+ " if 'scopes' in event['request']:\n"
+ " event['response']['claimsAndScopeOverrideDetails'] = {\n"
+ " 'idTokenGeneration': {'claimsToAddOrOverride': seen},\n"
+ " 'accessTokenGeneration': {'claimsToAddOrOverride': seen}}\n"
+ " else:\n"
+ " event['response']['claimsOverrideDetails'] = {'claimsToAddOrOverride': seen}\n"
+ " return event\n"
+ )
+ fn_name = f"ministack-pretoken-event-version-{version}"
+ lam.create_function(
+ FunctionName=fn_name, Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},
+ )
+ fn_arn = lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]
+ pool_id, client = _setup_pool_with_user(
+ cognito_idp, generate_secret=False, explicit_auth_flows=["ALLOW_ADMIN_USER_PASSWORD_AUTH"])
+ config = ({"PreTokenGeneration": fn_arn} if version == "V1_0"
+ else {"PreTokenGenerationConfig": {"LambdaArn": fn_arn, "LambdaVersion": version}})
+ cognito_idp.update_user_pool(UserPoolId=pool_id, LambdaConfig=config)
+
+ def admin_sign_in(username, password):
+ return cognito_idp.admin_initiate_auth(
+ UserPoolId=pool_id, ClientId=client["ClientId"], AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": username, "PASSWORD": password})
+
+ signed_in = _decode_jwt_claims(admin_sign_in("testuser", "TestPass1!")["AuthenticationResult"]["IdToken"])
+ assert (signed_in["ev_version"], signed_in["ev_source"]) == (version[1], "TokenGeneration_Authentication")
+
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="newcomer", TemporaryPassword="TempPass1!",
+ MessageAction="SUPPRESS")
+ challenge = admin_sign_in("newcomer", "TempPass1!")
+ answered = cognito_idp.admin_respond_to_auth_challenge(
+ UserPoolId=pool_id, ClientId=client["ClientId"], ChallengeName="NEW_PASSWORD_REQUIRED",
+ Session=challenge["Session"], ChallengeResponses={"USERNAME": "newcomer", "NEW_PASSWORD": "FinalPass1!"},
+ )["AuthenticationResult"]
+ changed = _decode_jwt_claims(answered["IdToken"])
+ assert (changed["ev_source"], changed["ev_user"]) == ("TokenGeneration_NewPasswordChallenge", "newcomer")
+
+ if version == "V3_0":
+ cognito_idp.create_resource_server(UserPoolId=pool_id, Identifier="api", Name="api",
+ Scopes=[{"ScopeName": "read", "ScopeDescription": "read"}])
+ machine = cognito_idp.create_user_pool_client(
+ UserPoolId=pool_id, ClientName="m2m", GenerateSecret=True, AllowedOAuthFlows=["client_credentials"],
+ AllowedOAuthScopes=["api/read"], AllowedOAuthFlowsUserPoolClient=True)["UserPoolClient"]
+ status, _, body = _post_form(f"{ENDPOINT}/oauth2/token", {
+ "grant_type": "client_credentials", "client_id": machine["ClientId"],
+ "client_secret": machine["ClientSecret"]})
+ assert status == 200, body
+ m2m = _decode_jwt_claims(json.loads(body)["access_token"])
+ assert (m2m["ev_version"], m2m["ev_user"]) == ("3", "ClientCredentials")
+
+
def test_cognito_pretoken_trigger_source_by_auth_flow(cognito_idp, lam):
"""PreTokenGeneration's triggerSource should differ by call path, matching
real AWS: InitiateAuth(USER_PASSWORD_AUTH) -> TokenGeneration_Authentication,