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): OAuth scope checks for federation and client_credentials (#2263)
iot-rocketd581576ca337
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4acce07e..e1cafb1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Cognito — OAuth scope checks for federation and `client_credentials`** — `/oauth2/authorize` with an `identity_provider` went on to the identity provider whatever the `scope`; it now redirects to the callback with `error_description=invalid_scope` (and the `state`) when a requested scope is not in the client's `AllowedOAuthScopes`, as the managed login does. The `client_credentials` grant answered `invalid_scope` to any request naming an undefined resource server scope; it now ignores those once a defined scope is requested, so `api/read bogus/x` is granted `api/read` and `api/admin bogus/x` answers `invalid_grant`, as AWS does. Contributed by @iot-rocket.- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.- **CloudTrail — `RecursiveLogging` on trails** — `CreateTrail` and `UpdateTrail` ignored `RecursiveLogging` and no trail response carried it; trails now store it (default `true`, kept by an `UpdateTrail` that leaves it out) and return it from `CreateTrail`, `UpdateTrail`, `GetTrail` and `DescribeTrails`. Contributed by @iot-rocket.- **CloudWatch — composite alarms follow their rule** — a composite alarm stayed in `INSUFFICIENT_DATA` whatever its children did and `DeleteAlarms` removed alarms that composite alarms depend on; a composite alarm now evaluates its `AlarmRule` (`ALARM`, `OK`, `INSUFFICIENT_DATA`, `TRUE`, `FALSE`, `AND`, `OR`, `NOT`, `AT_LEAST`) when it is created or updated and whenever a child changes state, with the `StateReason`, `StateReasonData` and history items AWS writes, `PutCompositeAlarm` refuses an unknown child or a malformed rule with `ValidationError`, `DeleteAlarms` refuses an alarm a composite alarm depends on and more than one composite alarm per call, and `DescribeAlarmHistory` returns composite alarm items only for `AlarmTypes=["CompositeAlarm"]`, as AWS does. Contributed by @iot-rocket.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 88e0886a..08beb4e1 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -808,7 +808,7 @@ def _id_token_granted(scope: str | None) -> bool:def _client_credentials_scope_error(pool: dict, client: dict, requested: str | None):- """invalid_scope for an undefined scope, invalid_grant for one the client doesn't allow; the whole grant fails."""+ """invalid_scope for a non-custom scope or no defined one, invalid_grant for one the client doesn't allow."""allowed = client.get("AllowedOAuthScopes") or []wanted = requested.split() if requested else [s for s in allowed if "/" in s]defined = {@@ -816,10 +816,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 (requested and not wanted) or any(scope not in defined for scope in wanted):+ # 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):error = "invalid_scope"- elif any(scope not in allowed for scope in wanted):+ elif any(scope in defined and scope not in allowed for scope in wanted):error = "invalid_grant"+ elif wanted and not defined.intersection(wanted):+ error = "invalid_scope"else:return Nonereturn 400, {"Content-Type": "application/json"}, json.dumps({"error": error}).encode()@@ -5960,6 +5963,18 @@ def _oauth2_error(error: str, description: str, status: int = 400):return status, {"Content-Type": "application/json"}, body+def _invalid_scope_redirect(client, redirect_uri: str, scope: str, state: str):+ """The redirect back to the app for an authorize request with a scope the client does not allow, or None."""+ allowed_scopes = client.get("AllowedOAuthScopes") or []+ if not (redirect_uri and scope and allowed_scopes and any(s not in allowed_scopes for s in scope.split())):+ return None+ sep = "&" if "?" in redirect_uri else "?"+ location = f"{redirect_uri}{sep}error=invalid_request&error_description=invalid_scope"+ if state:+ location += f"&state={quote(state)}"+ return 302, {"Location": location, "Cache-Control": "no-store"}, b""++def _use_choice_based_ui(client) -> bool:"""True when the client's ExplicitAuthFlows opts into USER_AUTH (choice-basedsign-in), which drives a multi-step Hosted UI instead of the single-page form."""@@ -6169,6 +6184,9 @@ def _oauth2_authorize_federation(query_params):if callback_urls and redirect_uri not in callback_urls:return error_response_json("InvalidParameterException",f"redirect_uri {redirect_uri} is not in CallbackURLs.", 400)+ invalid_scope = _invalid_scope_redirect(client, redirect_uri, _qp(query_params, "scope"), state)+ if invalid_scope:+ return invalid_scopeif not identity_provider:return error_response_json("InvalidParameterException", "identity_provider is required.", 400)@@ -6275,14 +6293,9 @@ def handle_oauth2_authorize(method, path, headers, query_params):return _oauth2_error("invalid_request", "redirect_uri is required.")if callback_urls and redirect_uri not in callback_urls:return _oauth2_error("invalid_request", f"redirect_uri is not allowed: {redirect_uri}")-- allowed_scopes = client.get("AllowedOAuthScopes") or []- if scope and allowed_scopes and any(s not in allowed_scopes for s in scope.split()):- sep = "&" if "?" in redirect_uri else "?"- location = f"{redirect_uri}{sep}error=invalid_request&error_description=invalid_scope"- if state:- location += f"&state={quote(state)}"- return 302, {"Location": location, "Cache-Control": "no-store"}, b""+ invalid_scope = _invalid_scope_redirect(client, redirect_uri, scope, state)+ if invalid_scope:+ return invalid_scopeif _use_choice_based_ui(client):html_body = _username_page_html(diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex bc2770f3..fa5a7c07 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -4878,7 +4878,7 @@ def test_apigwv1_cognito_client_credentials_http(apigw_v1, cognito_idp, basic):assert (status, body) == (401, {"message": "Unauthorized"})assert headers["x-amzn-errortype"] == "UnauthorizedException"for scope, error in (("api/admin", "invalid_grant"), ("api/missing", "invalid_scope"),- ("api/read api/admin", "invalid_grant"), ("api/read api/missing", "invalid_scope")):+ ("api/read api/admin", "invalid_grant"), ("api/admin bogus/x", "invalid_grant")):status, response = get_token(scope)assert status == 400, responseassert response["error"] == errordiff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex ada92b58..5ac86de0 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -3091,6 +3091,27 @@ def test_cognito_oauth2_authorize_oidc_redirect(cognito_idp):stop()+def test_cognito_oauth2_authorize_oidc_invalid_scope_redirects_to_the_callback(cognito_idp):+ """A scope the client does not allow is refused before the IdP redirect."""+ _pid, cid = _setup_oidc_pool(cognito_idp, "https://idp.example.com/token")+ url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestOIDC&state=mystate&scope=openid+profile"+ )+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected 302"+ except urllib.error.HTTPError as e:+ assert e.code == 302+ location = e.headers.get("Location", "")+ assert location.startswith("http://localhost:3000/callback?")+ assert _parse_qs(urlparse(location).query) == {+ "error": ["invalid_request"], "error_description": ["invalid_scope"], "state": ["mystate"],+ }++def test_cognito_oidc_full_flow(cognito_idp):"""End-to-end OIDC federation: authorize → IdP callback → token exchangeagainst fake IdP → user provisioned → app redirect with MS auth code."""@@ -4805,6 +4826,8 @@ def test_oauth2_token_client_credentials_expires_with_the_client():('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'),+ ('api/read api/bogus', 'api/read'),])def test_oauth2_token_client_credentials_carries_granted_scopes(requested, scope):"""No scope parameter grants every scope the client allows."""@@ -4859,7 +4882,7 @@ def test_oauth2_token_client_credentials_refuses_scopes_it_cannot_grant(requeste('api/missing', 'invalid_scope'),('missing/read', 'invalid_scope'),('api/read api/admin', 'invalid_grant'),- ('api/read api/missing', 'invalid_scope'),+ ('api/admin missing/read', 'invalid_grant'),('openid', 'invalid_scope'),(' ', 'invalid_scope'),])