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): build federation endpoints from the user pool domain (#1407)
Temå053c51204fa9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 667a8dab..a7809d23 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed+- **Cognito — federation endpoints are built from the user pool's domain, and `CustomDomainConfig` is honored** — `CreateUserPoolDomain` accepted `CustomDomainConfig` and discarded it, always expanding `Domain` to `{Domain}.auth.{region}.amazoncognito.com`, while the SAML ACS URL and the OIDC federation callback ignored the domain entirely and were built from `MINISTACK_HOST`/`GATEWAY_PORT`. Federated sign-in therefore handed external identity providers `redirect_uri=http://localhost:4566/oauth2/idpresponse` — an address the browser cannot reach and that Google and other public IdPs reject outright for the scheme alone — so the flow died at the hop to the IdP with no way to correct it. `CustomDomainConfig` now distinguishes a custom domain (a full FQDN, served as-is and reported as `CustomDomain` on `DescribeUserPool`, fronted by a CloudFront distribution) from a prefix domain (a bare label, still expanded to the regional host), and `/saml2/idpresponse` and `/oauth2/idpresponse` — including the `AssertionConsumerServiceURL` in the generated SAML `AuthnRequest` and the `redirect_uri` replayed on the back-channel token exchange — are derived from whichever the pool has, exactly as AWS derives them. Configuring a custom domain is the same `create-user-pool-domain --custom-domain-config CertificateArn=...` call you would make against AWS; the certificate is recorded, not served, since TLS for a custom domain is terminated by whatever fronts it (nginx, an ALB, CloudFront) and proxied to the gateway. A pool holds one domain of each kind independently, a `CustomDomainConfig` without a `CertificateArn` is a `InvalidParameterException`, and a pool with no domain still falls back to the local gateway, so existing setups are unchanged.+## [1.4.18] — 2026-08-16### Addeddiff --git a/README.md b/README.mdindex 00dc31c3..cc298882 100644--- a/README.md+++ b/README.md@@ -573,7 +573,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here || **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here || **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |-| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, CreateResourceServer, UpdateResourceServer, DescribeResourceServer, DeleteResourceServer, ListResourceServers, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |+| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, CreateResourceServer, UpdateResourceServer, DescribeResourceServer, DeleteResourceServer, ListResourceServers, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory; **user pool domains**: `CreateUserPoolDomain` with `CustomDomainConfig` registers a custom domain served on its own FQDN (without it, `Domain` is a prefix expanded to `{prefix}.auth.{region}.amazoncognito.com`), and the SAML ACS URL and OIDC federation callback are built from it — set one when MiniStack is reached through an external TLS terminator, so external IdPs get a reachable `https://{domain}/oauth2/idpresponse` instead of the internal gateway address || **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here || **AppSync** | **GraphQL APIs**: CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL queries/mutations execute against DynamoDB resolvers; Lambda resolvers supported. Event APIs support AWS-shaped `/v2/apis` management, `/v1/apis/{apiId}/apikeys` API-key operations, `POST /event` on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket flows with API-key and Lambda-authorizer checks || **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible |diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 0a1f7a33..d28bef07 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -1529,27 +1529,55 @@ def _invoke_verify_auth_challenge_trigger(pool_id: str, client_id: str, username# SAML / OAuth2 helpers# ----------------------------------------------------------------------------def _acs_url() -> str:- """Assertion Consumer Service URL for SAML responses."""- return f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}/saml2/idpresponse"+def _pool_domain_base_url(pool: dict) -> str:+ """Public base URL of the user pool's Cognito domain, or "" when it has none.++ A custom domain (one created with `CustomDomainConfig`) is served on its own+ FQDN; a prefix domain expands to the regional Cognito host. This is how AWS+ builds the federation endpoints — from the configured domain, not from the+ request headers.++ Both forms are `https://`, as on AWS. MiniStack does not itself terminate TLS+ for them: a custom domain is expected to be fronted by whatever terminates it+ externally (nginx, an ALB, CloudFront) and proxied back to the gateway, which+ is exactly the topology the domain exists to describe. The certificate named+ in `CustomDomainConfig.CertificateArn` is recorded, never served.+ """+ if pool.get("CustomDomain"):+ return f"https://{pool['CustomDomain']}"+ if pool.get("Domain"):+ return f"https://{pool['Domain']}.auth.{_pool_region(pool.get('Id', ''))}.amazoncognito.com"+ return ""++def _acs_url(pool: dict) -> str:+ """Assertion Consumer Service URL for SAML responses.-def _oidc_callback_url() -> str:+ AWS serves this at `https://{user pool domain}/saml2/idpresponse`. A pool with+ no domain configured falls back to the local gateway, which is all a+ non-federated setup ever needs.+ """+ base = _pool_domain_base_url(pool) or f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}"+ return f"{base}/saml2/idpresponse"+++def _oidc_callback_url(pool: dict) -> str:"""OIDC callback URL — external OIDC IdPs redirect back here with `code`+`state`."""- return f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}/oauth2/idpresponse"+ base = _pool_domain_base_url(pool) or f"http://{_MINISTACK_HOST}:{_MINISTACK_PORT}"+ return f"{base}/oauth2/idpresponse"-def _build_saml_authn_request(pool_id: str, destination: str) -> str:+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")req.set("ID", "_" + new_uuid())req.set("Version", "2.0")req.set("IssueInstant", datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))- req.set("AssertionConsumerServiceURL", _acs_url())+ req.set("AssertionConsumerServiceURL", _acs_url(pool))req.set("Destination", destination)req.set("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")issuer = SubElement(req, "{urn:oasis:names:tc:SAML:2.0:assertion}Issuer")- issuer.text = f"urn:amazon:cognito:sp:{pool_id}"+ issuer.text = f"urn:amazon:cognito:sp:{pool.get('Id', '')}"xml_bytes = xml_tostring(req, encoding="unicode").encode("utf-8")# Raw deflate (strip zlib header/checksum) per SAML HTTP-Redirect bindingdeflated = zlib.compress(xml_bytes)[2:-4]@@ -1973,6 +2001,7 @@ def _create_user_pool(data):"DeletionProtection": data.get("DeletionProtection", "INACTIVE"),"LambdaConfig": data.get("LambdaConfig", {}),"Domain": None,+ "CustomDomain": None,"_clients": {},"_users": {},"_groups": {},@@ -1997,8 +2026,9 @@ def _delete_user_pool(data):pool, err = _resolve_pool(pid)if err:return err- if pool.get("Domain"):- _pool_domain_map.pop(pool["Domain"], None)+ for configured in (pool.get("Domain"), pool.get("CustomDomain")):+ if configured:+ _pool_domain_map.pop(configured, None)del _user_pools[pid]return json_response({})@@ -3859,6 +3889,16 @@ def _list_users_in_group(data):# DOMAIN# ===========================================================================+def _cloudfront_domain(domain: str) -> str:+ """Deterministic CloudFront distribution domain fronting a custom domain."""+ return f"d{hashlib.sha256(domain.encode()).hexdigest()[:13]}.cloudfront.net"+++def _prefix_domain_host(domain: str, pid: str) -> str:+ """Regional Cognito host a prefix domain expands to."""+ return f"{domain}.auth.{_pool_region(pid)}.amazoncognito.com"++def _create_user_pool_domain(data):pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)@@ -3869,9 +3909,24 @@ def _create_user_pool_domain(data):return error_response_json("InvalidParameterException", "Domain is required.", 400)if domain in _pool_domain_map:return error_response_json("InvalidParameterException", f"Domain {domain} already exists.", 400)- pool["Domain"] = domain+ # CustomDomainConfig is what separates the two kinds of domain: supplied means+ # `Domain` is a full FQDN served as-is, omitted means it is a bare prefix AWS+ # expands to {prefix}.auth.{region}.amazoncognito.com. A pool may hold one of+ # each, so they are stored in separate fields.+ custom_config = data.get("CustomDomainConfig")+ if custom_config is not None:+ if not isinstance(custom_config, dict) or not custom_config.get("CertificateArn"):+ return error_response_json(+ "InvalidParameterException",+ "CustomDomainConfig must specify a CertificateArn.", 400)+ pool["CustomDomain"] = domain+ pool["_custom_domain_config"] = custom_config+ cloudfront = _cloudfront_domain(domain)+ else:+ pool["Domain"] = domain+ cloudfront = _prefix_domain_host(domain, pid)_pool_domain_map[domain] = pid- return json_response({"CloudFrontDomain": f"{domain}.auth.{_pool_region(pid)}.amazoncognito.com"})+ return json_response({"CloudFrontDomain": cloudfront})def _delete_user_pool_domain(data):@@ -3881,7 +3936,11 @@ def _delete_user_pool_domain(data):return errdomain = data.get("Domain")_pool_domain_map.pop(domain, None)- pool["Domain"] = None+ if domain and pool.get("CustomDomain") == domain:+ pool["CustomDomain"] = None+ pool.pop("_custom_domain_config", None)+ else:+ pool["Domain"] = Nonereturn json_response({})@@ -3891,16 +3950,18 @@ def _describe_user_pool_domain(data):if not pid:return json_response({"DomainDescription": {}})pool = _user_pools.get(pid, {})+ is_custom = pool.get("CustomDomain") == domainreturn json_response({"DomainDescription": {"UserPoolId": pid,"AWSAccountId": get_account_id(),"Domain": domain,"S3Bucket": "",- "CloudFrontDistribution": f"{domain}.auth.{_pool_region(pid)}.amazoncognito.com",+ "CloudFrontDistribution": (_cloudfront_domain(domain) if is_custom+ else _prefix_domain_host(domain, pid)),"Version": "1","Status": "ACTIVE",- "CustomDomainConfig": {},+ "CustomDomainConfig": pool.get("_custom_domain_config", {}) if is_custom else {},}})@@ -4465,7 +4526,7 @@ def _oauth2_authorize_federation(query_params):if not sso_url:return error_response_json("InvalidParameterException","SAML provider has no IDPSSOEndpoint or MetadataURL.", 400)- saml_request = _build_saml_authn_request(pool_id, sso_url)+ saml_request = _build_saml_authn_request(pool, sso_url)redirect_url = sso_url + ("&" if "?" in sso_url else "?") + urlencode({"SAMLRequest": saml_request,"RelayState": relay_key,@@ -4481,7 +4542,7 @@ def _oauth2_authorize_federation(query_params):redirect_url = authorize_url + ("&" if "?" in authorize_url else "?") + urlencode({"response_type": response_type or "code","client_id": oidc_client_id,- "redirect_uri": _oidc_callback_url(),+ "redirect_uri": _oidc_callback_url(pool),"scope": details.get("authorize_scopes", scope),"state": relay_key,})@@ -4783,7 +4844,7 @@ def _oauth2_idp_response(method, body, query_params):token_body = urlencode({"grant_type": "authorization_code","code": code,- "redirect_uri": _oidc_callback_url(),+ "redirect_uri": _oidc_callback_url(pool),"client_id": oidc_client_id,"client_secret": oidc_client_secret,}).encode("ascii")diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 88711261..e88d20ba 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -10,6 +10,7 @@ import urllib.errorimport urllib.requestimport uuid as _uuid_modimport zipfile+import zlibfrom urllib.parse import parse_qs as _parse_qsfrom urllib.parse import urlencode as _urlencodefrom urllib.parse import urlparse@@ -7076,3 +7077,195 @@ def test_custom_auth_admin_first_create_receives_empty_session(cognito_idp, lam)ChallengeResponses={"ANSWER": "123456", "USERNAME": "[email protected]"},)assert "AuthenticationResult" in step3+++# ===========================================================================+# CUSTOM USER POOL DOMAINS+#+# The SAML ACS URL and the OIDC federation callback are built from the pool's+# configured domain, the way AWS does it — not from an env var and not from the+# request's Host header. A custom domain is `https://` because TLS for it is+# terminated externally (nginx, an ALB, CloudFront) and proxied to the gateway;+# MiniStack records the certificate but never serves it.+# ===========================================================================++_CUSTOM_CERT_ARN = (+ "arn:aws:acm:us-east-1:000000000000:certificate/"+ "11111111-2222-3333-4444-555555555555"+)+++def _pool_unique_domain(pid, label="auth"):+ """A domain unique to this pool — _pool_domain_map outlives a single test."""+ return f"{label}.{pid.split('_', 1)[1].lower()}.example.com"+++def test_cognito_custom_domain_create_and_describe(cognito_idp):+ """CustomDomainConfig marks the domain custom: served as-is, fronted by CloudFront."""+ pid = cognito_idp.create_user_pool(PoolName="CustomDomainPool")["UserPool"]["Id"]+ domain = _pool_unique_domain(pid)+ resp = cognito_idp.create_user_pool_domain(+ UserPoolId=pid, Domain=domain,+ CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN},+ )+ # A custom domain gets a CloudFront distribution, never the regional prefix host.+ assert resp["CloudFrontDomain"].endswith(".cloudfront.net"), resp["CloudFrontDomain"]+ assert ".amazoncognito.com" not in resp["CloudFrontDomain"]++ dd = cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]+ assert dd["UserPoolId"] == pid+ assert dd["Status"] == "ACTIVE"+ assert dd["CustomDomainConfig"] == {"CertificateArn": _CUSTOM_CERT_ARN}+ assert dd["CloudFrontDistribution"] == resp["CloudFrontDomain"]++ # AWS surfaces a custom domain as `CustomDomain`; `Domain` stays the prefix slot.+ pool = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]+ assert pool.get("CustomDomain") == domain+ assert not pool.get("Domain")+++def test_cognito_prefix_domain_unchanged_by_custom_domain_support(cognito_idp):+ """Regression: no CustomDomainConfig still means a prefix domain that expands."""+ pid = cognito_idp.create_user_pool(PoolName="PrefixDomainPool")["UserPool"]["Id"]+ domain = f"prefix-{pid.split('_', 1)[1].lower()}"+ resp = cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=domain)+ assert resp["CloudFrontDomain"] == f"{domain}.auth.us-east-1.amazoncognito.com"++ dd = cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]+ assert dd["CloudFrontDistribution"] == f"{domain}.auth.us-east-1.amazoncognito.com"+ assert dd["CustomDomainConfig"] == {}++ pool = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]+ assert pool.get("Domain") == domain+ assert not pool.get("CustomDomain")+++def test_cognito_custom_domain_requires_certificate_arn(cognito_idp):+ """A CustomDomainConfig carrying no CertificateArn is rejected, as on AWS.++ Sent raw: botocore enforces the member's 20-char minimum client-side, so this+ only reaches the server from a hand-rolled caller or another SDK. Rejecting it+ keeps a malformed body from being stored as a usable custom domain.+ """+ pid = cognito_idp.create_user_pool(PoolName="NoCertPool")["UserPool"]["Id"]+ for bad_config in ({}, {"CertificateArn": ""}, "not-a-struct"):+ request = urllib.request.Request(+ ENDPOINT,+ data=json.dumps({+ "UserPoolId": pid,+ "Domain": _pool_unique_domain(pid, "nocert"),+ "CustomDomainConfig": bad_config,+ }).encode(),+ headers={+ "Content-Type": "application/x-amz-json-1.1",+ "X-Amz-Target": "AWSCognitoIdentityProviderService.CreateUserPoolDomain",+ },+ method="POST",+ )+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(request, timeout=10)+ assert exc.value.code == 400+ assert json.loads(exc.value.read())["__type"].endswith("InvalidParameterException")++ # Nothing was registered, so the domain is still free.+ assert cognito_idp.describe_user_pool_domain(+ Domain=_pool_unique_domain(pid, "nocert"))["DomainDescription"] == {}+++def test_cognito_pool_holds_prefix_and_custom_domain_independently(cognito_idp):+ """A pool may have both; deleting one must not clear the other."""+ pid = cognito_idp.create_user_pool(PoolName="BothDomainsPool")["UserPool"]["Id"]+ prefix = f"both-{pid.split('_', 1)[1].lower()}"+ custom = _pool_unique_domain(pid, "both")+ cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=prefix)+ cognito_idp.create_user_pool_domain(+ UserPoolId=pid, Domain=custom,+ CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN},+ )++ cognito_idp.delete_user_pool_domain(UserPoolId=pid, Domain=custom)+ pool = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]+ assert not pool.get("CustomDomain")+ assert pool.get("Domain") == prefix, "deleting the custom domain dropped the prefix one"+ assert cognito_idp.describe_user_pool_domain(Domain=custom)["DomainDescription"] == {}+ assert cognito_idp.describe_user_pool_domain(+ Domain=prefix)["DomainDescription"]["UserPoolId"] == pid+++def test_cognito_federation_urls_follow_pool_domain():+ """The ACS / OIDC-callback base is the pool's domain, with the gateway as fallback."""+ mod = _cognito_module()++ # No domain configured — unchanged behaviour, the local gateway.+ bare = {"Id": "us-east-1_abc123"}+ assert mod._acs_url(bare) == f"{_advertised_endpoint()}/saml2/idpresponse"+ assert mod._oidc_callback_url(bare) == f"{_advertised_endpoint()}/oauth2/idpresponse"++ # Prefix domain — expands to the regional host, region read from the pool id.+ prefix = {"Id": "eu-central-1_abc123", "Domain": "my-prefix"}+ assert mod._oidc_callback_url(prefix) == (+ "https://my-prefix.auth.eu-central-1.amazoncognito.com/oauth2/idpresponse")++ # Custom domain wins over the prefix, and carries no port.+ custom = {"Id": "us-east-1_abc123", "Domain": "my-prefix",+ "CustomDomain": "auth.example.com"}+ assert mod._acs_url(custom) == "https://auth.example.com/saml2/idpresponse"+ assert mod._oidc_callback_url(custom) == "https://auth.example.com/oauth2/idpresponse"+++def test_cognito_oidc_authorize_redirect_uri_uses_custom_domain(cognito_idp):+ """The redirect_uri handed to an external IdP is the pool's custom domain.++ This is the flow that fails behind an external TLS terminator when the URL is+ built from the internal host: a public IdP rejects `http://localhost:4566/...`.+ """+ token_url, _recorded, stop = _start_fake_oidc_idp({"sub": "ignored"})+ try:+ pid, cid = _setup_oidc_pool(cognito_idp, token_url)+ domain = _pool_unique_domain(pid, "oidc")+ cognito_idp.create_user_pool_domain(+ UserPoolId=pid, Domain=domain,+ CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN},+ )+ 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"+ )+ 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", "")+ qs = _parse_qs(urlparse(location).query)+ assert qs["redirect_uri"] == [f"https://{domain}/oauth2/idpresponse"]+ finally:+ stop()+++def test_cognito_saml_authn_request_acs_uses_custom_domain(cognito_idp):+ """The AuthnRequest's AssertionConsumerServiceURL follows the custom domain."""+ pid, cid = _setup_saml_pool(cognito_idp)+ domain = _pool_unique_domain(pid, "saml")+ cognito_idp.create_user_pool_domain(+ UserPoolId=pid, Domain=domain,+ CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN},+ )+ url = (+ f"{ENDPOINT}/oauth2/authorize?"+ f"response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback"+ f"&identity_provider=TestSAML&state=mystate&scope=openid"+ )+ try:+ _no_redirect_opener.open(url)+ assert False, "Expected 302"+ except urllib.error.HTTPError as e:+ location = e.headers.get("Location", "")+ saml_request = _parse_qs(urlparse(location).query)["SAMLRequest"][0]+ # Raw deflate per the SAML HTTP-Redirect binding.+ xml = zlib.decompress(base64.b64decode(saml_request), -15).decode()+ assert f'AssertionConsumerServiceURL="https://{domain}/saml2/idpresponse"' in xml+ assert f'urn:amazon:cognito:sp:{pid}' in xml