Skip to content

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

fix(cognito): run the client_credentials pre token trigger for V3_0 only (#2399)

iot-rocket24f44a05b87b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f64d21c0..f212a89e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.
### Fixed
+- **Cognito — pre token generation for `client_credentials`** — a `client_credentials` grant invoked a `V2_0` pre token generation trigger; it now invokes the trigger only when `LambdaVersion` is `V3_0`, as AWS documents and does. Contributed by @iot-rocket.
- **Cognito — `client_credentials` needs the flow** — the `/oauth2/token` endpoint gave a `client_credentials` token to an app client without `client_credentials` in `AllowedOAuthFlows`; such a client now gets `invalid_grant`, or `invalid_scope` first when a requested scope is unknown or none is left, as on AWS. Contributed by @iot-rocket.
- **S3 — ACLs on buckets with `BucketOwnerEnforced`** — on a bucket with ACLs disabled, the default for new buckets, ACL writes answered 200 and a stored bucket grant still opened the bucket to other accounts and anonymous callers; `PutBucketAcl` and `PutObjectAcl` now answer 400 `AccessControlListNotSupported`, `PutObject`, `CopyObject`, `CreateMultipartUpload` and POST uploads refuse any ACL but an owner-only one with the same error, `CreateBucket` and a switch to `BucketOwnerEnforced` refuse an ACL that grants others with 400 `InvalidBucketAclWithObjectOwnership`, and ACLs stored earlier grant nothing and read as the owner's until ACLs are enabled again. Contributed by @iot-rocket.
- **S3 — `RestrictPublicBuckets` and policies that are not public** — the setting dropped the bucket policy for every caller from another account, so a policy that names one account stopped granting it; it now drops the policy only when the policy is public, as the S3 user guide describes. Contributed by @iot-rocket.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 676919eb..6c25924b 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -1049,6 +1049,9 @@ def _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,
# V1_0 only fires for id tokens.
if not use_v2 and token_type != "id":
return claims
+ # Client credentials grants only fire V3_0.
+ if trigger_source == "TokenGeneration_ClientCredentials" and v2_version != "V3_0":
+ return claims
event = _build_pretoken_event(
pool_id=pool_id,
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 6beb59c0..39f728f7 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -6718,6 +6718,39 @@ def test_cognito_pretoken_trigger_source_by_auth_flow(cognito_idp, lam):
assert _decode_jwt_claims(resp2["access_token"])["seen_trigger_source"] == "TokenGeneration_RefreshTokens"
[email protected]("version,fires", [("V2_0", False), ("V3_0", True)])
+def test_cognito_pretoken_client_credentials_fires_only_v3(cognito_idp, lam, version, fires):
+ """A client_credentials grant invokes the pre token generation trigger only with LambdaVersion V3_0."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " event['response']['claimsAndScopeOverrideDetails'] = {'accessTokenGeneration': {\n"
+ " 'claimsToAddOrOverride': {'seen_trigger_source': event['triggerSource']}}}\n"
+ " return event\n"
+ )
+ fn_name = f"ministack-pretoken-client-credentials-{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 = _client_credentials_client(cognito_idp)
+ cognito_idp.update_user_pool(
+ UserPoolId=pool_id,
+ LambdaConfig={"PreTokenGenerationConfig": {"LambdaArn": fn_arn, "LambdaVersion": version}},
+ )
+
+ status, _, body = _post_form(f"{ENDPOINT}/oauth2/token", {
+ "grant_type": "client_credentials", "client_id": client["ClientId"],
+ "client_secret": client["ClientSecret"], "scope": "api/read",
+ })
+
+ assert status == 200, body
+ claims = _decode_jwt_claims(json.loads(body)["access_token"])
+ assert claims.get("seen_trigger_source") == ("TokenGeneration_ClientCredentials" if fires else None)
+
+
def test_cognito_pretoken_v2_event_carries_the_granted_scopes(cognito_idp, lam):
"""request.scopes holds the access token's scopes."""
handler = (
@@ -6885,6 +6918,11 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):
# M2M client_credentials — carries client metadata via the separate
# aws_client_metadata POST field, not a ClientMetadata request parameter.
+ # Only a V3_0 trigger runs for this grant.
+ cognito_idp.update_user_pool(
+ UserPoolId=pool_id,
+ LambdaConfig={"PreTokenGenerationConfig": {"LambdaArn": fn_arn, "LambdaVersion": "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(