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
feat(cognito): add UpdateUserPoolDomain and update domains in place (#2181)
iot-rocket332bee0a0d39
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8ebb39eb..0196427c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **Cognito — `UpdateUserPoolDomain` and `AWS::Cognito::UserPoolDomain` stack updates** — `UpdateUserPoolDomain` was an unknown action; it now changes a domain's `ManagedLoginVersion` and a custom domain's certificate, `CreateUserPoolDomain` and `DescribeUserPoolDomain` return the version, and a second prefix domain on a pool is refused as on AWS. A stack update applies `ManagedLoginVersion` and `CustomDomainConfig` through it instead of running the create again, a `Domain` or `UserPoolId` change replaces the domain, the create keeps `CustomDomainConfig`, `Ref` returns the domain name and `Fn::GetAtt` returns `CloudFrontDistribution`. Contributed by @iot-rocket.- **IoT — provisioning template versions** — `CreateProvisioningTemplateVersion`, `ListProvisioningTemplateVersions`, `DescribeProvisioningTemplateVersion` and `DeleteProvisioningTemplateVersion` answered `Unsupported IoT path` and `UpdateProvisioningTemplate` refused every `defaultVersionId` but 1; a template now keeps up to five versions whose ids are never reused, `setAsDefault` and `defaultVersionId` choose the version that `DescribeProvisioningTemplate` returns and `RegisterThing` applies, the default version cannot be deleted, and an `AWS::IoT::ProvisioningTemplate` whose `TemplateBody` changes gets a new default version (deleting the oldest at the limit), all with AWS's errors, including its message for a body that is not JSON. Contributed by @iot-rocket.- **IoT — pre-provisioning hook** — `RegisterThing` over MQTT now invokes the template's `preProvisioningHook` Lambda before the template is resolved and applies its answer the way AWS does: `parameterOverrides` are merged into the device's parameters, `allowProvisioning: false` is rejected as `AccessDenied`, and a function that fails, answers in another shape, takes longer than six seconds or may not be invoked gets AWS's `InvocationError` or `InvalidResult`. `CreateProvisioningTemplate` and `UpdateProvisioningTemplate` check the hook like AWS (a Lambda function ARN, payload version `2020-04-01`, no hook on JITP templates, and an invoke permission for `iot.amazonaws.com` that covers the template) and store the default payload version. Contributed by @iot-rocket.- **IoT — fleet provisioning by claim** — `CreateProvisioningClaim` issues a five-minute claim certificate that the mTLS listener accepts until it expires, and a device connected with it (or with any registered certificate) gets a certificate from `$aws/certificates/create/json` and registers itself through `$aws/provisioning-templates/<name>/provision/json`: the template's parameters, `Ref` and `Fn::Join` are resolved, the thing is created or checked against its `OverrideSettings`, and the certificate is activated and attached to the thing and the template's policies, with AWS's replies and rejections on the requesting connection; with `AUTH=true` a claim connection is limited to the certificate topics and its own template's, as on AWS. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex b538a205..2d68a50a 100644--- a/README.md+++ b/README.md@@ -541,7 +541,7 @@ subnet = ec2.create_subnet(| `AWS::Cognito::UserPoolResourceServer` | Identifier | — || `AWS::Cognito::IdentityPool` | Pool ID | — || `AWS::Cognito::IdentityPoolPrincipalTag` | `<pool ID>\|<provider name>` | — |-| `AWS::Cognito::UserPoolDomain` | Domain | — |+| `AWS::Cognito::UserPoolDomain` | Domain | CloudFrontDistribution || `AWS::IoT::Thing` | Thing name | Arn, Id || `AWS::IoT::Certificate` | Certificate id | Arn, Id || `AWS::IoT::ThingPrincipalAttachment` | `{ThingName}\|{Principal}` | None |@@ -636,7 +636,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, PutFileSystemPolicy, DescribeFileSystemPolicy, DeleteFileSystemPolicy, UpdateFileSystemProtection, CreateReplicationConfiguration, DescribeReplicationConfigurations, DeleteReplicationConfiguration, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist or it is in a replication configuration; `CreateMountTarget` checks the subnet, security groups, zone and address; replication creates records only, nothing is copied; CFN `AWS::EFS::FileSystem`, `MountTarget` and `AccessPoint` supported || **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, SetUICustomization, GetUICustomization, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier, AdminLinkProviderForUser, AdminDisableProviderForUser, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, SetPrincipalTagAttributeMap, GetPrincipalTagAttributeMap, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (authorization_code, refresh_token, client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); `USER_SRP_AUTH` runs real SRP: `PASSWORD_VERIFIER` checks the client's proof against the stored password; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); `AdminCreateUser` invokes the pool's `CustomMessage` trigger for the invitation; session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP verifies for real: the `AssociateSoftwareToken` secret is stored and checked with RFC 6238 (wrong code = `EnableSoftwareTokenMFAException` on verify, `CodeMismatchException` on the SOFTWARE_TOKEN_MFA challenge); 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; **federated user linking**: `AdminLinkProviderForUser` links an external identity to an existing profile before its first sign-in, so that sign-in resolves to the linked profile instead of minting a second `{Provider}_id` one, and the profile carries the `identities` attribute (also an ID-token claim); **`PreventUserExistenceErrors=ENABLED`** hides an unknown user across the auth flows (generic `NotAuthorizedException` incl. at `RespondToAuthChallenge`, simulated `CodeDeliveryDetails` with the masked `Destination` on `ForgotPassword`/`ResendConfirmationCode`, `CodeMismatchException` on `ConfirmForgotPassword`; the API default is `LEGACY`, as on AWS); `AdminListUserAuthEvents` requires `UserPoolAddOns.AdvancedSecurityMode` != `OFF`, else `UserPoolAddOnNotEnabledException` as on AWS — events themselves are never recorded, so the answer is always an empty list; **principal tag attribute maps** are stored and reported verbatim per identity provider, and a provider that was never configured answers `ResourceNotFoundException` (`No Principal Tags configured for Provider {name}`) as on AWS — `UseDefaults` round-trips but is never expanded into a tag map, since AWS applies the default claim mapping when it vends credentials, and `GetCredentialsForIdentity` registers its credentials as an STS session (GetCallerIdentity reports the pool role assumed as `CognitoIdentityCredentials`, and `AUTH=true` evaluates the session like any AssumeRole), though principal tags still never reach a session's `aws:PrincipalTag` policy context |+| **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, UpdateUserPoolDomain, SetUICustomization, GetUICustomization, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier, AdminLinkProviderForUser, AdminDisableProviderForUser, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, SetPrincipalTagAttributeMap, GetPrincipalTagAttributeMap, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (authorization_code, refresh_token, client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); `USER_SRP_AUTH` runs real SRP: `PASSWORD_VERIFIER` checks the client's proof against the stored password; **CUSTOM_AUTH flow** wired through the configured `DefineAuthChallenge` / `CreateAuthChallenge` / `VerifyAuthChallengeResponse` Lambda triggers (passwordless / magic-link / SMS-OTP); `AdminCreateUser` invokes the pool's `CustomMessage` trigger for the invitation; session TTL honors `AuthSessionValidity`, capped at 3 answered rounds per AWS; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP verifies for real: the `AssociateSoftwareToken` secret is stored and checked with RFC 6238 (wrong code = `EnableSoftwareTokenMFAException` on verify, `CodeMismatchException` on the SOFTWARE_TOKEN_MFA challenge); 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; **federated user linking**: `AdminLinkProviderForUser` links an external identity to an existing profile before its first sign-in, so that sign-in resolves to the linked profile instead of minting a second `{Provider}_id` one, and the profile carries the `identities` attribute (also an ID-token claim); **`PreventUserExistenceErrors=ENABLED`** hides an unknown user across the auth flows (generic `NotAuthorizedException` incl. at `RespondToAuthChallenge`, simulated `CodeDeliveryDetails` with the masked `Destination` on `ForgotPassword`/`ResendConfirmationCode`, `CodeMismatchException` on `ConfirmForgotPassword`; the API default is `LEGACY`, as on AWS); `AdminListUserAuthEvents` requires `UserPoolAddOns.AdvancedSecurityMode` != `OFF`, else `UserPoolAddOnNotEnabledException` as on AWS — events themselves are never recorded, so the answer is always an empty list; **principal tag attribute maps** are stored and reported verbatim per identity provider, and a provider that was never configured answers `ResourceNotFoundException` (`No Principal Tags configured for Provider {name}`) as on AWS — `UseDefaults` round-trips but is never expanded into a tag map, since AWS applies the default claim mapping when it vends credentials, and `GetCredentialsForIdentity` registers its credentials as an STS session (GetCallerIdentity reports the pool role assumed as `CognitoIdentityCredentials`, and `AUTH=true` evaluates the session like any AssumeRole), though principal tags still never reach a session's `aws:PrincipalTag` policy context || **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, UpdateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, UpdateDataSource, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, UpdateResolver, DeleteResolver, CreateFunction, GetFunction, ListFunctions, UpdateFunction, DeleteFunction, CreateType, GetType, ListTypes, UpdateType, StartSchemaCreation, GetSchemaCreationStatus, GetIntrospectionSchema, PutGraphqlApiEnvironmentVariables, GetGraphqlApiEnvironmentVariables, CreateApiCache, GetApiCache, UpdateApiCache, DeleteApiCache, FlushApiCache, EvaluateCode, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL execution goes through `graphql-core` when the API has a schema (parse, validate, execute; an AppSync prelude supplies the `AWS*` scalars and `@aws_*` directives; a schemaless API keeps a lenient path); **`APPSYNC_JS` resolvers execute** — unit and pipeline, `util`/`runtime`/`extensions` globals, the `@aws-appsync/utils/dynamodb` helpers, `NONE`/`HTTP`/`AMAZON_DYNAMODB`/`AWS_LAMBDA` data sources — on a pool of warm Node workers (one evaluation in flight per worker, 30s bound with kill-and-respawn, heap cap; reuses the image's Node, no new dependency); `GetIntrospectionSchema` serves SDL or a real `format=JSON` introspection document; the API cache is honored by the data plane under `FULL_REQUEST_CACHING` and `PER_RESOLVER_CACHING`; a data-plane request satisfying none of the API's auth modes answers `401 UnauthorizedException`, as on AWS (credentials are not verified — only their absence is refused). 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/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 6afae716..873458ae 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -685,6 +685,9 @@ _CUSTOM_NAME_REPLACEMENT = {"name": "Identifier","requires_replacement": _requires_replacement_cognito_resource_server,},+ # Domain is required, so a pool move under the same Domain fails on the+ # name, as the replacement's CreateUserPoolDomain does.+ "AWS::Cognito::UserPoolDomain": {"name": "Domain", "exists": "Domain already exists"},"AWS::Pipes::Pipe": {"name": "Name","requires_replacement": _requires_replacement_pipes,@@ -7131,25 +7134,50 @@ def _cognito_identity_pool_delete(physical_id, props):# --- Cognito UserPoolDomain ---+def _cognito_user_pool_domain_request(props):+ """The CreateUserPoolDomain / UpdateUserPoolDomain request a template declares."""+ request = {"UserPoolId": props.get("UserPoolId", ""), "Domain": props.get("Domain", "")}+ for key in ("CustomDomainConfig", "Routing"):+ if key in props:+ request[key] = props[key]+ if "ManagedLoginVersion" in props:+ request["ManagedLoginVersion"] = int(props["ManagedLoginVersion"])+ return request+++def _cognito_user_pool_domain_attributes(domain):+ _, _, body = _cognito._describe_user_pool_domain({"Domain": domain})+ description = json.loads(body)["DomainDescription"]+ return {"CloudFrontDistribution": description.get("CloudFrontDistribution", "")}++def _cognito_user_pool_domain_create(logical_id, props, stack_name):pid = props.get("UserPoolId", "")domain = props.get("Domain", "")pool = _cognito._user_pools.get(pid)if not pool:raise ValueError(f"UserPool {pid} not found for UserPoolDomain")- pool["Domain"] = domain- _cognito._pool_domain_map[domain] = pid- phys_id = f"{pid}-domain-{domain}"- return phys_id, {}+ status, _, body = _cognito._create_user_pool_domain(_cognito_user_pool_domain_request(props))+ if status >= 400:+ raise ValueError(f"AWS::Cognito::UserPoolDomain create failed: {body!r}")+ # Ref returns the domain name.+ return domain, _cognito_user_pool_domain_attributes(domain)+++def _cognito_user_pool_domain_update(physical_id, old_props, new_props, stack_name):+ """Apply CustomDomainConfig and ManagedLoginVersion through UpdateUserPoolDomain, which refuses Routing."""+ request = _cognito_user_pool_domain_request(new_props)+ status, _, body = _cognito._update_user_pool_domain(request)+ if status >= 400:+ raise ValueError(f"AWS::Cognito::UserPoolDomain update failed: {body!r}")+ return physical_id, _cognito_user_pool_domain_attributes(request["Domain"])def _cognito_user_pool_domain_delete(physical_id, props):domain = props.get("Domain", "")- pid = _cognito._pool_domain_map.pop(domain, None)- if pid:- pool = _cognito._user_pools.get(pid)- if pool:- pool["Domain"] = None+ pid = props.get("UserPoolId", "")+ if _cognito._pool_domain_map.get(domain) == pid:+ _cognito._delete_user_pool_domain({"UserPoolId": pid, "Domain": domain})# ===========================================================================@@ -14192,6 +14220,7 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::StepFunctions::StateMachine": ("StateMachineName", "StateMachineType"),"AWS::Cognito::UserPoolGroup": ("GroupName", "UserPoolId"),"AWS::Cognito::UserPoolResourceServer": ("Identifier", "UserPoolId"),+ "AWS::Cognito::UserPoolDomain": ("Domain", "UserPoolId"),"AWS::Scheduler::ScheduleGroup": ("Name",),"AWS::IoT::Thing": ("ThingName",),"AWS::IoT::Certificate": (@@ -14770,7 +14799,11 @@ _RESOURCE_HANDLERS = {"delete": _cognito_identity_pool_delete,"import": _cognito_identity_pool_import,},- "AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},+ "AWS::Cognito::UserPoolDomain": {+ "create": _cognito_user_pool_domain_create,+ "update": _cognito_user_pool_domain_update,+ "delete": _cognito_user_pool_domain_delete,+ },"AWS::ECR::Repository": {"create": _ecr_repo_create,"update": _ecr_repo_update,diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex e49c3a70..d72ab824 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -25,6 +25,7 @@ User Pools operations:AdminResetUserPassword, AdminUserGlobalSignOut,GlobalSignOut, RevokeToken,CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain,+ UpdateUserPoolDomain,CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider,DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier,AdminLinkProviderForUser, AdminDisableProviderForUser,@@ -2602,6 +2603,7 @@ async def _dispatch_idp(action: str, data: dict):"CreateUserPoolDomain": _create_user_pool_domain,"DeleteUserPoolDomain": _delete_user_pool_domain,"DescribeUserPoolDomain": _describe_user_pool_domain,+ "UpdateUserPoolDomain": _update_user_pool_domain,# Identity Providers"CreateIdentityProvider": _create_identity_provider,"DescribeIdentityProvider": _describe_identity_provider,@@ -5057,6 +5059,11 @@ def _cloudfront_domain(domain: str) -> str:return f"d{hashlib.sha256(domain.encode()).hexdigest()[:13]}.cloudfront.net"+def _managed_login_version(requested, current):+ """The domain's managed login version: a value other than 1 or 2 keeps the current one."""+ return requested if requested in (1, 2) else current++def _create_user_pool_domain(data):pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)@@ -5072,6 +5079,9 @@ def _create_user_pool_domain(data):# 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 None and pool.get("Domain"):+ return error_response_json(+ "InvalidParameterException", "User pool already has a domain configured.", 400)if custom_config is not None:if not isinstance(custom_config, dict) or not custom_config.get("CertificateArn"):return error_response_json(@@ -5086,7 +5096,59 @@ def _create_user_pool_domain(data):# CNAME to, so AWS returns a null CloudFrontDomain for it — omit it.cloudfront = None_pool_domain_map[domain] = pid- return json_response({"CloudFrontDomain": cloudfront} if cloudfront else {})+ version = _managed_login_version(data.get("ManagedLoginVersion"), 1)+ pool.setdefault("_managed_login_versions", {})[domain] = version+ resp = {"ManagedLoginVersion": version}+ if cloudfront:+ resp["CloudFrontDomain"] = cloudfront+ return json_response(resp)+++def _update_user_pool_domain(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ domain = data.get("Domain")+ owner = _pool_domain_map.get(domain)+ if owner is None:+ return error_response_json("ResourceNotFoundException", "User pool domain was not found.", 400)+ if owner != pid:+ return error_response_json(+ "InvalidParameterException", "The domain is not configured for this user pool.", 400)+ is_custom = pool.get("CustomDomain") == domain+ custom_config = data.get("CustomDomainConfig")+ if custom_config is not None:+ if not is_custom:+ return error_response_json(+ "InvalidParameterException", "Cannot convert prefix domain to custom domain.", 400)+ if not isinstance(custom_config, dict) or not custom_config.get("CertificateArn"):+ return error_response_json(+ "InvalidParameterException",+ "CustomDomainConfig must specify a CertificateArn.", 400)+ versions = pool.setdefault("_managed_login_versions", {})+ version = _managed_login_version(data.get("ManagedLoginVersion"), versions.get(domain, 1))+ routing = data.get("Routing")+ if routing:+ if version != 2:+ return error_response_json(+ "InvalidParameterException", "Routing field is not supported for Hosted UI (classic)", 400)+ # Failover routes to a replica region, and no user pool here has one.+ region = (routing.get("Failover") or {}).get("SecondaryRegion")+ if region == _pool_region(pid):+ return error_response_json(+ "InvalidParameterException",+ "Routing field can only be configured when replica status is one of: "+ "ACTIVE, CREATING, INACTIVE. Current status: null", 400)+ return error_response_json(+ "InvalidParameterException", f"Region {region} is not active for the user pool", 400)+ versions[domain] = version+ resp = {"ManagedLoginVersion": version}+ if is_custom:+ if custom_config is not None:+ pool["_custom_domain_config"] = custom_config+ resp["CloudFrontDomain"] = _cloudfront_domain(domain)+ return json_response(resp)def _delete_user_pool_domain(data):@@ -5096,6 +5158,7 @@ def _delete_user_pool_domain(data):return errdomain = data.get("Domain")_pool_domain_map.pop(domain, None)+ pool.get("_managed_login_versions", {}).pop(domain, None)if domain and pool.get("CustomDomain") == domain:pool["CustomDomain"] = Nonepool.pop("_custom_domain_config", None)@@ -5124,6 +5187,7 @@ def _describe_user_pool_domain(data):"Version": "1","Status": "ACTIVE","CustomDomainConfig": pool.get("_custom_domain_config", {}) if is_custom else {},+ "ManagedLoginVersion": pool.get("_managed_login_versions", {}).get(domain, 1),}})diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex d802e151..f593aa14 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -23252,6 +23252,175 @@ def test_cfn_cognito_resource_server_move_under_custom_name_fails_loudly(cfn, cocognito_idp.delete_user_pool(UserPoolId=pool_id)+def _cfn_user_pool_domain_template(pool_id, domain, version=None, fail=False, **props):+ props = {"UserPoolId": pool_id, "Domain": domain, **props}+ if version is not None:+ props["ManagedLoginVersion"] = version+ body = json.dumps({+ "Resources": {"Dom": {"Type": "AWS::Cognito::UserPoolDomain", "Properties": props}},+ "Outputs": {"DomRef": {"Value": {"Ref": "Dom"}}},+ })+ return _cfn_with_failing_resource(body, "Dom") if fail else body+++def _cfn_user_pool_domain(cognito_idp, domain):+ return cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]+++def test_cfn_cognito_user_pool_domain_update_in_place(cfn, cognito_idp):+ """ManagedLoginVersion changes in place, survives a rollback and stays when the template drops it."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-cog-dom-upd-{uid}"+ domain = f"cfn-dom-upd-{uid}"+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-dom-upd-{uid}")["UserPool"]["Id"]++ def update(template, status="UPDATE_COMPLETE"):+ cfn.update_stack(StackName=stack_name, TemplateBody=template)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == status, stack.get("StackStatusReason")+ assert _output(stack, "DomRef") == domain+ return _cfn_user_pool_domain(cognito_idp, domain)["ManagedLoginVersion"]++ cfn.create_stack(StackName=stack_name,+ TemplateBody=_cfn_user_pool_domain_template(pool_id, domain))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert _output(stack, "DomRef") == domain+ assert _cfn_user_pool_domain(cognito_idp, domain)["ManagedLoginVersion"] == 1++ assert update(_cfn_user_pool_domain_template(pool_id, domain, 2)) == 2+ assert update(_cfn_user_pool_domain_template(pool_id, domain, 1, fail=True),+ "UPDATE_ROLLBACK_COMPLETE") == 2+ assert update(_cfn_user_pool_domain_template(pool_id, domain)) == 2+ assert update(_cfn_user_pool_domain_template(pool_id, domain, 1)) == 1+ assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]["Domain"] == domain++ cfn.delete_stack(StackName=stack_name)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ assert _cfn_user_pool_domain(cognito_idp, domain) == {}+ assert not cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"].get("Domain")+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ cognito_idp.delete_user_pool(UserPoolId=pool_id)+++def test_cfn_cognito_user_pool_domain_custom_domain_certificate_update(cfn, cognito_idp):+ """CustomDomainConfig makes a custom domain whose certificate changes in place; GetAtt is its CloudFront target."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-cog-dom-cert-{uid}"+ domain = f"auth.{uid}.example.com"+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-dom-cert-{uid}")["UserPool"]["Id"]+ cert = "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-{}"++ def template(serial):+ body = json.loads(_cfn_user_pool_domain_template(+ pool_id, domain, CustomDomainConfig={"CertificateArn": cert.format(serial)}))+ body["Outputs"]["CloudFront"] = {"Value": {"Fn::GetAtt": ["Dom", "CloudFrontDistribution"]}}+ return json.dumps(body)++ cfn.create_stack(StackName=stack_name, TemplateBody=template("555555555555"))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ cloudfront = _output(stack, "CloudFront")+ assert cloudfront.endswith(".cloudfront.net")+ described = _cfn_user_pool_domain(cognito_idp, domain)+ assert described["CloudFrontDistribution"] == cloudfront+ assert described["CustomDomainConfig"] == {"CertificateArn": cert.format("555555555555")}+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]+ assert pool.get("CustomDomain") == domain+ assert not pool.get("Domain")++ cfn.update_stack(StackName=stack_name, TemplateBody=template("666666666666"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert _output(stack, "DomRef") == domain+ assert _output(stack, "CloudFront") == cloudfront+ assert _cfn_user_pool_domain(cognito_idp, domain)["CustomDomainConfig"] == {+ "CertificateArn": cert.format("666666666666")}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ cognito_idp.delete_user_pool(UserPoolId=pool_id)++[email protected]("change,reason", [+ ("pool", "Domain already exists"),+ ("domain", "User pool already has a domain configured."),+], ids=["pool-move-same-domain", "rename-same-pool"])+def test_cfn_cognito_user_pool_domain_replacement_refused(cfn, cognito_idp, change, reason):+ """A replacement's create fails on the kept Domain or on the pool's prefix domain, and the stack rolls back."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-cog-dom-refuse-{uid}"+ domain = f"cfn-dom-refuse-{uid}"+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-dom-a-{uid}")["UserPool"]["Id"]+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-dom-b-{uid}")["UserPool"]["Id"]+ changed = {"pool": (pool_b, domain), "domain": (pool_a, f"{domain}-new")}[change]++ cfn.create_stack(StackName=stack_name,+ TemplateBody=_cfn_user_pool_domain_template(pool_a, domain, 2))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ cfn.update_stack(StackName=stack_name,+ TemplateBody=_cfn_user_pool_domain_template(*changed, 2))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ assert reason in _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "DomRef") == domain++ kept = _cfn_user_pool_domain(cognito_idp, domain)+ assert kept["UserPoolId"] == pool_a+ assert kept["ManagedLoginVersion"] == 2+ assert cognito_idp.describe_user_pool(UserPoolId=pool_a)["UserPool"]["Domain"] == domain+ assert not cognito_idp.describe_user_pool(UserPoolId=pool_b)["UserPool"].get("Domain")+ assert _cfn_user_pool_domain(cognito_idp, f"{domain}-new") == {}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for pool_id in (pool_a, pool_b):+ cognito_idp.delete_user_pool(UserPoolId=pool_id)++[email protected]("fail", [False, True], ids=["replaced", "rolled-back"])+def test_cfn_cognito_user_pool_domain_move_and_rename_replaces(cfn, cognito_idp, fail):+ """A new Domain in another pool replaces the domain; a rollback keeps the old one and deletes the new one."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-cog-dom-move-{uid}"+ old, new = f"cfn-dom-move-{uid}", f"cfn-dom-move-{uid}-new"+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-dom-a-{uid}")["UserPool"]["Id"]+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-dom-b-{uid}")["UserPool"]["Id"]++ cfn.create_stack(StackName=stack_name,+ TemplateBody=_cfn_user_pool_domain_template(pool_a, old))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ cfn.update_stack(StackName=stack_name,+ TemplateBody=_cfn_user_pool_domain_template(pool_b, new, 2, fail=fail))+ stack = _wait_stack(cfn, stack_name)+ pools = {pool_a: cognito_idp.describe_user_pool(UserPoolId=pool_a)["UserPool"].get("Domain"),+ pool_b: cognito_idp.describe_user_pool(UserPoolId=pool_b)["UserPool"].get("Domain")}+ if fail:+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ assert _output(stack, "DomRef") == old+ assert _cfn_user_pool_domain(cognito_idp, old)["UserPoolId"] == pool_a+ assert _cfn_user_pool_domain(cognito_idp, new) == {}+ assert pools == {pool_a: old, pool_b: None}+ else:+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert _output(stack, "DomRef") == new+ created = _cfn_user_pool_domain(cognito_idp, new)+ assert (created["UserPoolId"], created["ManagedLoginVersion"]) == (pool_b, 2)+ assert _cfn_user_pool_domain(cognito_idp, old) == {}+ assert pools == {pool_a: None, pool_b: new}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for pool_id in (pool_a, pool_b):+ cognito_idp.delete_user_pool(UserPoolId=pool_id)++def test_cfn_secret_update_publishes_a_new_version(cfn, sm):"""A changed SecretString publishes a new AWSCURRENT version of the samesecret: same ARN, the first value still there as AWSPREVIOUS, and the@@ -29313,6 +29482,22 @@ def test_cognito_change_set_reports_mfa_configuration_in_place(cfn, stack):assert change["Replacement"] == "False"[email protected]("prop,value,recreation,replacement", [+ ("ManagedLoginVersion", 2, "Never", "False"),+ ("Domain", None, "Always", "True"),+])+def test_cognito_change_set_reports_user_pool_domain_replacement(cfn, cognito_idp, stack, prop, value,+ recreation, replacement):+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"+ pool_id = cognito_idp.create_user_pool(PoolName=name)["UserPool"]["Id"]+ props = {"UserPoolId": pool_id, "Domain": name}+ old = _template("AWS::Cognito::UserPoolDomain", props)+ new = _template("AWS::Cognito::UserPoolDomain", {**props, prop: value or name + "-new"})+ change = _change(cfn, stack(old), new)+ assert _requirements(change) == {prop: recreation}+ assert change["Replacement"] == replacement++_PASS = json.dumps({"StartAt": "A", "States": {"A": {"Type": "Pass", "End": True}}})_ROLE = "arn:aws:iam::000000000000:role/review"diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 88c8ef6b..8844944a 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -636,6 +636,92 @@ def test_cognito_domain_crud(cognito_idp):desc2 = cognito_idp.describe_user_pool_domain(Domain="my-test-domain")assert desc2["DomainDescription"] == {}+def test_cognito_update_user_pool_domain_managed_login_version(cognito_idp):+ """ManagedLoginVersion defaults to 1; a value other than 1 or 2, or none, keeps the current one."""+ pid = cognito_idp.create_user_pool(PoolName="DomainVersionPool")["UserPool"]["Id"]+ domain = f"mlv-{pid.split('_', 1)[1].lower()}"++ def version():+ return cognito_idp.describe_user_pool_domain(+ Domain=domain)["DomainDescription"]["ManagedLoginVersion"]++ def update(**kwargs):+ resp = cognito_idp.update_user_pool_domain(UserPoolId=pid, Domain=domain, **kwargs)+ assert "CloudFrontDomain" not in resp+ return resp["ManagedLoginVersion"]++ created = cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=domain)+ assert created["ManagedLoginVersion"] == 1+ assert version() == 1+ assert update(ManagedLoginVersion=2) == 2+ assert version() == 2+ assert update() == 2+ assert update(ManagedLoginVersion=3) == 2+ assert update(ManagedLoginVersion=0) == 2+ assert version() == 2+ assert update(ManagedLoginVersion=1) == 1+ assert version() == 1++ for requested, expected in ((2, 2), (3, 1)):+ other = cognito_idp.create_user_pool(PoolName="DomainVersionPool")["UserPool"]["Id"]+ other_domain = f"mlv-{other.split('_', 1)[1].lower()}"+ created = cognito_idp.create_user_pool_domain(+ UserPoolId=other, Domain=other_domain, ManagedLoginVersion=requested)+ assert created["ManagedLoginVersion"] == expected+ assert cognito_idp.describe_user_pool_domain(+ Domain=other_domain)["DomainDescription"]["ManagedLoginVersion"] == expected+++def test_cognito_update_user_pool_domain_refusals(cognito_idp):+ """UpdateUserPoolDomain refuses these requests and changes nothing."""+ pid = cognito_idp.create_user_pool(PoolName="DomainRefusalPool")["UserPool"]["Id"]+ other = cognito_idp.create_user_pool(PoolName="DomainRefusalPool")["UserPool"]["Id"]+ domain = f"refuse-{pid.split('_', 1)[1].lower()}"+ cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=domain)++ def refused(**kwargs):+ with pytest.raises(ClientError) as exc:+ cognito_idp.update_user_pool_domain(**{"UserPoolId": pid, "Domain": domain, **kwargs})+ return exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]++ def failover(region):+ return {"Failover": {"SecondaryRegion": region,+ "PrimaryRoute53HealthCheckId": "00000000-0000-0000-0000-000000000000"}}++ assert refused(Domain=f"{domain}-none", ManagedLoginVersion=2) == (+ "ResourceNotFoundException", "User pool domain was not found.")+ assert refused(UserPoolId=other, ManagedLoginVersion=2) == (+ "InvalidParameterException", "The domain is not configured for this user pool.")+ assert refused(CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN}) == (+ "InvalidParameterException", "Cannot convert prefix domain to custom domain.")+ assert refused(Routing=failover("eu-west-1")) == (+ "InvalidParameterException", "Routing field is not supported for Hosted UI (classic)")+ assert refused(ManagedLoginVersion=2, Routing=failover("eu-west-1")) == (+ "InvalidParameterException", "Region eu-west-1 is not active for the user pool")+ assert refused(ManagedLoginVersion=2, Routing=failover(pid.split("_", 1)[0])) == (+ "InvalidParameterException",+ "Routing field can only be configured when replica status is one of: "+ "ACTIVE, CREATING, INACTIVE. Current status: null")++ dd = cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]+ assert dd["ManagedLoginVersion"] == 1+ assert dd["CustomDomainConfig"] == {}+++def test_cognito_managed_login_version_survives_warm_boot(_enable_persistence):+ """The domain's ManagedLoginVersion lives on the pool record and survives a restart."""+ mod = _cognito_module()+ mod.reset()+ _, _, body = mod._create_user_pool({"PoolName": "MlvPersistPool"})+ pid = json.loads(body)["UserPool"]["Id"]+ mod._create_user_pool_domain({"UserPoolId": pid, "Domain": "mlv-persist", "ManagedLoginVersion": 2})++ _cognito_round_trip(mod)++ _, _, body = mod._describe_user_pool_domain({"Domain": "mlv-persist"})+ assert json.loads(body)["DomainDescription"]["ManagedLoginVersion"] == 2+ mod.reset()+def test_cognito_mfa_config(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="MfaPool")["UserPool"]["Id"]resp = cognito_idp.get_user_pool_mfa_config(UserPoolId=pid)@@ -8695,6 +8781,29 @@ def test_cognito_custom_domain_create_and_describe(cognito_idp):assert not pool.get("Domain")+def test_cognito_update_custom_domain_certificate(cognito_idp):+ """UpdateUserPoolDomain replaces a custom domain's certificate and answers its CloudFront target."""+ pid = cognito_idp.create_user_pool(PoolName="CustomDomainUpdatePool")["UserPool"]["Id"]+ domain = _pool_unique_domain(pid, "renew")+ created = cognito_idp.create_user_pool_domain(+ UserPoolId=pid, Domain=domain,+ CustomDomainConfig={"CertificateArn": _CUSTOM_CERT_ARN},+ )+ renewed = _CUSTOM_CERT_ARN.replace("555555555555", "666666666666")++ resp = cognito_idp.update_user_pool_domain(+ UserPoolId=pid, Domain=domain,+ CustomDomainConfig={"CertificateArn": renewed}, ManagedLoginVersion=2,+ )+ assert resp["CloudFrontDomain"] == created["CloudFrontDomain"]+ assert resp["ManagedLoginVersion"] == 2++ dd = cognito_idp.describe_user_pool_domain(Domain=domain)["DomainDescription"]+ assert dd["CustomDomainConfig"] == {"CertificateArn": renewed}+ assert dd["ManagedLoginVersion"] == 2+ assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"].get("CustomDomain") == 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"]@@ -8744,6 +8853,21 @@ def test_cognito_custom_domain_requires_certificate_arn(cognito_idp):Domain=_pool_unique_domain(pid, "nocert"))["DomainDescription"] == {}+def test_cognito_second_prefix_domain_is_refused(cognito_idp):+ """A pool holds one prefix domain: a second one is refused and the first stays."""+ pid = cognito_idp.create_user_pool(PoolName="SecondPrefixPool")["UserPool"]["Id"]+ suffix = pid.split("_", 1)[1].lower()+ cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=f"first-{suffix}")++ with pytest.raises(ClientError) as exc:+ cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=f"second-{suffix}")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+ assert exc.value.response["Error"]["Message"] == "User pool already has a domain configured."++ assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["Domain"] == f"first-{suffix}"+ assert cognito_idp.describe_user_pool_domain(Domain=f"second-{suffix}")["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"]