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): store and validate the user pool tier (#2286)
iot-rocket1e79a5fdfcc2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 235fe50a..91a120b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Cognito — user pool feature plans** — `CreateUserPool`, `UpdateUserPool` and `AWS::Cognito::UserPool` ignored `UserPoolTier`; a pool now stores and describes its tier (`ESSENTIALS` by default, `PLUS` when created with threat protection on), keeps it when an update omits it, and refuses threat protection on `ESSENTIALS` and password history on `LITE` with `FeatureUnavailableInTierException` or, on a tier change, `TierChangeNotAllowedException`. Contributed by @iot-rocket.### Fixed- **IoT — topic rule name errors** — `CreateTopicRule` refused a name outside `^[a-zA-Z0-9_]+$` or longer than 128 characters with its own `Invalid ruleName: must match [a-zA-Z0-9_]{1,128}`; it now answers AWS's 400 `InvalidRequestException` validation message, which names the failed pattern, the failed length or both, and the topic rule calls that already checked the name give the length part too. A valid name followed by a newline passed the name check, so `CreateTopicRule` stored a rule under it; all six calls refuse it now. Contributed by @iot-rocket.- **IoT — unknown topic rules answer 401** — `GetTopicRule`, `ReplaceTopicRule`, `EnableTopicRule` and `DisableTopicRule` on a rule that does not exist answered 404 `ResourceNotFoundException` and `DeleteTopicRule` answered 200; they now answer 401 `UnauthorizedException` (`Access to topic rule '<name>' was denied`) as AWS does, and `GetTopicRule`, `ReplaceTopicRule` and `DeleteTopicRule` refuse a name outside the rule name pattern with the 400 `InvalidRequestException` that `EnableTopicRule` gives. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 52355d57..5a6a3bff 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -6935,7 +6935,7 @@ _COGNITO_USER_POOL_UPDATABLE = {_COGNITO_USER_POOL_CREATE_ONLY = ("Schema", "AliasAttributes", "UsernameAttributes","UsernameConfiguration")-# The rest of the AWS::Cognito::UserPool reference (UserPoolTier, the+# The rest of the AWS::Cognito::UserPool reference (the# EmailAuthentication* and WebAuthn* properties, IssuerConfiguration,# KeyConfiguration) has no field on the service's record and is not# modelled: it is accepted and ignored on create and on update alike.@@ -6955,7 +6955,7 @@ def _cognito_user_pool_create(logical_id, props, stack_name):_cognito_user_pool_update applies later."""payload = {key: props[key]- for key in (*_COGNITO_USER_POOL_CREATE_ONLY, *_COGNITO_USER_POOL_UPDATABLE)+ for key in (*_COGNITO_USER_POOL_CREATE_ONLY, *_COGNITO_USER_POOL_UPDATABLE, "UserPoolTier")if key in props}payload["PoolName"] = _cognito_user_pool_name(props, stack_name, logical_id)@@ -7053,6 +7053,9 @@ def _cognito_user_pool_update(physical_id, old_props, new_props, stack_name,"a new UserPool resource instead.")payload = _declared_or_default(old_props, new_props, _COGNITO_USER_POOL_UPDATABLE)+ # A dropped UserPoolTier keeps the pool's plan, as an UpdateUserPool without it does.+ if "UserPoolTier" in new_props:+ payload["UserPoolTier"] = new_props["UserPoolTier"]if payload:payload["UserPoolId"] = physical_idstatus, _, body = _cognito._update_user_pool(payload)diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 0781f538..f89d1799 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2759,6 +2759,40 @@ async def _dispatch_identity(action: str, data: dict):# USER POOL CRUD# ===========================================================================+_USER_POOL_TIERS = ("ESSENTIALS", "LITE", "PLUS")+++def _threat_protection_on(add_ons) -> bool:+ return (add_ons or {}).get("AdvancedSecurityMode", "OFF") != "OFF"+++def _user_pool_tier(pool: dict) -> str:+ """The pool's feature plan, defaulting as CreateUserPool does when the request omits it."""+ tier = pool.get("UserPoolTier")+ if tier is None:+ tier = "PLUS" if _threat_protection_on(pool.get("UserPoolAddOns")) else "ESSENTIALS"+ return tier+++def _user_pool_tier_error(tier, add_ons, policies, current=None):+ """Refuse an unknown tier or a feature it lacks (threat protection on ESSENTIALS, password history on LITE)."""+ if tier not in _USER_POOL_TIERS:+ return error_response_json(+ "InvalidParameterException",+ f"1 validation error detected: Value '{tier}' at 'userPoolTier' failed to satisfy constraint: "+ f"Member must satisfy enum value set: [{', '.join(_USER_POOL_TIERS)}]", 400)+ if tier == "ESSENTIALS" and _threat_protection_on(add_ons):+ feature = "Threat Protection"+ elif tier == "LITE" and ((policies or {}).get("PasswordPolicy") or {}).get("PasswordHistorySize"):+ feature = "Password History"+ else:+ return None+ # A plan change the pool's features rule out has its own error code.+ code = "TierChangeNotAllowedException" if current not in (None, tier) else "FeatureUnavailableInTierException"+ return error_response_json(+ code, f"The following features need to be disabled for the {tier} pricing tier configured: {feature}", 400)++def _create_user_pool(data):name = data.get("PoolName")if not name:@@ -2774,6 +2808,10 @@ def _create_user_pool(data):return error_response_json("InvalidParameterException","Required custom attributes are not supported.", 400)+ tier = _user_pool_tier(data)+ err = _user_pool_tier_error(tier, data.get("UserPoolAddOns"), data.get("Policies"))+ if err:+ return errpid = _pool_id()now = _now_epoch()@@ -2813,6 +2851,7 @@ def _create_user_pool(data):"AccountRecoverySetting": data.get("AccountRecoverySetting", {}),"DeletionProtection": data.get("DeletionProtection", "INACTIVE"),"LambdaConfig": data.get("LambdaConfig", {}),+ "UserPoolTier": tier,"Domain": None,"CustomDomain": None,"_clients": {},@@ -2877,6 +2916,12 @@ def _list_user_pools(data):def _update_user_pool(data):pid = data.get("UserPoolId")pool, err = _resolve_pool(pid)+ if err:+ return err+ # An omitted tier keeps the pool's plan; omitted add-ons stay out of the check, AWS resets them.+ current = _user_pool_tier(pool)+ err = _user_pool_tier_error(data.get("UserPoolTier", current), data.get("UserPoolAddOns"),+ data.get("Policies", pool.get("Policies")), current)if err:return errupdatable = {@@ -2886,7 +2931,7 @@ def _update_user_pool(data):"EmailConfiguration", "SmsConfiguration", "UserPoolTags","AdminCreateUserConfig", "UserPoolAddOns", "VerificationMessageTemplate","AccountRecoverySetting", "LambdaConfig",- "UserAttributeUpdateSettings",+ "UserAttributeUpdateSettings", "UserPoolTier",# Deletion protection is switched off through UpdateUserPool before a# protected pool can be deleted (per the DeletionProtection property# on the CloudFormation resource reference).@@ -2974,6 +3019,7 @@ def _email_configuration_out(email_configuration) -> dict:def _pool_out(pool: dict) -> dict:_ensure_schema_attributes(pool)output = {k: v for k, v in pool.items() if not k.startswith("_")}+ output["UserPoolTier"] = _user_pool_tier(pool)if "EmailConfiguration" in output:output["EmailConfiguration"] = _email_configuration_out(output["EmailConfiguration"]diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 94b66247..9dcd25c2 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -22251,6 +22251,48 @@ def test_cfn_cognito_user_pool_update_preserves_users(cfn, cognito_idp):_wait_stack(cfn, "cfn-pool-upd")+def test_cfn_cognito_user_pool_tier(cfn, cognito_idp):+ """UserPoolTier is applied on create and updated in place; dropping it keeps the pool's tier."""+ def template(**props):+ return json.dumps({+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool",+ "Properties": {"UserPoolName": "cfn-tier", **props}}},+ "Outputs": {"Id": {"Value": {"Ref": "Pool"}}},+ })++ def tier(pid):+ return cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["UserPoolTier"]++ cfn.create_stack(StackName="cfn-tier", TemplateBody=template(UserPoolTier="LITE"))+ stack = _wait_stack(cfn, "cfn-tier")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ pool_id = stack["Outputs"][0]["OutputValue"]+ assert tier(pool_id) == "LITE"+ for props, expected in (({"UserPoolTier": "PLUS"}, "PLUS"), ({"UserPoolTier": "LITE"}, "LITE"), ({}, "LITE")):+ cfn.update_stack(StackName="cfn-tier", TemplateBody=template(**props))+ stack = _wait_stack(cfn, "cfn-tier")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ assert stack["Outputs"][0]["OutputValue"] == pool_id+ assert tier(pool_id) == expected+ cfn.delete_stack(StackName="cfn-tier")+ _wait_stack(cfn, "cfn-tier")++ cfn.create_stack(StackName="cfn-tier-audit", TemplateBody=template(+ UserPoolAddOns={"AdvancedSecurityMode": "AUDIT"}))+ stack = _wait_stack(cfn, "cfn-tier-audit")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ assert tier(stack["Outputs"][0]["OutputValue"]) == "PLUS"+ cfn.delete_stack(StackName="cfn-tier-audit")+ _wait_stack(cfn, "cfn-tier-audit")++ cfn.create_stack(StackName="cfn-tier-ess-audit", TemplateBody=template(+ UserPoolTier="ESSENTIALS", UserPoolAddOns={"AdvancedSecurityMode": "AUDIT"}))+ assert _wait_stack(cfn, "cfn-tier-ess-audit")["StackStatus"] == "ROLLBACK_COMPLETE"+ assert "FeatureUnavailableInTierException" in _stack_event_reasons(cfn, "cfn-tier-ess-audit")+ cfn.delete_stack(StackName="cfn-tier-ess-audit")+ _wait_stack(cfn, "cfn-tier-ess-audit")++def test_cfn_secret_update_keeps_arn_and_versions(cfn):"""A changed SecretString becomes the new AWSCURRENT on the same secret —same ARN, history kept (the fallback minted a new ARN and dropped it all)."""diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 685984c6..439ea0cb 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -77,6 +77,83 @@ def test_cognito_update_user_pool(cognito_idp):desc = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]assert desc["UserPoolTags"].get("env") == "test"+def test_cognito_user_pool_tier(cognito_idp):+ """UserPoolTier defaults to ESSENTIALS (PLUS with threat protection on), is kept when an update omits it."""+ def tier(pid):+ return cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["UserPoolTier"]++ created = cognito_idp.create_user_pool(PoolName="TierDefault")["UserPool"]+ assert created["UserPoolTier"] == "ESSENTIALS"+ assert tier(created["Id"]) == "ESSENTIALS"+ audit = cognito_idp.create_user_pool(+ PoolName="TierAudit", UserPoolAddOns={"AdvancedSecurityMode": "AUDIT"})["UserPool"]+ assert audit["UserPoolTier"] == "PLUS"+ off = cognito_idp.create_user_pool(+ PoolName="TierOff", UserPoolAddOns={"AdvancedSecurityMode": "OFF"})["UserPool"]+ assert off["UserPoolTier"] == "ESSENTIALS"++ pid = cognito_idp.create_user_pool(PoolName="TierLite", UserPoolTier="LITE")["UserPool"]["Id"]+ assert tier(pid) == "LITE"+ for target in ("PLUS", "LITE", "ESSENTIALS"):+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTier=target)+ assert tier(pid) == target+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTags={"k": "v"})+ assert tier(pid) == "ESSENTIALS"++ for value in ("BASIC", "lite", ""):+ with pytest.raises(ClientError) as exc:+ cognito_idp.create_user_pool(PoolName="TierBad", UserPoolTier=value)+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+ assert exc.value.response["Error"]["Message"] == (+ f"1 validation error detected: Value '{value}' at 'userPoolTier' failed to satisfy "+ "constraint: Member must satisfy enum value set: [ESSENTIALS, LITE, PLUS]")+ with pytest.raises(ClientError) as exc:+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTier="BASIC")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+ assert tier(pid) == "ESSENTIALS"++def test_cognito_user_pool_tier_features(cognito_idp):+ """Threat protection needs a tier other than ESSENTIALS and password history one other than LITE."""+ audit = {"AdvancedSecurityMode": "AUDIT"}+ history = {"PasswordPolicy": {"MinimumLength": 8, "PasswordHistorySize": 3}}++ def refused(code, tier, feature, call, **kwargs):+ with pytest.raises(ClientError) as exc:+ call(**kwargs)+ assert exc.value.response["Error"]["Code"] == code+ assert exc.value.response["Error"]["Message"] == (+ f"The following features need to be disabled for the {tier} pricing tier configured: {feature}")++ refused("FeatureUnavailableInTierException", "ESSENTIALS", "Threat Protection",+ cognito_idp.create_user_pool, PoolName="TierEssAudit", UserPoolTier="ESSENTIALS",+ UserPoolAddOns={"AdvancedSecurityMode": "ENFORCED"})+ refused("FeatureUnavailableInTierException", "LITE", "Password History",+ cognito_idp.create_user_pool, PoolName="TierLiteHistory", UserPoolTier="LITE", Policies=history)+ # LITE keeps threat protection; a zero history size is no history.+ cognito_idp.create_user_pool(PoolName="TierLiteAudit", UserPoolTier="LITE", UserPoolAddOns=audit)+ cognito_idp.create_user_pool(+ PoolName="TierLiteNoHistory", UserPoolTier="LITE",+ Policies={"PasswordPolicy": {"MinimumLength": 8, "PasswordHistorySize": 0}})++ pid = cognito_idp.create_user_pool(PoolName="TierUpdate", UserPoolTier="ESSENTIALS")["UserPool"]["Id"]+ refused("FeatureUnavailableInTierException", "ESSENTIALS", "Threat Protection",+ cognito_idp.update_user_pool, UserPoolId=pid, UserPoolAddOns=audit)+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTier="PLUS", UserPoolAddOns=audit)+ refused("TierChangeNotAllowedException", "ESSENTIALS", "Threat Protection",+ cognito_idp.update_user_pool, UserPoolId=pid, UserPoolTier="ESSENTIALS", UserPoolAddOns=audit)+ assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["UserPoolTier"] == "PLUS"+ # Nothing in this request needs PLUS once UserPoolAddOns is omitted, so the downgrade goes through.+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTier="ESSENTIALS")++ pid = cognito_idp.create_user_pool(PoolName="TierHistory", Policies=history)["UserPool"]["Id"]+ refused("TierChangeNotAllowedException", "LITE", "Password History",+ cognito_idp.update_user_pool, UserPoolId=pid, UserPoolTier="LITE")+ pid = cognito_idp.create_user_pool(PoolName="TierLiteUpdate", UserPoolTier="LITE")["UserPool"]["Id"]+ refused("FeatureUnavailableInTierException", "LITE", "Password History",+ cognito_idp.update_user_pool, UserPoolId=pid, Policies=history)+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTier="ESSENTIALS", Policies=history)+ assert cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]["UserPoolTier"] == "ESSENTIALS"+def test_cognito_delete_user_pool(cognito_idp):resp = cognito_idp.create_user_pool(PoolName="DeletePool")pid = resp["UserPool"]["Id"]@@ -2110,6 +2187,31 @@ def test_cognito_restore_drops_the_old_default_token_validity():mod.reset()+def test_cognito_user_pool_tier_survives_restore():+ """A stored tier round-trips; a pool saved before UserPoolTier describes the CreateUserPool default."""+ from ministack.core.responses import AccountRegionScopedDict++ mod = _cognito_module()+ account, region = "111111111111", "eu-central-1"+ saved = AccountRegionScopedDict()+ saved.set_scoped(account, region, f"{region}_lite", {"Id": f"{region}_lite", "UserPoolTier": "LITE"})+ saved.set_scoped(account, region, f"{region}_old", {"Id": f"{region}_old"})+ saved.set_scoped(account, region, f"{region}_oldaudit",+ {"Id": f"{region}_oldaudit", "UserPoolAddOns": {"AdvancedSecurityMode": "AUDIT"}})+ try:+ mod.reset()+ mod.load_persisted_state({"user_pools": saved})+ state = mod.get_state()+ mod.reset()+ mod.load_persisted_state(state)+ assert {+ pid: mod._pool_out(mod._user_pools.get_scoped(account, region, f"{region}_{pid}"))["UserPoolTier"]+ for pid in ("lite", "old", "oldaudit")+ } == {"lite": "LITE", "old": "ESSENTIALS", "oldaudit": "PLUS"}+ finally:+ mod.reset()++def test_cognito_describe_identity(cognito_identity):resp = cognito_identity.create_identity_pool(IdentityPoolName="DescribeIdPool",