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): refuse client_credentials for clients without that flow (#2398)
iot-rocket3fca640ac9bf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6cfa8aea..f64d21c0 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 — `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.- **IoT — thing-group membership by ARN** — `AddThingToThingGroup` and `RemoveThingFromThingGroup` ignored `thingGroupArn` and `thingArn`, so a body with ARNs answered 400 or 404; both calls now act on the thing group and thing the ARNs name (in the request's region, as on AWS), refuse a name and ARN that differ, an ARN of another type or account and a body without the group or the thing with 400 `InvalidRequestException` and AWS's messages, and removing a thing from a group that does not exist answers 200 also when the group is given by ARN. Under `AUTH=true` such an ARN is authorized as that resource. Contributed by @iot-rocket.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 77d1a6e3..676919eb 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -818,6 +818,7 @@ def _token_validity(pool_id: str, client_id: str, token_type: str) -> int:_API_TOKEN_SCOPE = "aws.cognito.signin.user.admin"+_STANDARD_OAUTH_SCOPES = ("openid", "email", "phone", "profile", _API_TOKEN_SCOPE)def _aws_scope_order(scopes: list[str], presized: bool = True) -> list[str]:@@ -859,7 +860,7 @@ def _id_token_granted(scope: str | None) -> bool:def _client_credentials_scope_error(pool: dict, client: dict, requested: str | None):- """invalid_scope for a non-custom scope or no defined one, invalid_grant for one the client doesn't allow."""+ """invalid_scope for a non-custom scope or no defined one, invalid_grant for one or a flow the client lacks."""allowed = client.get("AllowedOAuthScopes") or []wanted = requested.split() if requested else [s for s in allowed if "/" in s]defined = {@@ -867,8 +868,13 @@ def _client_credentials_scope_error(pool: dict, client: dict, requested: str | Nfor identifier, server in (pool.get("_resource_servers") or {}).items()for scope in server.get("Scopes", [])}+ if "client_credentials" not in (client.get("AllowedOAuthFlows") or []):+ # Unknown scopes fail first; known ones get invalid_grant without the flow+ known = [scope for scope in wanted if scope in defined or scope in _STANDARD_OAUTH_SCOPES]+ unknown = any("/" not in scope and scope not in _STANDARD_OAUTH_SCOPES for scope in wanted)+ error = "invalid_scope" if unknown or not known else "invalid_grant"# An undefined resource server scope is dropped when a defined one is requested- if (requested and not wanted) or any("/" not in scope for scope in wanted):+ elif (requested and not wanted) or any("/" not in scope for scope in wanted):error = "invalid_scope"elif any(scope in defined and scope not in allowed for scope in wanted):error = "invalid_grant"@@ -7655,14 +7661,14 @@ def _oauth2_token(data, query_params, raw_body: bytes = b"", headers: dict | Nonpool_id, pool, client = _find_pool_by_client_id(cid)if not pool or not client:return _oauth2_error("invalid_client", "Client not found.")- if not client.get("ClientSecret"):- return _oauth2_error("invalid_client", "client_credentials requires a confidential client.")- if csec != client["ClientSecret"]:+ if csec != (client.get("ClientSecret") or ""):return _oauth2_error("invalid_client", "Invalid client credentials.")scope_error = _client_credentials_scope_error(pool, client, form.get("scope"))if scope_error:return scope_error+ if not client.get("ClientSecret"):+ return _oauth2_error("invalid_client", "client_credentials requires a confidential client.")# M2M's own client-metadata channel — a JSON object, urlencoded, in# the aws_client_metadata POST field (there's no ClientMetadatadiff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 4c24fe2c..6beb59c0 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -5624,6 +5624,39 @@ def test_oauth2_token_client_credentials_refuses_scopes_it_cannot_grant(requesteassert 'access_token' not in response[email protected]('flows,secret,requested,error', [+ (['code'], True, None, 'invalid_grant'),+ (['code'], True, 'api/read', 'invalid_grant'),+ (['code'], True, 'openid', 'invalid_grant'),+ (['code'], True, 'email', 'invalid_grant'),+ (['code'], True, 'api/read bogus/x', 'invalid_grant'),+ (['code'], True, 'bogus', 'invalid_scope'),+ (['implicit'], True, 'api/read', 'invalid_grant'),+ (['code'], False, None, 'invalid_grant'),+ ([], True, None, 'invalid_scope'),+])+def test_oauth2_token_client_credentials_needs_the_flow(flows, secret, requested, error):+ """A client without client_credentials in AllowedOAuthFlows gets no token; unknown scopes fail first."""+ cognito_idp = make_client('cognito-idp')+ pool_id, _ = _client_credentials_client(cognito_idp)+ oauth = {'AllowedOAuthFlows': flows, 'AllowedOAuthScopes': ['openid', 'api/read'],+ 'AllowedOAuthFlowsUserPoolClient': True, 'CallbackURLs': ['https://example.com/cb']}+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pool_id, ClientName='web', GenerateSecret=secret, **(oauth if flows else {}),+ )['UserPoolClient']+ form = {'grant_type': 'client_credentials', 'client_id': client['ClientId']}+ if secret:+ form['client_secret'] = client['ClientSecret']+ if requested is not None:+ form['scope'] = requested+ try:+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', form)+ assert status == 400, body+ assert json.loads(body) == {'error': error}+ finally:+ cognito_idp.delete_user_pool(UserPoolId=pool_id)++@pytest.mark.parametrize('basic', [False, True])@pytest.mark.parametrize('requested,error', [('api/admin', 'invalid_grant'),@@ -6767,7 +6800,6 @@ def test_cognito_pretoken_receives_client_metadata(cognito_idp, lam):}},)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.@@ -6853,10 +6885,15 @@ 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.+ 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": client_id,- "client_secret": client_secret,+ "client_id": machine["ClientId"],+ "client_secret": machine["ClientSecret"],"aws_client_metadata": json.dumps({"orgId": "org-m2m"}),})assert status == 200