Skip to content

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

fix(cognito): resolve SAML SSO URL from MetadataFile in oauth2 authorize (#2168)

kjdevc4dc419f22f8
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 7c2e9244..7d7be2b6 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -2041,6 +2041,24 @@ def _oidc_callback_url(pool: dict) -> str:
return f"{base}/oauth2/idpresponse"
+def _saml_sso_url_from_metadata(metadata_xml: str) -> str:
+ """Return the IdP SingleSignOnService Location, preferring HTTP-Redirect; "" if unresolvable."""
+ if not metadata_xml:
+ return ""
+ try:
+ root = safe_xml_parse(metadata_xml.strip())
+ except Exception:
+ return ""
+ services = [
+ el for el in root.iter("{urn:oasis:names:tc:SAML:2.0:metadata}SingleSignOnService")
+ if el.get("Location")
+ ]
+ for el in services:
+ if el.get("Binding") == "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect":
+ return el.get("Location")
+ return services[0].get("Location") if services else ""
+
+
def _build_saml_authn_request(pool: dict, destination: str) -> str:
"""Build a minimal SAML AuthnRequest, deflate + base64-encode for HTTP-Redirect binding."""
req = Element("{urn:oasis:names:tc:SAML:2.0:protocol}AuthnRequest")
@@ -5969,11 +5987,16 @@ def _oauth2_authorize_federation(query_params):
details = provider.get("ProviderDetails", {})
if provider_type == "SAML":
- # Resolve IdP SSO URL: IDPSSOEndpoint > MetadataURL
- sso_url = details.get("IDPSSOEndpoint") or details.get("MetadataURL", "")
+ # Resolve IdP SSO URL: IDPSSOEndpoint > MetadataFile > MetadataURL.
+ # MetadataURL is used verbatim because MiniStack does not fetch remote metadata.
+ sso_url = (details.get("IDPSSOEndpoint")
+ or _saml_sso_url_from_metadata(details.get("MetadataFile", ""))
+ or details.get("MetadataURL", ""))
if not sso_url:
- return error_response_json("InvalidParameterException",
- "SAML provider has no IDPSSOEndpoint or MetadataURL.", 400)
+ return error_response_json(
+ "InvalidParameterException",
+ "SAML provider has no IDPSSOEndpoint, MetadataFile with SingleSignOnService, or MetadataURL.",
+ 400)
saml_request = _build_saml_authn_request(pool, sso_url)
redirect_url = sso_url + ("&" if "?" in sso_url else "?") + urlencode({
"SAMLRequest": saml_request,
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index f76db8f0..58bf565c 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2521,6 +2521,39 @@ def test_cognito_oauth2_authorize_saml_redirect(cognito_idp):
assert "RelayState=" in location
+def test_cognito_oauth2_authorize_saml_metadata_file(cognito_idp):
+ """MetadataFile only: SSO URL resolves from SingleSignOnService, preferring HTTP-Redirect."""
+ pid, cid = _setup_saml_pool(cognito_idp)
+ metadata = (
+ '<?xml version="1.0"?>'
+ '<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://idp.example.com/e">'
+ '<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">'
+ '<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"'
+ ' Location="https://post.example.com/sso"/>'
+ '<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"'
+ ' Location="https://redirect.example.com/sso"/>'
+ '</IDPSSODescriptor></EntityDescriptor>'
+ )
+ cognito_idp.create_identity_provider(
+ UserPoolId=pid, ProviderName="MetaSAML", ProviderType="SAML",
+ ProviderDetails={"MetadataFile": metadata},
+ )
+ url = (
+ f"{ENDPOINT}/oauth2/authorize?"
+ f"response_type=code&client_id={cid}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&identity_provider=MetaSAML&state=xyz123&scope=openid"
+ )
+ try:
+ _no_redirect_opener.open(url)
+ assert False, "Expected redirect, got 200"
+ except urllib.error.HTTPError as e:
+ assert e.code == 302, f"Expected 302, got {e.code}"
+ location = e.headers.get("Location", "")
+ assert location.startswith("https://redirect.example.com/sso?")
+ assert "SAMLRequest=" in location
+
+
def test_cognito_oauth2_authorize_invalid_client(cognito_idp):
"""GET /oauth2/authorize with unknown client_id returns 400."""
url = f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id=nonexistent&redirect_uri=http://x&identity_provider=X"