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): report SchemaAttributes and add custom attributes (#1516)
Johannes Grumböck0a5d345199b7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 58e2731a..57cbd109 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Cognito — `AddCustomAttributes`, and a user pool that reports its schema (`SchemaAttributes`)** — `DescribeUserPool` never returned the pool's attribute schema (the create request's `Schema` was stored under that request-shaped key and no `SchemaAttributes` was ever produced), so a client that diffs its desired schema against the pool saw every attribute as missing. Terraform re-planned an `aws_cognito_user_pool` as changed immediately after creating it and then failed the follow-up apply with `InvalidAction: Unknown Cognito IDP action: AddCustomAttributes`, because that is the operation the provider uses to reconcile added schema items. A pool now carries the full standard attribute set (`sub`, `email`, `email_verified`, `phone_number`, `updated_at`, ... with AWS's data types, mutability, and constraints), a request's `Schema` entries are stored under their `custom:` (or `dev:`) prefix and override a standard entry field-for-field when they redefine one, and `AddCustomAttributes` adds 1-25 attributes per call with `InvalidParameterException` for a duplicate, a standard attribute name, or more than 50 custom attributes, and `ResourceNotFoundException` for an unknown pool. Pools restored from an older snapshot rebuild their schema on load. Also fixed two adjacent read-back gaps that showed up as permanent drift: `EmailConfiguration` now reports `EmailSendingAccount: COGNITO_DEFAULT` when the request omitted it, and `GetUserPoolMfaConfig` no longer invents a disabled `SoftwareTokenMfaConfiguration` for a pool that never configured MFA.+### Fixed- **EventBridge — an input template no longer needs quotes around a string variable** — AWS documents that quotes are optional for a variable holding a string and adds them itself so the transformed input stays valid JSON, quoting neither an object nor an array. MiniStack pasted every value in verbatim, so the documented form `{"detail": <detail>, "groupId": <groupId>}` produced `"groupId": some-value` and the target received a body that would not parse, forcing consumers to hand-quote the placeholder. Substitution is now aware of where the placeholder sits: a string variable in a JSON value position is quoted, a variable inside a string literal is interpolated raw as before, and an object or array spliced into a string has its internal quotes stripped the way AWS does.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 19c74ded..f9d87110 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -3356,7 +3356,7 @@ def _cognito_user_pool_create(logical_id, props, stack_name):"TemporaryPasswordValidityDays": 7,}}),- "Schema": props.get("Schema", []),+ "SchemaAttributes": _cognito._build_schema_attributes(props.get("Schema")),"AutoVerifiedAttributes": props.get("AutoVerifiedAttributes", []),"AliasAttributes": props.get("AliasAttributes", []),"UsernameAttributes": props.get("UsernameAttributes", []),diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 41f2daa2..d26003a6 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -7,6 +7,7 @@ Covers two boto3 clients:User Pools operations:CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool,+ AddCustomAttributes,CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient,ListUserPoolClients, UpdateUserPoolClient,AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers,@@ -281,6 +282,156 @@ _SAML_NS = {"saml": "urn:oasis:names:tc:SAML:2.0:assertion",}+# ---------------------------------------------------------------------------+# User pool schema attributes+# ---------------------------------------------------------------------------+# Every user pool carries the standard OIDC attribute set, and DescribeUserPool+# returns it in `SchemaAttributes` (never `Schema` — that name only exists on the+# CreateUserPool/UpdateUserPool *request*). Custom attributes are returned with+# a `custom:` prefix, developer-only ones with `dev:`.+# https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserPoolType.html+# https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SchemaAttributeType.html+# https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html+# Clients diff against this list — the Terraform provider, for one, drops an+# attribute from state only when it matches the standard entry field for field —+# so the shapes below mirror what the real service answers with.++_ATTRIBUTE_CUSTOM_PREFIX = "custom:"+_ATTRIBUTE_DEV_PREFIX = "dev:"+_MAX_CUSTOM_ATTRIBUTES = 50+++def _standard_string_attribute(name, min_length="0", max_length="2048"):+ return {+ "Name": name,+ "AttributeDataType": "String",+ "DeveloperOnlyAttribute": False,+ "Mutable": True,+ "Required": False,+ "StringAttributeConstraints": {+ "MinLength": min_length,+ "MaxLength": max_length,+ },+ }+++def _standard_boolean_attribute(name):+ return {+ "Name": name,+ "AttributeDataType": "Boolean",+ "DeveloperOnlyAttribute": False,+ "Mutable": True,+ "Required": False,+ }+++_STANDARD_SCHEMA_ATTRIBUTES = [+ _standard_string_attribute("sub", min_length="1"),+ _standard_string_attribute("name"),+ _standard_string_attribute("given_name"),+ _standard_string_attribute("family_name"),+ _standard_string_attribute("middle_name"),+ _standard_string_attribute("nickname"),+ _standard_string_attribute("preferred_username"),+ _standard_string_attribute("profile"),+ _standard_string_attribute("picture"),+ _standard_string_attribute("website"),+ _standard_string_attribute("email"),+ _standard_boolean_attribute("email_verified"),+ _standard_string_attribute("gender"),+ _standard_string_attribute("birthdate", min_length="10", max_length="10"),+ _standard_string_attribute("zoneinfo"),+ _standard_string_attribute("locale"),+ _standard_string_attribute("phone_number"),+ _standard_boolean_attribute("phone_number_verified"),+ _standard_string_attribute("address"),+ {+ "Name": "updated_at",+ "AttributeDataType": "Number",+ "DeveloperOnlyAttribute": False,+ "Mutable": True,+ "Required": False,+ "NumberAttributeConstraints": {"MinValue": "0"},+ },+]+# `sub` is the one standard attribute that is immutable and required.+for _attr in _STANDARD_SCHEMA_ATTRIBUTES:+ if _attr["Name"] == "sub":+ _attr["Mutable"] = False+ _attr["Required"] = True+del _attr++_STANDARD_ATTRIBUTES_BY_NAME = {a["Name"]: a for a in _STANDARD_SCHEMA_ATTRIBUTES}+++def _schema_attribute_name(raw) -> str:+ """Return the stored attribute name, prefixing custom/developer attributes.++ AWS: "When you add an attribute with a Name value of MyAttribute, Amazon+ Cognito creates the custom attribute custom:MyAttribute", and dev:MyAttribute+ when DeveloperOnlyAttribute is true. A caller that already sent the prefix+ (as a round-tripped DescribeUserPool response does) keeps it.+ """+ name = (raw.get("Name") or "").strip()+ if (name in _STANDARD_ATTRIBUTES_BY_NAME+ or name.startswith(_ATTRIBUTE_CUSTOM_PREFIX)+ or name.startswith(_ATTRIBUTE_DEV_PREFIX)):+ return name+ prefix = (_ATTRIBUTE_DEV_PREFIX if raw.get("DeveloperOnlyAttribute")+ else _ATTRIBUTE_CUSTOM_PREFIX)+ return f"{prefix}{name}"+++def _normalize_schema_attribute(raw: dict) -> dict:+ """Fill a request SchemaAttributeType out to its DescribeUserPool shape.++ Overriding a standard attribute (a pool that makes `email` required, say)+ starts from the standard entry, so unspecified fields keep the values the+ real service reports rather than dropping out of the response.+ """+ name = _schema_attribute_name(raw)+ base = _STANDARD_ATTRIBUTES_BY_NAME.get(name)+ attr = copy.deepcopy(base) if base else {+ "Name": name,+ "AttributeDataType": "String",+ "DeveloperOnlyAttribute": False,+ "Mutable": False,+ "Required": False,+ }+ attr["Name"] = name+ for key in ("AttributeDataType",):+ if raw.get(key):+ attr[key] = raw[key]+ for key in ("DeveloperOnlyAttribute", "Mutable", "Required"):+ if key in raw:+ attr[key] = bool(raw[key])+ for key in ("StringAttributeConstraints", "NumberAttributeConstraints"):+ if raw.get(key):+ attr[key] = dict(raw[key])+ return attr+++def _build_schema_attributes(schema) -> list:+ """Standard attributes plus the caller's, as DescribeUserPool returns them."""+ attrs = copy.deepcopy(_STANDARD_SCHEMA_ATTRIBUTES)+ index = {a["Name"]: i for i, a in enumerate(attrs)}+ for raw in schema or []:+ if not isinstance(raw, dict):+ continue+ attr = _normalize_schema_attribute(raw)+ if attr["Name"] in index:+ attrs[index[attr["Name"]]] = attr+ else:+ index[attr["Name"]] = len(attrs)+ attrs.append(attr)+ return attrs+++def _custom_attribute_count(pool) -> int:+ return sum(1 for a in pool.get("SchemaAttributes", [])+ if a["Name"].startswith((_ATTRIBUTE_CUSTOM_PREFIX, _ATTRIBUTE_DEV_PREFIX)))++# ---------------------------------------------------------------------------# In-memory state — User Pools (cognito-idp)# ---------------------------------------------------------------------------@@ -288,7 +439,7 @@ _SAML_NS = {_user_pools = AccountRegionScopedDict()# pool_id -> {# Id, Name, Arn, CreationDate, LastModifiedDate, Status,-# Policies, Schema, AutoVerifiedAttributes, UsernameAttributes,+# Policies, SchemaAttributes, AutoVerifiedAttributes, UsernameAttributes,# MfaConfiguration, EstimatedNumberOfUsers,# AdminCreateUserConfig, UserPoolTags,# Domain (str|None),@@ -435,6 +586,7 @@ def restore_state(data):data.get("user_pools", {}),lambda pool_id, _pool: _region_from_pool_id(pool_id),)+_restore_regional_store(_pool_domain_map,data.get("pool_domain_map", {}),@@ -457,6 +609,19 @@ def restore_state(data):_challenge_sessions.update(data.get("challenge_sessions", {}))+def _ensure_schema_attributes(pool: dict) -> dict:+ """Backfill a pool restored from a pre-SchemaAttributes snapshot.++ Older snapshots stored the CreateUserPool request's `Schema` list verbatim+ and carried no `SchemaAttributes`; rebuilding from it on first use keeps a+ restored pool describing itself the way a freshly created one does, without+ rewriting records that a caller never touches.+ """+ if not pool.get("SchemaAttributes"):+ pool["SchemaAttributes"] = _build_schema_attributes(pool.pop("Schema", None))+ return pool++def _restore_regional_store(store, restored, region_for_item):"""Restore a Cognito store, self-placing legacy records from their IDs."""if isinstance(restored, AccountRegionScopedDict):@@ -1847,6 +2012,7 @@ async def _dispatch_idp(action: str, data: dict):"DescribeUserPool": _describe_user_pool,"ListUserPools": _list_user_pools,"UpdateUserPool": _update_user_pool,+ "AddCustomAttributes": _add_custom_attributes,# User Pool Client CRUD"CreateUserPoolClient": _create_user_pool_client,"DeleteUserPoolClient": _delete_user_pool_client,@@ -1994,7 +2160,7 @@ def _create_user_pool(data):"TemporaryPasswordValidityDays": 7,}}),- "Schema": data.get("Schema", []),+ "SchemaAttributes": _build_schema_attributes(data.get("Schema")),"AutoVerifiedAttributes": data.get("AutoVerifiedAttributes", []),"AliasAttributes": data.get("AliasAttributes", []),"UsernameAttributes": data.get("UsernameAttributes", []),@@ -2004,7 +2170,7 @@ def _create_user_pool(data):"SmsAuthenticationMessage": data.get("SmsAuthenticationMessage", ""),"MfaConfiguration": data.get("MfaConfiguration", "OFF"),"EstimatedNumberOfUsers": 0,- "EmailConfiguration": data.get("EmailConfiguration", {}),+ "EmailConfiguration": _email_configuration_out(data.get("EmailConfiguration", {})),"SmsConfiguration": data.get("SmsConfiguration", {}),"UserPoolTags": data.get("UserPoolTags", {}),"AdminCreateUserConfig": data.get("AdminCreateUserConfig", {@@ -2089,12 +2255,86 @@ def _update_user_pool(data):for k in updatable:if k in data:pool[k] = data[k]+ if "EmailConfiguration" in data:+ pool["EmailConfiguration"] = _email_configuration_out(data["EmailConfiguration"])+ pool["LastModifiedDate"] = _now_epoch()+ return json_response({})+++def _add_custom_attributes(data):+ # https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AddCustomAttributes.html+ # Adds to the pool schema only: 1-25 attributes per call, each stored under+ # its `custom:` (or `dev:`) prefix, and custom attributes can never be+ # removed or redefined afterwards.+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ custom_attributes = data.get("CustomAttributes")+ if not isinstance(custom_attributes, list) or not custom_attributes:+ return error_response_json(+ "InvalidParameterException",+ "1 validation error detected: Value null at 'customAttributes' failed to "+ "satisfy constraint: Member must not be null", 400)+ if len(custom_attributes) > 25:+ return error_response_json(+ "InvalidParameterException",+ "1 validation error detected: Value at 'customAttributes' failed to satisfy "+ "constraint: Member must have length less than or equal to 25", 400)++ existing = {a["Name"] for a in _ensure_schema_attributes(pool)["SchemaAttributes"]}+ additions = []+ for raw in custom_attributes:+ if not isinstance(raw, dict) or not (raw.get("Name") or "").strip():+ return error_response_json(+ "InvalidParameterException", "Invalid attribute name.", 400)+ attr = _normalize_schema_attribute(raw)+ if not attr["Name"].startswith((_ATTRIBUTE_CUSTOM_PREFIX, _ATTRIBUTE_DEV_PREFIX)):+ # A standard attribute name is not a custom attribute; AWS refuses+ # rather than silently redefining the standard schema entry.+ return error_response_json(+ "InvalidParameterException",+ f"{attr['Name']} is a standard attribute and cannot be added as a "+ "custom attribute.", 400)+ if attr["Name"] in existing:+ return error_response_json(+ "InvalidParameterException",+ f"{attr['Name']}: Attribute already exists in the schema.", 400)+ existing.add(attr["Name"])+ additions.append(attr)++ if _custom_attribute_count(pool) + len(additions) > _MAX_CUSTOM_ATTRIBUTES:+ return error_response_json(+ "InvalidParameterException",+ f"user pool can have up to {_MAX_CUSTOM_ATTRIBUTES} custom attributes.", 400)++ pool["SchemaAttributes"].extend(additions)pool["LastModifiedDate"] = _now_epoch()+ logger.info("Cognito: AddCustomAttributes %s (%s)",+ ", ".join(a["Name"] for a in additions), pid)return json_response({})+def _email_configuration_out(email_configuration) -> dict:+ # AWS reports EmailSendingAccount even when the request omitted it: an+ # unspecified account means Cognito's built-in mailer.+ # https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html+ config = dict(email_configuration or {})+ # Cognito reports its default mailer even when no explicit email options+ # were supplied. This also normalizes pools created by older MiniStack+ # versions whose persisted EmailConfiguration was empty.+ config.setdefault("EmailSendingAccount", "COGNITO_DEFAULT")+ return config++def _pool_out(pool: dict) -> dict:- return {k: v for k, v in pool.items() if not k.startswith("_")}+ _ensure_schema_attributes(pool)+ output = {k: v for k, v in pool.items() if not k.startswith("_")}+ if "EmailConfiguration" in output:+ output["EmailConfiguration"] = _email_configuration_out(+ output["EmailConfiguration"]+ )+ return output# ===========================================================================@@ -4395,15 +4635,20 @@ def _linked_username_for_federation(pool, provider_name, name_id, user_attrs):def _get_user_pool_mfa_config(data):+ # https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserPoolMfaConfig.html+ # A configuration that was never set is absent from the response rather than+ # reported as a disabled block — clients diff the response against their+ # desired state, so an invented SoftwareTokenMfaConfiguration reads as drift.pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)if err:return err- return json_response({- "SmsMfaConfiguration": pool.get("SmsMfaConfiguration", {}),- "SoftwareTokenMfaConfiguration": pool.get("SoftwareTokenMfaConfiguration", {"Enabled": False}),- "MfaConfiguration": pool.get("MfaConfiguration", "OFF"),- })+ resp = {"MfaConfiguration": pool.get("MfaConfiguration", "OFF")}+ for key in ("SmsMfaConfiguration", "SoftwareTokenMfaConfiguration",+ "EmailMfaConfiguration", "WebAuthnConfiguration"):+ if pool.get(key):+ resp[key] = pool[key]+ return json_response(resp)def _admin_set_user_mfa_preference(data):@@ -4468,14 +4713,19 @@ def _set_user_pool_mfa_config(data):pool["SmsMfaConfiguration"] = data["SmsMfaConfiguration"]if "SoftwareTokenMfaConfiguration" in data:pool["SoftwareTokenMfaConfiguration"] = data["SoftwareTokenMfaConfiguration"]+ if "EmailMfaConfiguration" in data:+ pool["EmailMfaConfiguration"] = data["EmailMfaConfiguration"]+ if "WebAuthnConfiguration" in data:+ pool["WebAuthnConfiguration"] = data["WebAuthnConfiguration"]if "MfaConfiguration" in data:pool["MfaConfiguration"] = data["MfaConfiguration"]pool["LastModifiedDate"] = _now_epoch()- return json_response({- "SmsMfaConfiguration": pool.get("SmsMfaConfiguration", {}),- "SoftwareTokenMfaConfiguration": pool.get("SoftwareTokenMfaConfiguration", {}),- "MfaConfiguration": pool.get("MfaConfiguration", "OFF"),- })+ resp = {"MfaConfiguration": pool.get("MfaConfiguration", "OFF")}+ for key in ("SmsMfaConfiguration", "SoftwareTokenMfaConfiguration",+ "EmailMfaConfiguration", "WebAuthnConfiguration"):+ if pool.get(key):+ resp[key] = pool[key]+ return json_response(resp)def _associate_software_token(data):diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 127395d9..c2b3695b 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -464,6 +464,10 @@ 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)assert resp["MfaConfiguration"] == "OFF"+ # An unconfigured pool reports no MFA blocks at all; inventing a disabled+ # SoftwareTokenMfaConfiguration reads as drift to a config-diffing client.+ assert "SoftwareTokenMfaConfiguration" not in resp+ assert "SmsMfaConfiguration" not in respcognito_idp.set_user_pool_mfa_config(UserPoolId=pid,@@ -474,6 +478,128 @@ def test_cognito_mfa_config(cognito_idp):assert resp["MfaConfiguration"] == "OPTIONAL"assert resp["SoftwareTokenMfaConfiguration"]["Enabled"] is True+def test_cognito_user_pool_returns_standard_schema_attributes(cognito_idp):+ pool = cognito_idp.create_user_pool(PoolName="SchemaStandardPool")["UserPool"]+ attrs = {a["Name"]: a for a in pool["SchemaAttributes"]}+ # AWS always returns the full standard OIDC attribute set.+ for name in ("sub", "name", "given_name", "family_name", "email",+ "email_verified", "phone_number", "address", "updated_at"):+ assert name in attrs+ assert attrs["sub"] == {+ "Name": "sub",+ "AttributeDataType": "String",+ "DeveloperOnlyAttribute": False,+ "Mutable": False,+ "Required": True,+ "StringAttributeConstraints": {"MinLength": "1", "MaxLength": "2048"},+ }+ assert attrs["email_verified"]["AttributeDataType"] == "Boolean"+ assert "StringAttributeConstraints" not in attrs["email_verified"]+ assert attrs["updated_at"]["NumberAttributeConstraints"] == {"MinValue": "0"}+ assert attrs["birthdate"]["StringAttributeConstraints"] == {+ "MinLength": "10", "MaxLength": "10"}+++def test_cognito_user_pool_schema_request_is_echoed_by_describe(cognito_idp):+ pool = cognito_idp.create_user_pool(+ PoolName="SchemaEchoPool",+ Schema=[+ {"Name": "email", "AttributeDataType": "String", "Mutable": True,+ "Required": True,+ "StringAttributeConstraints": {"MinLength": "1", "MaxLength": "256"}},+ {"Name": "tenant", "AttributeDataType": "String", "Mutable": True,+ "StringAttributeConstraints": {"MinLength": "1", "MaxLength": "32"}},+ ],+ )["UserPool"]+ described = cognito_idp.describe_user_pool(+ UserPoolId=pool["Id"])["UserPool"]["SchemaAttributes"]+ assert described == pool["SchemaAttributes"]+ attrs = {a["Name"]: a for a in described}+ # A standard attribute the request redefines keeps the caller's values ...+ assert attrs["email"]["Required"] is True+ assert attrs["email"]["StringAttributeConstraints"] == {+ "MinLength": "1", "MaxLength": "256"}+ # ... and a new attribute is stored under its custom: prefix.+ assert "tenant" not in attrs+ assert attrs["custom:tenant"]["Mutable"] is True+ assert attrs["custom:tenant"]["Required"] is False+ assert attrs["custom:tenant"]["DeveloperOnlyAttribute"] is False+++def test_cognito_user_pool_developer_only_attribute_gets_dev_prefix(cognito_idp):+ pool = cognito_idp.create_user_pool(+ PoolName="SchemaDevPool",+ Schema=[{"Name": "internal", "AttributeDataType": "String",+ "DeveloperOnlyAttribute": True}],+ )["UserPool"]+ names = [a["Name"] for a in pool["SchemaAttributes"]]+ assert "dev:internal" in names+++def test_cognito_add_custom_attributes(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="AddCustomAttrPool")["UserPool"]["Id"]+ cognito_idp.add_custom_attributes(+ UserPoolId=pid,+ CustomAttributes=[+ {"Name": "deliverables", "AttributeDataType": "String", "Mutable": True,+ "StringAttributeConstraints": {"MinLength": "1", "MaxLength": "255"}},+ {"Name": "seats", "AttributeDataType": "Number",+ "NumberAttributeConstraints": {"MinValue": "1"}},+ ],+ )+ attrs = {a["Name"]: a for a in+ cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["SchemaAttributes"]}+ assert attrs["custom:deliverables"]["StringAttributeConstraints"] == {+ "MinLength": "1", "MaxLength": "255"}+ assert attrs["custom:seats"]["AttributeDataType"] == "Number"+ assert attrs["custom:seats"]["NumberAttributeConstraints"] == {"MinValue": "1"}+++def test_cognito_add_custom_attributes_rejects_duplicate(cognito_idp):+ pid = cognito_idp.create_user_pool(+ PoolName="AddCustomAttrDupPool",+ Schema=[{"Name": "tenant", "AttributeDataType": "String"}],+ )["UserPool"]["Id"]+ with pytest.raises(ClientError) as exc:+ cognito_idp.add_custom_attributes(+ UserPoolId=pid,+ CustomAttributes=[{"Name": "tenant", "AttributeDataType": "String"}],+ )+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+++def test_cognito_add_custom_attributes_rejects_standard_attribute(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="AddCustomAttrStdPool")["UserPool"]["Id"]+ with pytest.raises(ClientError) as exc:+ cognito_idp.add_custom_attributes(+ UserPoolId=pid,+ CustomAttributes=[{"Name": "email", "AttributeDataType": "String"}],+ )+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+++def test_cognito_add_custom_attributes_unknown_pool(cognito_idp):+ with pytest.raises(ClientError) as exc:+ cognito_idp.add_custom_attributes(+ UserPoolId="us-east-1_missingpool",+ CustomAttributes=[{"Name": "tenant", "AttributeDataType": "String"}],+ )+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_cognito_email_configuration_defaults_to_cognito_default(cognito_idp):+ empty_pool = cognito_idp.create_user_pool(PoolName="EmailCfgEmptyPool")["UserPool"]+ assert empty_pool["EmailConfiguration"]["EmailSendingAccount"] == "COGNITO_DEFAULT"++ pool = cognito_idp.create_user_pool(+ PoolName="EmailCfgPool",+ EmailConfiguration={"ReplyToEmailAddress": "[email protected]"},+ )["UserPool"]+ assert pool["EmailConfiguration"]["EmailSendingAccount"] == "COGNITO_DEFAULT"+ described = cognito_idp.describe_user_pool(UserPoolId=pool["Id"])["UserPool"]+ assert described["EmailConfiguration"]["EmailSendingAccount"] == "COGNITO_DEFAULT"++def test_cognito_tags(cognito_idp):resp = cognito_idp.create_user_pool(PoolName="TagPool")pid = resp["UserPool"]["Id"]diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 9f3bcaca..5dde53ba 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -4284,6 +4284,44 @@ def test_cognito_region_scoped_state_round_trips_and_is_rejected_by_v2_reader(set_request_region(original_region)+def test_cognito_restore_rebuilds_schema_attributes_from_legacy_snapshot(monkeypatch):+ """A pool snapshotted before SchemaAttributes existed still describes fully."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import cognito++ original_account = get_account_id()+ original_region = get_region()+ pool_id = "us-west-2_legacyschema"+ try:+ set_request_account_id("000000000000")+ set_request_region("us-west-2")+ cognito.reset()+ cognito.restore_state({+ "user_pools": {+ pool_id: {+ "Id": pool_id,+ "Name": "legacy",+ "Schema": [{"Name": "tenant", "AttributeDataType": "String"}],+ }+ }+ })+ pool = cognito._pool_out(cognito._user_pools[pool_id])+ names = [a["Name"] for a in pool["SchemaAttributes"]]+ assert "sub" in names and "email" in names+ assert "custom:tenant" in names+ # The request-shaped key does not survive into the response shape.+ assert "Schema" not in pool+ finally:+ cognito.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)++def test_waf_region_scoped_v3_state_round_trips_idempotently(monkeypatch, tmp_path):import json as _json