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): token endpoint access tokens carry the granted scopes (#2199)
iot-rocket47d20b16b103
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aee917cc..c71908f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Cognito — no ID token without `openid`** — the `/oauth2/token` authorization code and refresh token grants returned an `id_token` whatever was granted; they now return one only when the grant carries `openid`, as AWS does, and a refresh token from `InitiateAuth` or `AdminInitiateAuth` still gets one. Contributed by @iot-rocket.+- **Cognito — token endpoint access tokens carry the granted scopes** — `/oauth2/token` wrote `aws.cognito.signin.user.admin` into every access token whatever was granted; the authorization code, client credentials and refresh token grants now write the requested scopes the app client allows (all of them when none are requested, only resource server scopes for client credentials) in the order AWS lists them, refreshed tokens keep the original scopes, and the pre token generation event's `request.scopes` lists them, so API Gateway scope checks decide as on AWS. Contributed by @iot-rocket.- **S3 — object ACL grants answer another account's read** — a bucket owned by another account refused every read that only the object ACL granted: the ACL was looked up under the wrong version, and a grant to the caller's canonical ID was never read. With ACLs enabled, a `READ` grant to the account or a group now opens `GetObject` and `HeadObject` of the version it was set on, `?versionId=` included, and `READ_ACP` opens `GetObjectAcl`; a grant to one account is not public, so Block Public Access leaves it in force. Contributed by @iot-rocket.- **CloudWatch — `DescribeAlarms` and `DescribeAlarmHistory` paging** — both returned at most `MaxRecords` items (default 100) and never a `NextToken`, so a paginator stopped after the first page; they now return a `NextToken` while more items match, default to 50 items and refuse a `MaxRecords` outside 1 to 100 with `ValidationError`. `DescribeAlarms` now lists metric and composite alarms in one name-ordered sequence that `MaxRecords` counts together, and `DescribeAlarmHistory` lists the newest items first unless `ScanBy` is `TimestampAscending`. `DescribeAlarms` without `AlarmTypes` now returns metric alarms only, as on AWS; composite alarms need `AlarmTypes=["CompositeAlarm"]`. Contributed by @iot-rocket.- **CloudWatch Logs — a log group's resource policy by `resourceArn` alone** — `PutResourcePolicy` and `DeleteResourcePolicy` refused a `resourceArn` without `policyName`; they now take it, store the group's policy without a name and with a counting `revisionId`, and answer a request with neither field or a revision conflict with AWS's errors. `AWS::Logs::LogGroup` now creates, rewrites and removes the group's own policy from `ResourcePolicyDocument`. Contributed by @iot-rocket.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex d72ab824..e3628487 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -766,18 +766,62 @@ def _token_validity(pool_id: str, client_id: str, token_type: str) -> int:return int(value) * _VALIDITY_UNIT_SECONDS.get(unit, 3600)+_API_TOKEN_SCOPE = "aws.cognito.signin.user.admin"+++def _aws_scope_order(scopes: list[str], presized: bool = True) -> list[str]:+ """Scopes in the iteration order of a Java HashSet built from them, the order AWS lists them in."""+ # The token's set is sized for the scopes up front, the trigger event's grows as they are added+ limit = len(scopes) / 0.75+ if presized:+ limit = int(limit) + 1+ size = 16+ while size < limit:+ size *= 2++ def bucket(scope):+ h = 0+ for ch in scope:+ h = (31 * h + ord(ch)) & 0xFFFFFFFF+ return (h ^ (h >> 16)) & (size - 1)++ return sorted(scopes, key=bucket)+++def _granted_scopes(client: dict | None, requested: str | None, grant: str = "authorization_code") -> str | None:+ """The scopes a token-endpoint grant carries: the requested ones the client allows, or all it allows."""+ listed = (client or {}).get("AllowedOAuthScopes") or []+ if not listed and not requested:+ # Nothing to grant from: keep the API sign-in scope+ return None+ # client_credentials grants only resource-server scopes+ allowed = sorted(s for s in listed if "/" in s or grant != "client_credentials")+ wanted = requested.split() if requested else allowed+ if listed:+ wanted = [s for s in wanted if s in allowed]+ return " ".join(dict.fromkeys(wanted))+++def _id_token_granted(scope: str | None) -> bool:+ """Whether a grant gets an ID token: API sign-ins always, OAuth grants only with openid."""+ return scope is None or "openid" in scope.split()++def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access",username: str = "", user_attrs: dict | None = None,groups: list[str] | None = None,nonce: str = "",trigger_source: str = "TokenGeneration_Authentication",- client_metadata: dict | None = None, origin_jti: str = "") -> str:+ client_metadata: dict | None = None, origin_jti: str = "",+ scope: str | 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 PreTokenGenerationLambda trigger (V2_0 — both tokens; V1_0 — id token only) before signing.- Refresh tokens are opaque in AWS and skip the trigger.+ Refresh tokens are opaque in AWS and skip the trigger. ``scope`` is the+ grant's scopes; None for API sign-ins."""+ granted = _API_TOKEN_SCOPE if scope is None else scopenow = int(time.time())origin_jti = origin_jti or new_uuid()claims = {@@ -824,7 +868,7 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesclaims["client_id"] = client_idclaims["auth_time"] = nowclaims["origin_jti"] = origin_jti- claims["scope"] = "aws.cognito.signin.user.admin"+ claims["scope"] = " ".join(_aws_scope_order(granted.split()))if username:claims["username"] = usernameif groups:@@ -833,6 +877,8 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "acces# RefreshToken — opaque in real AWS, but we use a JWT stub for simplicityclaims["client_id"] = client_idclaims["origin_jti"] = origin_jti+ if scope is not None:+ claims["scope"] = scopeif token_type in ("access", "id"):claims = _apply_pretoken_trigger(@@ -845,6 +891,7 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "accesuser_attrs=user_attrs or {},groups=groups or [],client_metadata=client_metadata,+ scope=granted,)return _signed_jwt(claims)@@ -872,7 +919,8 @@ def _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],- client_metadata: dict | None = None) -> dict:+ client_metadata: dict | None = None,+ scope: str = _API_TOKEN_SCOPE) -> dict:"""Invoke the user pool's PreTokenGeneration Lambda and apply its overrides.Honours both V1_0 (``LambdaConfig.PreTokenGeneration`` — id token only,@@ -911,6 +959,7 @@ def _apply_pretoken_trigger(pool_id: str, claims: dict, token_type: str,trigger_source=trigger_source,version=v2_version if use_v2 else "V1_0",client_metadata=client_metadata,+ scope=scope,)strict = os.environ.get("MINISTACK_COGNITO_PRETOKEN_STRICT", "").lower() in ("1", "true", "yes")@@ -978,7 +1027,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,- client_metadata: dict | None = None) -> dict:+ client_metadata: dict | None = None,+ scope: str = _API_TOKEN_SCOPE) -> dict:"""Construct the event payload AWS sends to a PreTokenGeneration Lambda.Shape from the Cognito Developer Guide@@ -995,7 +1045,7 @@ def _build_pretoken_event(pool_id: str, client_id: str, username: str,"clientMetadata": client_metadata or {},}if version.startswith("V2") or version.startswith("V3"):- request_block["scopes"] = ["aws.cognito.signin.user.admin"]+ request_block["scopes"] = _aws_scope_order(scope.split(), presized=False)response_block = ({"claimsAndScopeOverrideDetails": None}@@ -3949,7 +3999,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",- client_metadata: dict | None = None, origin_jti: str = "") -> dict:+ client_metadata: dict | None = None, origin_jti: str = "",+ scope: str | None = None) -> dict:if not origin_jti:origin_jti = new_uuid()user.setdefault("_origin_jtis", []).append(origin_jti)@@ -3961,12 +4012,12 @@ def _build_auth_result(pool_id: str, client_id: str, user: dict, nonce: str = """AccessToken": _fake_token(sub, pool_id, client_id, "access", username=username,user_attrs=attrs, groups=groups,trigger_source=trigger_source,- client_metadata=client_metadata, origin_jti=origin_jti),+ client_metadata=client_metadata, origin_jti=origin_jti, scope=scope),"IdToken": _fake_token(sub, pool_id, client_id, "id", username=username,user_attrs=attrs, groups=groups, nonce=nonce,trigger_source=trigger_source,- client_metadata=client_metadata, origin_jti=origin_jti),- "RefreshToken": _fake_token(sub, pool_id, client_id, "refresh", origin_jti=origin_jti),+ client_metadata=client_metadata, origin_jti=origin_jti, scope=scope),+ "RefreshToken": _fake_token(sub, pool_id, client_id, "refresh", origin_jti=origin_jti, scope=scope),"TokenType": "Bearer","ExpiresIn": _token_validity(pool_id, client_id, "access"),}@@ -4358,8 +4409,10 @@ def _refresh_auth_result(pool, pid, cid, refresh_token):user, err = _refresh_auth_user(pool, pid, cid, refresh_token)if err:return None, err+ claims = _token_claims(refresh_token)result = _build_auth_result(pid, cid, user, trigger_source="TokenGeneration_RefreshTokens",- origin_jti=_token_claims(refresh_token).get("origin_jti", ""))+ origin_jti=claims.get("origin_jti", ""),+ scope=claims.get("scope"))result.pop("RefreshToken", None) # AWS doesn't return a new refresh token herereturn result, None@@ -6960,6 +7013,8 @@ def _oauth2_refresh_api_issued_token(refresh_val: str, cid: str, csec: str):"token_type": "Bearer","expires_in": 3600,}+ if not _id_token_granted(claims.get("scope")):+ del resp["id_token"]return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()@@ -7031,8 +7086,9 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonif not user:return _oauth2_error("server_error", "User not found.")+ scope = _granted_scopes(client, entry.get("scope"))result = _build_auth_result(pool_id, cid, user, nonce=entry.get("nonce", ""),- trigger_source="TokenGeneration_HostedAuth")+ trigger_source="TokenGeneration_HostedAuth", scope=scope)refresh_val = result["RefreshToken"]_refresh_tokens[refresh_val] = {"pool_id": pool_id,@@ -7048,6 +7104,8 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Non"token_type": "Bearer","expires_in": result["ExpiresIn"],}+ if not _id_token_granted(scope):+ del resp["id_token"]return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()# Try SAML/OIDC federation auth codes@@ -7067,6 +7125,7 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonuser_attrs = {}groups = []origin_jti = new_uuid()+ scope = _granted_scopes(_find_pool_by_client_id(effective_client_id)[2], code_data.get("scopes"))pool = _get_pool_unscoped(pool_id)if pool:user = pool["_users"].get(username)@@ -7077,19 +7136,24 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonaccess_token = _fake_token(sub, pool_id, effective_client_id, "access", username,user_attrs=user_attrs, groups=groups,- trigger_source="TokenGeneration_HostedAuth", origin_jti=origin_jti)+ trigger_source="TokenGeneration_HostedAuth", origin_jti=origin_jti,+ scope=scope)id_token = _fake_token(sub, pool_id, effective_client_id, "id", username, user_attrs=user_attrs,groups=groups, trigger_source="TokenGeneration_HostedAuth",- nonce=code_data.get("nonce", ""), origin_jti=origin_jti)- refresh_token = _fake_token(sub, pool_id, effective_client_id, "refresh", origin_jti=origin_jti)+ nonce=code_data.get("nonce", ""), origin_jti=origin_jti, scope=scope)+ refresh_token = _fake_token(sub, pool_id, effective_client_id, "refresh", origin_jti=origin_jti,+ scope=scope)- return json_response({+ resp = {"id_token": id_token,"access_token": access_token,"refresh_token": refresh_token,"token_type": "Bearer","expires_in": _token_validity(pool_id, effective_client_id, "access"),- })+ }+ if not _id_token_granted(scope):+ del resp["id_token"]+ return json_response(resp)return _oauth2_error("invalid_grant", "Invalid or expired authorization code.")@@ -7117,15 +7181,21 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonattrs = _attr_list_to_dict(user.get("Attributes", []))sub = attrs.get("sub", user["Username"])username = user.get("Username", "")- origin_jti = _token_claims(refresh_val).get("origin_jti", "")+ refresh_claims = _token_claims(refresh_val)+ origin_jti = refresh_claims.get("origin_jti", "")+ scope = refresh_claims.get("scope")resp = {"access_token": _fake_token(sub, pool_id, client_id, "access", username=username,- trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti),+ trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti,+ scope=scope),"id_token": _fake_token(sub, pool_id, client_id, "id", username=username, user_attrs=attrs,- trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti),+ trigger_source="TokenGeneration_RefreshTokens", origin_jti=origin_jti,+ scope=scope),"token_type": "Bearer","expires_in": _token_validity(pool_id, client_id, "access"),}+ if not _id_token_granted(scope):+ del resp["id_token"]return 200, {"Content-Type": "application/json"}, json.dumps(resp).encode()# ── client_credentials ──@@ -7155,7 +7225,8 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonaccess_token = _fake_token(cid, pool_id, cid, "access",trigger_source="TokenGeneration_ClientCredentials",- client_metadata=client_metadata)+ client_metadata=client_metadata,+ scope=_granted_scopes(client, form.get("scope"), "client_credentials"))resp = {"access_token": access_token,"token_type": "Bearer",diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 8844944a..e01161ac 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -4593,6 +4593,129 @@ def test_oauth2_token_refresh_token():assert 'id_token' in resp2+def _scoped_code_client(cognito_idp, scopes):+ """A pool with testuser and a code-flow client allowing *scopes* (resource servers api and zeta)."""+ pool_id, _ = _setup_pool_with_user(cognito_idp, generate_secret=False)+ for identifier, names in (('api', ('read', 'write', 'admin', *(f's{i}' for i in range(1, 9)))), ('zeta', ('x',))):+ cognito_idp.create_resource_server(+ UserPoolId=pool_id, Identifier=identifier, Name=identifier,+ Scopes=[{'ScopeName': n, 'ScopeDescription': n} for n in names],+ )+ return cognito_idp.create_user_pool_client(+ UserPoolId=pool_id, ClientName='scoped', AllowedOAuthFlows=['code'], AllowedOAuthScopes=scopes,+ AllowedOAuthFlowsUserPoolClient=True, CallbackURLs=['http://localhost:3000/callback'],+ ExplicitAuthFlows=['ALLOW_ADMIN_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ )['UserPoolClient']+++def _code_grant_tokens(cognito_idp, client_id, scope):+ code = _do_login_and_get_code(cognito_idp, client_id, {'scope': scope})+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code', 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback', 'client_id': client_id,+ })+ assert status == 200, body+ return json.loads(body)+++_SCOPED_CLIENT_SCOPES = ['profile', 'api/read', 'openid', 'email', 'aws.cognito.signin.user.admin', 'phone',+ 'api/write']++[email protected]('requested,scope', [+ ('openid email profile aws.cognito.signin.user.admin', 'aws.cognito.signin.user.admin openid profile email'),+ ('email openid', 'openid email'),+ ('phone api/write openid api/read', 'phone openid api/write api/read'),+ ('openid openid email', 'openid email'),+ ('api/read', 'api/read'),+ # No scope parameter: every scope the client allows+ ('', 'aws.cognito.signin.user.admin phone openid profile api/write email api/read'),+])+def test_oauth2_token_authorization_code_carries_granted_scopes(requested, scope):+ """The access token lists the granted scopes in AWS's order."""+ cognito_idp = make_client('cognito-idp')+ client = _scoped_code_client(cognito_idp, _SCOPED_CLIENT_SCOPES)+ tokens = _code_grant_tokens(cognito_idp, client['ClientId'], requested)+ assert _decode_jwt_claims(tokens['access_token'])['scope'] == scope+++_TWELVE_SCOPES = 'openid email phone profile ' + ' '.join(f'api/s{i}' for i in range(1, 9))++[email protected]('requested,scope', [+ # Scopes of one hash bucket keep the order of the request+ ('phone zeta/x api/s3', 'phone zeta/x api/s3'),+ ('api/s3 zeta/x phone', 'api/s3 zeta/x phone'),+ (_TWELVE_SCOPES, 'openid profile api/s1 api/s2 phone api/s3 api/s4 api/s5 api/s6 api/s7 api/s8 email'),+ (_TWELVE_SCOPES + ' aws.cognito.signin.user.admin',+ 'aws.cognito.signin.user.admin openid profile api/s1 api/s2 phone api/s3 api/s4 api/s5 api/s6 api/s7 '+ 'api/s8 email'),+ ('', 'aws.cognito.signin.user.admin openid profile api/read api/s1 api/s2 api/s3 phone zeta/x api/s4 api/s5 '+ 'api/s6 api/s7 api/s8 api/write email'),+])+def test_oauth2_token_scope_order_with_many_scopes(requested, scope):+ """Many granted scopes keep AWS's order."""+ cognito_idp = make_client('cognito-idp')+ client = _scoped_code_client(cognito_idp, ['zeta/x', *(f'api/s{i}' for i in range(8, 0, -1)), 'phone', 'openid',+ 'email', 'profile', 'aws.cognito.signin.user.admin', 'api/read',+ 'api/write'])+ tokens = _code_grant_tokens(cognito_idp, client['ClientId'], requested)+ assert _decode_jwt_claims(tokens['access_token'])['scope'] == scope+++def test_oauth2_token_authorization_code_drops_scopes_the_client_does_not_allow():+ """A scope the client does not allow is left out of the token; AWS refuses it at /oauth2/authorize."""+ cognito_idp = make_client('cognito-idp')+ client = _scoped_code_client(cognito_idp, ['email', 'openid'])+ tokens = _code_grant_tokens(cognito_idp, client['ClientId'], 'openid email profile api/read')+ assert _decode_jwt_claims(tokens['access_token'])['scope'] == 'openid email'+++def test_oauth2_refreshed_tokens_keep_the_granted_scopes():+ """Both refresh paths keep the code grant's scopes; API sign-ins keep the admin scope."""+ cognito_idp = make_client('cognito-idp')+ client = _scoped_code_client(cognito_idp, _SCOPED_CLIENT_SCOPES)+ client_id = client['ClientId']+ tokens = _code_grant_tokens(cognito_idp, client_id, 'phone api/write openid api/read')++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'refresh_token', 'refresh_token': tokens['refresh_token'], 'client_id': client_id,+ })+ assert status == 200, body+ assert _decode_jwt_claims(json.loads(body)['access_token'])['scope'] == 'phone openid api/write api/read'+ refreshed = cognito_idp.initiate_auth(+ ClientId=client_id, AuthFlow='REFRESH_TOKEN_AUTH',+ AuthParameters={'REFRESH_TOKEN': tokens['refresh_token']},+ )['AuthenticationResult']+ assert _decode_jwt_claims(refreshed['AccessToken'])['scope'] == 'phone openid api/write api/read'++ admin = cognito_idp.admin_initiate_auth(+ UserPoolId=client['UserPoolId'], ClientId=client_id, AuthFlow='ADMIN_USER_PASSWORD_AUTH',+ AuthParameters={'USERNAME': 'testuser', 'PASSWORD': 'TestPass1!'},+ )['AuthenticationResult']+ assert _decode_jwt_claims(admin['AccessToken'])['scope'] == 'aws.cognito.signin.user.admin'+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'refresh_token', 'refresh_token': admin['RefreshToken'], 'client_id': client_id,+ })+ assert status == 200, body+ assert _decode_jwt_claims(json.loads(body)['access_token'])['scope'] == 'aws.cognito.signin.user.admin'+++def test_oauth2_token_issues_no_id_token_without_openid():+ """The token endpoint returns no id_token when openid was not granted."""+ cognito_idp = make_client('cognito-idp')+ client = _scoped_code_client(cognito_idp, _SCOPED_CLIENT_SCOPES)+ tokens = _code_grant_tokens(cognito_idp, client['ClientId'], 'api/read')+ assert sorted(tokens) == ['access_token', 'expires_in', 'refresh_token', 'token_type']++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'refresh_token', 'refresh_token': tokens['refresh_token'], 'client_id': client['ClientId'],+ })++ assert status == 200, body+ assert sorted(json.loads(body)) == ['access_token', 'expires_in', 'token_type']++def test_oauth2_token_client_credentials():cognito_idp = make_client('cognito-idp')pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)@@ -4636,6 +4759,37 @@ def test_oauth2_token_client_credentials_expires_with_the_client():assert resp['expires_in'] == claims['exp'] - claims['iat'] == 300[email protected]('requested,scope', [+ (None, 'zeta/x api/write api/read'),+ ('api/read', 'api/read'),+ ('api/read api/write zeta/x', 'zeta/x api/write api/read'),+ ('api/read api/read', 'api/read'),+ ('api/read bogus/x', 'api/read'),+])+def test_oauth2_token_client_credentials_carries_granted_scopes(requested, scope):+ """No scope parameter grants every scope the client allows."""+ cognito_idp = make_client('cognito-idp')+ pool_id, _ = _setup_pool_with_user(cognito_idp)+ for identifier, names in (('api', ('read', 'write', 'admin')), ('zeta', ('x',))):+ cognito_idp.create_resource_server(+ UserPoolId=pool_id, Identifier=identifier, Name=identifier,+ Scopes=[{'ScopeName': n, 'ScopeDescription': n} for n in names],+ )+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pool_id, ClientName='m2m', GenerateSecret=True, AllowedOAuthFlows=['client_credentials'],+ AllowedOAuthScopes=['zeta/x', 'api/write', 'api/read'], AllowedOAuthFlowsUserPoolClient=True,+ )['UserPoolClient']+ form = {'grant_type': 'client_credentials', 'client_id': client['ClientId'],+ 'client_secret': client['ClientSecret']}+ if requested is not None:+ form['scope'] = requested++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', form)++ assert status == 200, body+ assert _decode_jwt_claims(json.loads(body)['access_token'])['scope'] == scope++def test_oauth2_token_client_auth_basic():cognito_idp = make_client('cognito-idp')pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)@@ -5402,6 +5556,48 @@ 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_v2_event_carries_the_granted_scopes(cognito_idp, lam):+ """request.scopes holds the access token's scopes."""+ handler = (+ "def handler(event, ctx):\n"+ " event['response']['claimsAndScopeOverrideDetails'] = {'accessTokenGeneration': {\n"+ " 'claimsToAddOrOverride': {'event_scopes': ' '.join(event['request']['scopes'])}}}\n"+ " return event\n"+ )+ fn_name = "ministack-pretoken-scopes"+ 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"]+ client = _scoped_code_client(cognito_idp, _SCOPED_CLIENT_SCOPES)+ cognito_idp.update_user_pool(+ UserPoolId=client["UserPoolId"],+ LambdaConfig={"PreTokenGenerationConfig": {"LambdaArn": fn_arn, "LambdaVersion": "V2_0"}},+ )++ access = _decode_jwt_claims(_code_grant_tokens(cognito_idp, client["ClientId"], "email openid")["access_token"])+ cognito_idp.update_user_pool_client(+ UserPoolId=client["UserPoolId"], ClientId=client["ClientId"], AllowedOAuthFlows=["code"],+ AllowedOAuthScopes=["openid", "email", "phone", "profile", *(f"api/s{i}" for i in range(1, 9))],+ AllowedOAuthFlowsUserPoolClient=True, CallbackURLs=["http://localhost:3000/callback"],+ ExplicitAuthFlows=["ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )+ twelve = _decode_jwt_claims(_code_grant_tokens(cognito_idp, client["ClientId"], _TWELVE_SCOPES)["access_token"])+ admin = cognito_idp.admin_initiate_auth(+ UserPoolId=client["UserPoolId"], ClientId=client["ClientId"], AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "testuser", "PASSWORD": "TestPass1!"},+ )["AuthenticationResult"]++ assert access["event_scopes"] == access["scope"] == "openid email"+ # Twelve scopes fill the event's set without growing it, while the token's is sized larger+ assert twelve["event_scopes"] == (+ "api/s1 api/s2 phone api/s3 openid api/s4 profile api/s5 api/s6 api/s7 api/s8 email")+ assert _decode_jwt_claims(admin["AccessToken"])["event_scopes"] == "aws.cognito.signin.user.admin"++def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):"""PreTokenGeneration's event.request.clientMetadata should carryClientMetadata from RespondToAuthChallenge / AdminRespondToAuthChallenge,