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): forward ClientMetadata into PreTokenGeneration's event.request (#1336)
ryan-bennett4b70bbf1be42
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11a30572..65c0a135 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Lambda — `LAMBDA_KEEPALIVE_MS=0` forces a per-invocation cold start** — a LocalStack-compat lever (not an AWS behavior): for Docker RIE runtimes (Ruby/Java/.NET), `LAMBDA_KEEPALIVE_MS=0` tears the warm container down after each invocation so the next invoke re-runs INIT, giving deterministic cold-start isolation for test suites. Unset or any non-zero value keeps the warm-pool behavior. Reported by @mayankgupta57.### Fixed+- **Cognito — PreTokenGeneration's `event.request` now carries `clientMetadata` on the operations that actually forward it** — `_build_pretoken_event` never included the key at all, so a Lambda reading `event.request.clientMetadata` always saw it as empty. Per the real AWS Cognito Developer Guide, that field is populated only from `RespondToAuthChallenge`/`AdminRespondToAuthChallenge`'s `ClientMetadata` parameter and, for M2M client-credentials tokens, the `aws_client_metadata` POST field on the token endpoint — Cognito explicitly excludes `InitiateAuth`/`AdminInitiateAuth` (including their `REFRESH_TOKEN_AUTH` flows) and `GetTokensFromRefreshToken` from this. Both are now threaded through correctly. Contributed by @ryan-bennett.- **S3 — POST Object no longer misreads form fields as the object body** — a multipart part was classified as the object content when its name was `file` **or** it carried a `filename` attribute, but browsers and HTTP libraries (Python `requests`' `files=`) set `filename` on ordinary form fields, so every field looked like the body, no `key` field survived, and the upload was rejected with `InvalidArgument`. Only the field literally named `file` is the body now, matching S3. Reported by @gaul.- **S3 — `GetObject` with `partNumber` returns the requested part** — the `partNumber` parameter was dropped, so a client fetching an N-part object in parallel received N full copies. A completed multipart object now returns the requested part as `206 Partial Content` with a `Content-Range` and `x-amz-mp-parts-count`, matching S3. Reported by @gaul.- **S3 — `ListObjectVersions` returns continuation markers when truncated** — a truncated response set `IsTruncated=true` but emitted neither `NextKeyMarker` nor `NextVersionIdMarker`, and the incoming `version-id-marker` was ignored, so a paginating client looped on page one or (as boto3 does) rejected `KeyMarker=None`. The markers are now emitted and `version-id-marker` resumes within `key-marker`. Reported by @gaul.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex bcf45741..30791780 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -579,7 +579,8 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesusername: str = "", user_attrs: dict | None = None,groups: list[str] | None = None,nonce: str = "",- trigger_source: str = "TokenGeneration_Authentication") -> str:+ trigger_source: str = "TokenGeneration_Authentication",+ client_metadata: dict | None = None) -> str:"""Return a JWT signed with the RSA key when cryptography is available.For ``access`` and ``id`` tokens, runs the user pool's PreTokenGeneration@@ -645,6 +646,7 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesusername=username,user_attrs=user_attrs or {},groups=groups or [],+ client_metadata=client_metadata,)payload = base64.urlsafe_b64encode(@@ -664,7 +666,8 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesdef _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,trigger_source: str, client_id: str,username: str, user_attrs: dict,- groups: list[str]) -> dict:+ groups: list[str],+ client_metadata: dict | None = None) -> dict:"""Invoke the user pool's PreTokenGeneration Lambda and apply its overrides.Honours both V1_0 (``LambdaConfig.PreTokenGeneration`` — id token only,@@ -702,6 +705,7 @@ def _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,groups=groups,trigger_source=trigger_source,version=v2_version if use_v2 else "V1_0",+ client_metadata=client_metadata,)strict = os.environ.get("MINISTACK_COGNITO_PRETOKEN_STRICT", "").lower() in ("1", "true", "yes")@@ -768,7 +772,8 @@ def _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,def _build_pretoken_event(pool_id: str, client_id: str, username: str,user_attrs: dict, groups: list[str],- trigger_source: str, version: str) -> dict:+ trigger_source: str, version: str,+ client_metadata: dict | None = None) -> dict:"""Construct the event payload AWS sends to a PreTokenGeneration Lambda.Shape from the Cognito Developer Guide@@ -782,6 +787,7 @@ def _build_pretoken_event(pool_id: str, client_id: str, username: str,"iamRolesToOverride": [],"preferredRole": None,},+ "clientMetadata": client_metadata or {},}if version.startswith("V2") or version.startswith("V3"):request_block["scopes"] = ["aws.cognito.signin.user.admin"]@@ -1300,7 +1306,8 @@ def _continue_custom_auth_after_define(if define_resp.get("issueTokens"):del _challenge_sessions[token]return json_response({"AuthenticationResult": _build_auth_result(- session["pool_id"], session["client_id"], user+ session["pool_id"], session["client_id"], user,+ client_metadata=client_metadata,)})next_challenge = define_resp.get("challengeName")@@ -2893,7 +2900,8 @@ def _mfa_challenge_for_user(pool: dict, user: dict, pid: str, username: str) ->def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = "",- trigger_source: str = "TokenGeneration_Authentication") -> dict:+ trigger_source: str = "TokenGeneration_Authentication",+ client_metadata: dict | None = None) -> dict:attrs = _attr_list_to_dict(user.get("Attributes", []))sub = attrs.get("sub", user["Username"])username = user.get("Username", "")@@ -2901,10 +2909,12 @@ def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = ""return {"AccessToken": _fake_token(sub, pool_id, client_id, "access", username=username,user_attrs=attrs, groups=groups,- trigger_source=trigger_source),+ trigger_source=trigger_source,+ client_metadata=client_metadata),"IdToken": _fake_token(sub, pool_id, client_id, "id", username=username,user_attrs=attrs, groups=groups, nonce=nonce,- trigger_source=trigger_source),+ trigger_source=trigger_source,+ client_metadata=client_metadata),"RefreshToken": _fake_token(sub, pool_id, client_id, "refresh"),"TokenType": "Bearer","ExpiresIn": 3600,@@ -3124,6 +3134,7 @@ def _admin_respond_to_auth_challenge(data):if challenge_name == "NEW_PASSWORD_REQUIRED":username = responses.get("USERNAME")new_password = responses.get("NEW_PASSWORD")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err@@ -3131,30 +3142,37 @@ def _admin_respond_to_auth_challenge(data):user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"user["UserLastModifiedDate"] = _now_epoch()- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})if challenge_name == "SMS_MFA":username = responses.get("USERNAME")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})if challenge_name == "SOFTWARE_TOKEN_MFA":username = responses.get("USERNAME")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err# Accept any TOTP code in emulator — no real TOTP validation- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})if challenge_name == "MFA_SETUP":# Triggered when pool MFA=ON but user hasn't enrolled yetusername = responses.get("USERNAME")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)@@ -3438,6 +3456,7 @@ def _respond_to_auth_challenge(data):username = responses.get("USERNAME")new_password = responses.get("NEW_PASSWORD") or responses.get("PASSWORD")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err@@ -3445,11 +3464,13 @@ def _respond_to_auth_challenge(data):user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"user["UserLastModifiedDate"] = _now_epoch()- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})if challenge_name == "NEW_PASSWORD_REQUIRED":username = responses.get("USERNAME")new_password = responses.get("NEW_PASSWORD") or responses.get("PASSWORD")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err@@ -3457,15 +3478,18 @@ def _respond_to_auth_challenge(data):user["_password"] = new_passworduser["UserStatus"] = "CONFIRMED"user["UserLastModifiedDate"] = _now_epoch()- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})if challenge_name in ("SOFTWARE_TOKEN_MFA", "MFA_SETUP"):username = responses.get("USERNAME")+ client_metadata = data.get("ClientMetadata", {})user, _err = _resolve_user(pool, username)if _err:return _err# Accept any TOTP code in emulator- return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})+ return json_response({"AuthenticationResult": _build_auth_result(+ pid, cid, user, client_metadata=client_metadata)})return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)@@ -5373,7 +5397,24 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonif csec != client["ClientSecret"]:return _oauth2_error("invalid_client", "Invalid client credentials.")- access_token = _fake_token(cid, pool_id, cid, "access")+ # M2M's own client-metadata channel — a JSON object, urlencoded, in+ # the aws_client_metadata POST field (there's no ClientMetadata+ # request field on this grant the way there is on+ # Initiate/RespondToAuthChallenge). parse_qs already url-decoded the+ # form, so this is the raw JSON string.+ client_metadata = {}+ raw_metadata = form.get("aws_client_metadata", "")+ if raw_metadata:+ try:+ parsed_metadata = json.loads(raw_metadata)+ if isinstance(parsed_metadata, dict):+ client_metadata = parsed_metadata+ except (json.JSONDecodeError, TypeError):+ pass++ access_token = _fake_token(cid, pool_id, cid, "access",+ trigger_source="TokenGeneration_ClientCredentials",+ client_metadata=client_metadata)resp = {"access_token": access_token,"token_type": "Bearer",diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 80ce3c42..787e5ed2 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -4320,6 +4320,135 @@ def test_cognito_pretoken_trigger_source_by_auth_flow(cognito_idp, lam):assert _decode_jwt_claims(resp2["access_token"])["seen_trigger_source"] == "TokenGeneration_RefreshTokens"+def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):+ """PreTokenGeneration's event.request.clientMetadata should carry+ ClientMetadata from RespondToAuthChallenge / AdminRespondToAuthChallenge,+ and aws_client_metadata from the M2M client_credentials grant — matching+ real AWS's documented behavior+ (https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html):+ "Amazon Cognito doesn't include data from the ClientMetadata parameter in+ AdminInitiateAuth and InitiateAuth API operations in the request that it+ passes to the pre token generation function." That exclusion covers+ REFRESH_TOKEN_AUTH (both InitiateAuth and AdminInitiateAuth) and+ GetTokensFromRefreshToken too, since none of those are+ RespondToAuthChallenge. Before this fix, _build_pretoken_event never+ included the key for any operation; an earlier version of this fix+ forwarded it from exactly the operations real AWS excludes, and dropped+ it from the ones that actually carry it."""+ handler = (+ "def handler(event, ctx):\n"+ " cm = event['request'].get('clientMetadata') or {}\n"+ " event['response']['claimsAndScopeOverrideDetails'] = {\n"+ " 'accessTokenGeneration': {'claimsToAddOrOverride': {'seen_org_id': cm.get('orgId', '')}},\n"+ " }\n"+ " return event\n"+ )+ fn_name = "ministack-pretoken-client-metadata"+ 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=True)+ cognito_idp.update_user_pool(+ UserPoolId=pool_id,+ LambdaConfig={"PreTokenGenerationConfig": {+ "LambdaArn": fn_arn, "LambdaVersion": "V2_0",+ }},+ )+ client_id = client["ClientId"]+ client_secret = client["ClientSecret"]++ # InitiateAuth(USER_PASSWORD_AUTH) — real AWS never forwards ClientMetadata+ # 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!"},+ ClientMetadata={"orgId": "org-password"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(auth["AccessToken"])["seen_org_id"] == ""++ # InitiateAuth(REFRESH_TOKEN_AUTH) — same exclusion.+ refreshed = cognito_idp.initiate_auth(+ ClientId=client_id, AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": auth["RefreshToken"]},+ ClientMetadata={"orgId": "org-refresh"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(refreshed["AccessToken"])["seen_org_id"] == ""++ # 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!"},+ ClientMetadata={"orgId": "org-admin-password"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(admin_auth["AccessToken"])["seen_org_id"] == ""++ # 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"]},+ ClientMetadata={"orgId": "org-admin-refresh"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(admin_refreshed["AccessToken"])["seen_org_id"] == ""++ # GetTokensFromRefreshToken — same exclusion.+ gtfrt = cognito_idp.get_tokens_from_refresh_token(+ ClientId=client_id, RefreshToken=auth["RefreshToken"],+ ClientMetadata={"orgId": "org-gtfrt"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(gtfrt["AccessToken"])["seen_org_id"] == ""++ # RespondToAuthChallenge(NEW_PASSWORD_REQUIRED) — one of the two operations+ # real AWS's docs say actually carries ClientMetadata to this trigger.+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="newpwduser")+ cognito_idp.admin_set_user_password(+ 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!"},+ )+ 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!"},+ ClientMetadata={"orgId": "org-new-password"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(respond_result["AccessToken"])["seen_org_id"] == "org-new-password"++ # AdminRespondToAuthChallenge(NEW_PASSWORD_REQUIRED) — the admin counterpart.+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="adminnewpwduser")+ cognito_idp.admin_set_user_password(+ 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!"},+ )+ 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!"},+ ClientMetadata={"orgId": "org-admin-new-password"},+ )["AuthenticationResult"]+ assert _decode_jwt_claims(admin_respond_result["AccessToken"])["seen_org_id"] == "org-admin-new-password"++ # M2M client_credentials — carries client metadata via the separate+ # aws_client_metadata POST field, not a ClientMetadata request parameter.+ status, _, body = _post_form(f"{ENDPOINT}/oauth2/token", {+ "grant_type": "client_credentials",+ "client_id": client_id,+ "client_secret": client_secret,+ "aws_client_metadata": json.dumps({"orgId": "org-m2m"}),+ })+ assert status == 200+ m2m_token = json.loads(body)["access_token"]+ assert _decode_jwt_claims(m2m_token)["seen_org_id"] == "org-m2m"++@pytest.fixturedef _enable_persistence(monkeypatch, tmp_path):"""Force PERSIST_STATE on and point STATE_DIR at a tmp dir so