Skip to content

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

fix(cognito): discover OIDC IdP endpoints from oidc_issuer (#2409)

Kinon6e4957b7ece3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05c45099..72049f2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Cognito — OIDC identity providers with only `oidc_issuer` use its discovered endpoints** — federated sign-in sent users to `{oidc_issuer}/authorize` and exchanged codes at `{oidc_issuer}/token` unless `authorize_url` and `token_url` were set, so an issuer whose endpoints live elsewhere, such as Google's, failed. Without those keys the endpoints now come from the issuer's `/.well-known/openid-configuration`, as on AWS, and a document naming another issuer is refused with `InvalidParameterException`. Contributed by @kinoh.
- **S3 — Block Public Access on new buckets** — `GetPublicAccessBlock` on a new bucket, from `CreateBucket` or from a template without `PublicAccessBlockConfiguration`, answered 404 and nothing refused a public bucket policy or ACL; under `AUTH=true` a new bucket now has all four settings on, as on AWS, so a public `PutBucketPolicy`, `PutBucketAcl` or object ACL answers 403 `AccessDenied` and `CreateBucket` with a public ACL 400 `InvalidBucketAclWithBlockPublicAccessError` until `PutPublicAccessBlock` or `DeletePublicAccessBlock` changes them, and removing the property from a template turns all four on again. With `AUTH` unset nothing changes. Contributed by @iot-rocket.
- **S3 — CORS under `AUTH=true`** — every S3 preflight answered 200 with `Access-Control-Allow-Origin: *` and every response carried the same wildcard headers, whatever the bucket's CORS configuration; under `AUTH=true` a preflight to an existing bucket now has to match one of its CORS rules (403 `AccessForbidden` without a configuration or a matching rule, 400 `BadRequest` without `Origin`) and gets that rule's headers, and a request with an `Origin` carries CORS headers only when a rule allows its origin and method. Contributed by @iot-rocket.
- **IoT — MQTT 5 No Local follows AWS IoT** — a subscription with No Local kept the client's own messages from it; AWS IoT Core ignores that option and delivers them, and so does the broker now. Contributed by @iot-rocket.
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 5b1e1ba7..18fe1f94 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -2306,6 +2306,39 @@ def _oidc_callback_url(pool: dict) -> str:
return f"{base}/oauth2/idpresponse"
+# ProviderDetails key -> OpenID Provider metadata key for the same endpoint.
+_OIDC_DISCOVERED_ENDPOINTS = {"authorize_url": "authorization_endpoint", "token_url": "token_endpoint"}
+
+
+def _oidc_endpoint(details: dict, key: str) -> str:
+ """An external OIDC IdP endpoint: the ProviderDetails value, else the one its issuer's discovery document advertises; "" if neither.
+
+ AWS takes `authorize_url` / `token_url` only for an IdP whose endpoints it
+ can't discover from `oidc_issuer`, so an issuer such as Google's, whose
+ endpoints are not `{issuer}/authorize` and `{issuer}/token`, works with
+ `oidc_issuer` alone. The document must name the configured issuer
+ (OpenID Connect Discovery 1.0, section 4.3).
+ """
+ import urllib.request
+
+ if details.get(key):
+ return details[key]
+ issuer = details.get("oidc_issuer", "")
+ if not issuer:
+ return ""
+ try:
+ with urllib.request.urlopen(f"{issuer.rstrip('/')}/.well-known/openid-configuration", timeout=10) as resp:
+ metadata = json.loads(resp.read().decode("utf-8"))
+ except (OSError, ValueError) as exc:
+ logger.warning("Cognito: OIDC discovery for %s failed: %s", issuer, exc)
+ return ""
+ if not isinstance(metadata, dict) or metadata.get("issuer") != issuer:
+ logger.warning("Cognito: OIDC discovery document of %s names another issuer", issuer)
+ return ""
+ url = metadata.get(_OIDC_DISCOVERED_ENDPOINTS[key])
+ return url if isinstance(url, str) else ""
+
+
def _saml_sso_url_from_metadata(metadata_xml: str) -> str:
"""The IdP's HTTP-Redirect SingleSignOnService Location, the binding Cognito sends AuthnRequests on; "" if none."""
if not metadata_xml:
@@ -6628,11 +6661,10 @@ def _oauth2_authorize_federation(query_params):
})
elif provider_type == "OIDC":
# OIDC authorize redirect
- oidc_issuer = details.get("oidc_issuer", "")
- authorize_url = details.get("authorize_url", f"{oidc_issuer}/authorize" if oidc_issuer else "")
+ authorize_url = _oidc_endpoint(details, "authorize_url")
if not authorize_url:
return error_response_json("InvalidParameterException",
- "OIDC provider has no oidc_issuer or authorize_url.", 400)
+ "OIDC provider has no authorize_url and none was discovered from its oidc_issuer.", 400)
oidc_client_id = details.get("client_id", "")
redirect_url = authorize_url + ("&" if "?" in authorize_url else "?") + urlencode({
"response_type": response_type or "code",
@@ -6950,11 +6982,10 @@ def _oauth2_idp_response(method, body, query_params):
f"OIDC provider {provider_name} not found.", 400)
details = provider.get("ProviderDetails", {})
- oidc_issuer = details.get("oidc_issuer", "")
- token_url = details.get("token_url") or (f"{oidc_issuer}/token" if oidc_issuer else "")
+ token_url = _oidc_endpoint(details, "token_url")
if not token_url:
return error_response_json("InvalidParameterException",
- "OIDC provider has no token_url or oidc_issuer.", 400)
+ "OIDC provider has no token_url and none was discovered from its oidc_issuer.", 400)
oidc_client_id = details.get("client_id", "")
oidc_client_secret = details.get("client_secret", "")
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 39f728f7..46dbaafb 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -3764,6 +3764,26 @@ def _start_fake_oidc_idp(claims):
self.end_headers()
self.wfile.write(payload)
+ def do_GET(self):
+ # Discovery document advertising endpoints off the issuer's root,
+ # as Google's does.
+ if self.path != "/.well-known/openid-configuration":
+ self.send_response(404)
+ self.end_headers()
+ return
+ issuer = f"http://127.0.0.1:{self.server.server_address[1]}"
+ payload = json.dumps({
+ "issuer": issuer,
+ "authorization_endpoint": f"{issuer}/o/oauth2/v2/auth",
+ "token_endpoint": f"{issuer}/oauth2/v4/token",
+ "jwks_uri": f"{issuer}/oauth2/v3/certs",
+ }).encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
def log_message(self, *args, **kwargs):
pass
@@ -3781,7 +3801,8 @@ def _start_fake_oidc_idp(claims):
return token_url, recorded, stop
-def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None, attribute_mapping=None):
+def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None, attribute_mapping=None,
+ provider_details=None):
pid = cognito_idp.create_user_pool(
PoolName="OIDCFedPool", **({"LambdaConfig": lambda_config} if lambda_config else {}),
)["UserPool"]["Id"]
@@ -3797,7 +3818,7 @@ def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None, attribute_mappi
UserPoolId=pid,
ProviderName="TestOIDC",
ProviderType="OIDC",
- ProviderDetails={
+ ProviderDetails=provider_details or {
"oidc_issuer": "https://idp.example.com",
"authorize_url": "https://idp.example.com/authorize",
"token_url": token_url,
@@ -3810,6 +3831,69 @@ def _setup_oidc_pool(cognito_idp, token_url, lambda_config=None, attribute_mappi
return pid, client["ClientId"]
+def _oidc_federation_redirect(client_id):
+ """The response to an /oauth2/authorize request federated to TestOIDC."""
+ url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={client_id}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=TestOIDC&state=appstate&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(url)
+ except urllib.error.HTTPError as e:
+ return e
+ assert False, "Expected an HTTP error status"
+
+
+def test_cognito_oidc_endpoints_from_issuer_discovery(cognito_idp):
+ """With only oidc_issuer, the IdP redirect and the token exchange use the
+ endpoints of the issuer's discovery document, not paths guessed from it."""
+ token_url, recorded, stop = _start_fake_oidc_idp({"sub": "user-9002"})
+ issuer = token_url.rsplit("/", 1)[0]
+ try:
+ pid, cid = _setup_oidc_pool(cognito_idp, token_url, provider_details={
+ "oidc_issuer": issuer,
+ "client_id": "oidc-client-id",
+ "client_secret": "oidc-client-secret",
+ "authorize_scopes": "openid email profile",
+ })
+ redirect = _oidc_federation_redirect(cid)
+ assert redirect.code == 302
+ location = redirect.headers.get("Location", "")
+ assert location.startswith(f"{issuer}/o/oauth2/v2/auth?")
+ relay_state = _parse_qs(urlparse(location).query)["state"][0]
+
+ try:
+ _no_redirect_opener.open(
+ f"{ENDPOINT}/oauth2/idpresponse?code=idp-issued-code&state={relay_state}")
+ assert False, "Expected 302 back to the app"
+ except urllib.error.HTTPError as e:
+ assert e.code == 302
+ assert recorded.get("path") == "/oauth2/v4/token"
+ cognito_idp.admin_get_user(UserPoolId=pid, Username="TestOIDC_user-9002")
+ finally:
+ stop()
+
+
+def test_cognito_oidc_discovery_issuer_mismatch(cognito_idp):
+ """A discovery document naming another issuer is refused (OpenID Connect
+ Discovery 1.0 §4.3), so no redirect reaches the endpoints it advertises."""
+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "ignored"})
+ port = urlparse(token_url).port
+ try:
+ _pid, cid = _setup_oidc_pool(cognito_idp, token_url, provider_details={
+ "oidc_issuer": f"http://localhost:{port}",
+ "client_id": "oidc-client-id",
+ "authorize_scopes": "openid email profile",
+ })
+ redirect = _oidc_federation_redirect(cid)
+ assert redirect.code == 400
+ assert "InvalidParameterException" in json.loads(redirect.read()).get("__type", "")
+ finally:
+ stop()
+
+
def test_cognito_oauth2_authorize_oidc_redirect(cognito_idp):
"""GET /oauth2/authorize with an OIDC identity_provider 302s to the IdP
with redirect_uri pointing at MiniStack's /oauth2/idpresponse."""