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 identity pool principal tag attribute maps (#1607)
ppettitau885eddb293cd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 600b5bc8..725d13bc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,11 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).+## [Unreleased]++### Added+- **Cognito — identity pool principal tag attribute maps** — `SetPrincipalTagAttributeMap` and `GetPrincipalTagAttributeMap` were missing, so a CDK or CloudFormation deployment declaring `AWS::Cognito::IdentityPoolPrincipalTag` rolled the stack back on an unknown resource type. The two operations now round-trip a per-provider mapping on the identity pool, verified against botocore `cognito-identity-2014-06-30`: both members are optional and are stored as sent, a provider nobody has configured answers `ResourceNotFoundException` with AWS's `No Principal Tags configured for Provider {name}` message rather than an empty mapping, and each identity provider on a pool keeps its own map. `UseDefaults` is not expanded into a tag map — AWS applies the per-provider default claim mapping when it vends credentials — and it is accepted alongside `PrincipalTags`, which is what terraform-provider-aws sends on every destroy. The CloudFormation resource provisions onto the pool, keys its physical id on the pool/provider pair so several providers coexist, applies a changed `PrincipalTags` in place, and clears the mapping on delete or on a replacement that moves the pool or provider. The mapping is stored and reported only — `GetCredentialsForIdentity` vends stub credentials without evaluating policy, so the tags never reach a session's `aws:PrincipalTag` context. State is account- and region-scoped and persisted.+## [1.5.6] — 2026-09-02### Addeddiff --git a/README.md b/README.mdindex 457f039d..04aee0ec 100644--- a/README.md+++ b/README.md@@ -508,6 +508,7 @@ subnet = ec2.create_subnet(| `AWS::Cognito::UserPoolClient` | Client ID | — || `AWS::Cognito::UserPoolResourceServer` | Identifier | — || `AWS::Cognito::IdentityPool` | Pool ID | — |+| `AWS::Cognito::IdentityPoolPrincipalTag` | `<pool ID>\|<provider name>` | — || `AWS::Cognito::UserPoolDomain` | Domain | — || `AWS::IoT::CACertificate` | Certificate id | Arn, Id || `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri |@@ -578,7 +579,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, CreateIdentityProvider, DescribeIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, ListIdentityProviders, GetIdentityProviderByIdentifier, AdminLinkProviderForUser, AdminDisableProviderForUser, 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; **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 |+| **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, 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 (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; **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` here returns stub credentials without evaluating policy, so tags never reach a session's `aws:PrincipalTag` 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 b796856d..da3520a5 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -6915,6 +6915,50 @@ def _cognito_identity_pool_role_attachment_delete(physical_id, props):pool["_roles"] = {}+def _cognito_identity_pool_principal_tag_apply(props):+ iid = props.get("IdentityPoolId")+ if not iid:+ raise ValueError("AWS::Cognito::IdentityPoolPrincipalTag requires IdentityPoolId")+ provider = props.get("IdentityProviderName")+ if not provider:+ raise ValueError("AWS::Cognito::IdentityPoolPrincipalTag requires IdentityProviderName")+ resp = _cognito._set_principal_tag_attribute_map({+ "IdentityPoolId": iid,+ "IdentityProviderName": provider,+ **({"UseDefaults": props["UseDefaults"]} if "UseDefaults" in props else {}),+ **({"PrincipalTags": props["PrincipalTags"]} if "PrincipalTags" in props else {}),+ })+ if resp[0] >= 400:+ raise ValueError(f"AWS::Cognito::IdentityPoolPrincipalTag failed: {resp[2]!r}")+ return iid, provider+++def _cognito_identity_pool_principal_tag_create(logical_id, props, stack_name):+ iid, provider = _cognito_identity_pool_principal_tag_apply(props)+ # Ref is the primary identifier, which AWS documents as the identity pool+ # and the provider name joined by a pipe, so one pool carries a mapping per+ # provider without sharing a physical id. The resource publishes no+ # Fn::GetAtt attributes.+ return f"{iid}|{provider}", {}+++def _cognito_identity_pool_principal_tag_update(physical_id, old_props, new_props, stack_name):+ iid, provider = _cognito_identity_pool_principal_tag_apply(new_props)+ # IdentityPoolId and IdentityProviderName are create-only: a change to+ # either is a replacement, and the mapping left on the old pair would+ # otherwise keep tagging principals after the template stopped declaring it.+ if (old_props.get("IdentityPoolId"), old_props.get("IdentityProviderName")) != (iid, provider):+ _cognito_identity_pool_principal_tag_delete(physical_id, old_props)+ return f"{iid}|{provider}", {}+++def _cognito_identity_pool_principal_tag_delete(physical_id, props):+ iid, _, provider = physical_id.partition("|")+ pool = _cognito._identity_pools.get(iid)+ if pool is not None:+ pool.get("_principal_tags", {}).pop(provider, None)++_RESOURCE_HANDLERS = {"AWS::OpenSearchService::Domain": {"create": _opensearch_domain_create,@@ -7232,6 +7276,11 @@ _RESOURCE_HANDLERS = {"create": _cognito_identity_pool_role_attachment_create,"delete": _cognito_identity_pool_role_attachment_delete,},+ "AWS::Cognito::IdentityPoolPrincipalTag": {+ "create": _cognito_identity_pool_principal_tag_create,+ "update": _cognito_identity_pool_principal_tag_update,+ "delete": _cognito_identity_pool_principal_tag_delete,+ },# EventBridge Scheduler"AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "delete": _scheduler_schedule_delete},"AWS::Scheduler::ScheduleGroup": {"create": _scheduler_group_create, "delete": _scheduler_group_delete},diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 21220314..7e1a98eb 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -35,6 +35,7 @@ Identity Pools operations:ListIdentityPools, UpdateIdentityPool,GetId, GetCredentialsForIdentity, GetOpenIdToken,SetIdentityPoolRoles, GetIdentityPoolRoles,+ SetPrincipalTagAttributeMap, GetPrincipalTagAttributeMap,ListIdentities, DescribeIdentity, MergeDeveloperIdentities,UnlinkDeveloperIdentity, UnlinkIdentity,TagResource, UntagResource, ListTagsForResource.@@ -471,6 +472,7 @@ _identity_pools = AccountRegionScopedDict()# OpenIdConnectProviderARNs, CognitoIdentityProviders,# SamlProviderARNs, IdentityPoolTags,# _roles: {authenticated: arn, unauthenticated: arn},+# _principal_tags: {provider_name -> {UseDefaults, PrincipalTags}},# _identities: {identity_id -> identity_dict},# }@@ -2190,6 +2192,8 @@ async def _dispatch_identity(action: str, data: dict):"GetOpenIdToken": _get_open_id_token,"SetIdentityPoolRoles": _set_identity_pool_roles,"GetIdentityPoolRoles": _get_identity_pool_roles,+ "SetPrincipalTagAttributeMap": _set_principal_tag_attribute_map,+ "GetPrincipalTagAttributeMap": _get_principal_tag_attribute_map,"ListIdentities": _list_identities,"DescribeIdentity": _describe_identity,"MergeDeveloperIdentities": _merge_developer_identities,@@ -6332,6 +6336,7 @@ def _create_identity_pool(data):"SamlProviderARNs": data.get("SamlProviderARNs", []),"IdentityPoolTags": data.get("IdentityPoolTags", {}),"_roles": {},+ "_principal_tags": {},"_identities": {},}_identity_pools[iid] = pool@@ -6450,6 +6455,63 @@ def _get_identity_pool_roles(data):})+def _principal_tag_target(data):+ """Resolve the (IdentityPoolId, IdentityProviderName) pair both principal-tag+ operations require. Returns (pool, provider_name, error_response)."""+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return None, "", error_response_json(+ "ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ provider = data.get("IdentityProviderName")+ if not provider:+ return None, "", error_response_json(+ "InvalidParameterException", "IdentityProviderName is required.", 400)+ return pool, provider, None+++def _principal_tag_out(iid, provider, mapping):+ return {+ "IdentityPoolId": iid,+ "IdentityProviderName": provider,+ "UseDefaults": mapping["UseDefaults"],+ "PrincipalTags": mapping["PrincipalTags"],+ }+++def _set_principal_tag_attribute_map(data):+ pool, provider, err = _principal_tag_target(data)+ if err:+ return err+ # Both members are optional and are stored exactly as sent. UseDefaults+ # selects the per-provider default claim-to-tag mapping (`sub` and `aud`+ # for a user pool IdP), which AWS applies when it vends credentials rather+ # than materializing into PrincipalTags — so no default map is fabricated+ # here. AWS accepts both members together: terraform-provider-aws sends+ # UseDefaults with an empty PrincipalTags on every destroy.+ mapping = {+ "UseDefaults": data.get("UseDefaults", False),+ "PrincipalTags": data.get("PrincipalTags", {}),+ }+ pool.setdefault("_principal_tags", {})[provider] = mapping+ return json_response(_principal_tag_out(pool["IdentityPoolId"], provider, mapping))+++def _get_principal_tag_attribute_map(data):+ pool, provider, err = _principal_tag_target(data)+ if err:+ return err+ mapping = pool.get("_principal_tags", {}).get(provider)+ if not mapping:+ # A provider nobody has configured is not readable: AWS answers+ # ResourceNotFoundException with this message rather than describing an+ # empty mapping (verified against cognito-identity in ap-southeast-2).+ return error_response_json(+ "ResourceNotFoundException",+ f"No Principal Tags configured for Provider {provider}", 400)+ return json_response(_principal_tag_out(pool["IdentityPoolId"], provider, mapping))++def _list_identities(data):iid = data.get("IdentityPoolId")pool = _identity_pools.get(iid)diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex b1ea44cb..8815ad4e 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -552,6 +552,63 @@ def test_cfn_iot_and_cognito_role_attachment(cfn, iot_client, cognito_identity):_wait_stack(cfn, "cfn-iot-cog")+def test_cfn_cognito_identity_pool_principal_tag(cfn, cognito_identity):+ """AWS::Cognito::IdentityPoolPrincipalTag provisions onto the identity pool,+ is readable through GetPrincipalTagAttributeMap, and is cleared on delete."""+ provider = "cognito-idp.us-east-1.amazonaws.com/us-east-1_example"+ replacement = "cognito-idp.us-east-1.amazonaws.com/us-east-1_replacement"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Pool": {"Type": "AWS::Cognito::IdentityPool", "Properties": {+ "IdentityPoolName": "cfn-tag-pool", "AllowUnauthenticatedIdentities": True}},+ "Tags": {"Type": "AWS::Cognito::IdentityPoolPrincipalTag", "Properties": {+ "IdentityPoolId": {"Ref": "Pool"},+ "IdentityProviderName": provider,+ "UseDefaults": False,+ "PrincipalTags": {"tenant": "custom:tenant"}}},+ },+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},+ "TagRef": {"Value": {"Ref": "Tags"}}},+ }+ cfn.create_stack(StackName="cfn-cog-tag", TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, "cfn-cog-tag")+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ pool_id = outputs["PoolId"]+ # Ref is the documented primary identifier: "<pool id>|<provider name>".+ assert outputs["TagRef"] == f"{pool_id}|{provider}"+ mapping = cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=pool_id, IdentityProviderName=provider)+ assert mapping["UseDefaults"] is False+ assert mapping["PrincipalTags"] == {"tenant": "custom:tenant"}++ # A changed PrincipalTags applies in place.+ template["Resources"]["Tags"]["Properties"]["PrincipalTags"] = {"email": "email"}+ cfn.update_stack(StackName="cfn-cog-tag", TemplateBody=json.dumps(template))+ assert _wait_stack(cfn, "cfn-cog-tag")["StackStatus"] == "UPDATE_COMPLETE"+ assert cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=pool_id, IdentityProviderName=provider,+ )["PrincipalTags"] == {"email": "email"}++ # IdentityProviderName is create-only: the mapping moves to the new provider+ # and the one it left goes inactive.+ template["Resources"]["Tags"]["Properties"]["IdentityProviderName"] = replacement+ cfn.update_stack(StackName="cfn-cog-tag", TemplateBody=json.dumps(template))+ assert _wait_stack(cfn, "cfn-cog-tag")["StackStatus"] == "UPDATE_COMPLETE"+ assert cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=pool_id, IdentityProviderName=replacement,+ )["PrincipalTags"] == {"email": "email"}+ with pytest.raises(ClientError) as exc:+ cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=pool_id, IdentityProviderName=provider)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ cfn.delete_stack(StackName="cfn-cog-tag")+ _wait_stack(cfn, "cfn-cog-tag")++def test_cfn_iot_policy_document_update_applies_in_place(cfn, iot_client):"""A changed PolicyDocument updates the policy instead of rolling the stackback: IoT stores a new default version and Ref keeps the same name."""diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex efa1809a..75ab060d 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -926,6 +926,77 @@ def test_cognito_identity_pool_roles(cognito_identity):assert roles["Roles"]["authenticated"] == "arn:aws:iam::000000000000:role/AuthRole"assert roles["Roles"]["unauthenticated"] == "arn:aws:iam::000000000000:role/UnauthRole"+def test_cognito_identity_pool_principal_tags(cognito_identity):+ """SetPrincipalTagAttributeMap stores a provider's attribute mapping and+ GetPrincipalTagAttributeMap reports it back."""+ iid = cognito_identity.create_identity_pool(+ IdentityPoolName="PrincipalTagPool",+ AllowUnauthenticatedIdentities=True,+ )["IdentityPoolId"]+ provider = "cognito-idp.us-east-1.amazonaws.com/us-east-1_example"++ resp = cognito_identity.set_principal_tag_attribute_map(+ IdentityPoolId=iid,+ IdentityProviderName=provider,+ UseDefaults=False,+ PrincipalTags={"tenant": "custom:tenant"},+ )+ assert resp["IdentityPoolId"] == iid+ assert resp["IdentityProviderName"] == provider+ assert resp["UseDefaults"] is False+ assert resp["PrincipalTags"] == {"tenant": "custom:tenant"}++ got = cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=provider)+ assert got["UseDefaults"] is False+ assert got["PrincipalTags"] == {"tenant": "custom:tenant"}++ # A second provider on the same pool keeps its own mapping.+ other = "cognito-idp.us-east-1.amazonaws.com/us-east-1_other"+ cognito_identity.set_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=other,+ UseDefaults=False, PrincipalTags={"email": "email"})+ assert cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=provider,+ )["PrincipalTags"] == {"tenant": "custom:tenant"}+++def test_cognito_identity_pool_principal_tags_unconfigured_provider(cognito_identity):+ """A provider nobody has configured is not readable, and UseDefaults+ round-trips without materializing a tag map."""+ iid = cognito_identity.create_identity_pool(+ IdentityPoolName="PrincipalTagDefaultsPool",+ AllowUnauthenticatedIdentities=True,+ )["IdentityPoolId"]+ provider = "cognito-idp.us-east-1.amazonaws.com/us-east-1_example"++ with pytest.raises(ClientError) as exc:+ cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=provider)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert exc.value.response["Error"]["Message"] == (+ f"No Principal Tags configured for Provider {provider}")++ # UseDefaults selects the mapping AWS applies when it vends credentials; it+ # does not populate PrincipalTags. terraform-provider-aws sends both+ # members together like this on destroy.+ cognito_identity.set_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=provider,+ UseDefaults=True, PrincipalTags={})+ defaulted = cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId=iid, IdentityProviderName=provider)+ assert defaulted["UseDefaults"] is True+ assert defaulted["PrincipalTags"] == {}+++def test_cognito_identity_pool_principal_tags_unknown_pool(cognito_identity):+ with pytest.raises(ClientError) as exc:+ cognito_identity.get_principal_tag_attribute_map(+ IdentityPoolId="us-east-1:00000000-0000-0000-0000-000000000000",+ IdentityProviderName="cognito-idp.us-east-1.amazonaws.com/us-east-1_example")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++def test_cognito_list_identities(cognito_identity):resp = cognito_identity.create_identity_pool(IdentityPoolName="ListIdPool",