Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(cognito): scope state by region (#1245)

Ian Oberste1d8b00d34b0
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 719449cf..6ae003dd 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -50,6 +50,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"ec2": 3,
"ecr": 3,
"cloudtrail": 3,
+ "cognito": 3,
"waf": 3,
"mq": 3,
"mwaa": 3,
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 5263a3a3..f8bd6f14 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -72,12 +72,15 @@ from defusedxml.ElementTree import fromstring as safe_xml_parse
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import (
+ AccountRegionScopedDict,
AccountScopedDict,
error_response_json,
get_account_id,
get_region,
json_response,
new_uuid,
+ set_request_account_id,
+ set_request_region,
)
logger = logging.getLogger("cognito")
@@ -263,7 +266,6 @@ def well_known_openid_configuration(pool_id: str, region: str | None = None, hos
}
return 200, {"Content-Type": "application/json"}, json.dumps(doc).encode()
-REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))
@@ -277,7 +279,7 @@ _SAML_NS = {
# In-memory state — User Pools (cognito-idp)
# ---------------------------------------------------------------------------
-_user_pools = AccountScopedDict()
+_user_pools = AccountRegionScopedDict()
# pool_id -> {
# Id, Name, Arn, CreationDate, LastModifiedDate, Status,
# Policies, Schema, AutoVerifiedAttributes, UsernameAttributes,
@@ -291,7 +293,7 @@ _user_pools = AccountScopedDict()
# _resource_servers: {identifier -> resource_server_dict},
# }
-_pool_domain_map = AccountScopedDict() # domain -> pool_id
+_pool_domain_map = AccountRegionScopedDict() # domain -> pool_id
# ---------------------------------------------------------------------------
# In-memory state — OAuth2 Authorization Codes & Refresh Tokens
@@ -305,7 +307,7 @@ _revoked_tokens: set = set() # refresh-token values invalidated
# In-memory state — Identity Pools (cognito-identity)
# ---------------------------------------------------------------------------
-_identity_pools = AccountScopedDict()
+_identity_pools = AccountRegionScopedDict()
# identity_pool_id -> {
# IdentityPoolId, IdentityPoolName, AllowUnauthenticatedIdentities,
# SupportedLoginProviders, DeveloperProviderName,
@@ -315,7 +317,7 @@ _identity_pools = AccountScopedDict()
# _identities: {identity_id -> identity_dict},
# }
-_identity_tags = AccountScopedDict() # identity_pool_id -> {key: value}
+_identity_tags = AccountRegionScopedDict() # identity_pool_id -> {key: value}
# ---------------------------------------------------------------------------
# In-memory state — OAuth2 authorization codes
@@ -349,6 +351,10 @@ _NEW_PASSWORD_SESSION_TTL = 300 # 5 minutes
# In-memory state — CUSTOM_AUTH Challenge Sessions
# ---------------------------------------------------------------------------
+# Keep challenge sessions account-scoped: signed AdminInitiateAuth can mint a
+# session in any region, while unsigned RespondToAuthChallenge redeems the
+# opaque token without a SigV4 region. The session's pool_id pins downstream
+# regional pool access in the worker context.
_challenge_sessions = AccountScopedDict()
# token (base64-encoded session token, opaque to client) -> {
# 'pool_id': str,
@@ -376,6 +382,25 @@ _MAX_CHALLENGE_ATTEMPTS = 3 # AWS parity — terminate CUSTOM_AUTH after 3 an
# ── Persistence ────────────────────────────────────────────
+_REGION_PREFIX_RE = re.compile(r"^[a-z]+(-[a-z]+)+-\d+$")
+
+
+def _region_from_pool_id(pool_id: str) -> str:
+ if isinstance(pool_id, str) and "_" in pool_id:
+ candidate = pool_id.rsplit("_", 1)[0]
+ if _REGION_PREFIX_RE.match(candidate):
+ return candidate
+ return get_region()
+
+
+def _region_from_identity_id(identity_id: str) -> str:
+ if isinstance(identity_id, str) and ":" in identity_id:
+ candidate = identity_id.split(":", 1)[0]
+ if _REGION_PREFIX_RE.match(candidate):
+ return candidate
+ return get_region()
+
+
def get_state():
return {
"user_pools": copy.deepcopy(_user_pools),
@@ -392,10 +417,26 @@ def get_state():
def restore_state(data):
if data:
- _user_pools.update(data.get("user_pools", {}))
- _pool_domain_map.update(data.get("pool_domain_map", {}))
- _identity_pools.update(data.get("identity_pools", {}))
- _identity_tags.update(data.get("identity_tags", {}))
+ _restore_regional_store(
+ _user_pools,
+ 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", {}),
+ lambda _domain, pool_id: _region_from_pool_id(pool_id),
+ )
+ _restore_regional_store(
+ _identity_pools,
+ data.get("identity_pools", {}),
+ lambda pool_id, _pool: _region_from_identity_id(pool_id),
+ )
+ _restore_regional_store(
+ _identity_tags,
+ data.get("identity_tags", {}),
+ lambda pool_id, _tags: _region_from_identity_id(pool_id),
+ )
_authorization_codes.update(data.get("authorization_codes", {}))
_refresh_tokens.update(data.get("refresh_tokens", {}))
_revoked_tokens.update(data.get("revoked_tokens", []))
@@ -403,6 +444,24 @@ def restore_state(data):
_challenge_sessions.update(data.get("challenge_sessions", {}))
+def _restore_regional_store(store, restored, region_for_item):
+ """Restore a Cognito store, self-placing legacy records from their IDs."""
+ if isinstance(restored, AccountRegionScopedDict):
+ store.update(restored)
+ return
+
+ if isinstance(restored, AccountScopedDict):
+ items = restored._data.items()
+ elif isinstance(restored, dict):
+ account_id = get_account_id()
+ items = (((account_id, key), value) for key, value in restored.items())
+ else:
+ return
+
+ for (account_id, key), value in items:
+ store.set_scoped(account_id, region_for_item(key, value), key, value)
+
+
try:
_restored = load_state("cognito")
if _restored:
@@ -441,11 +500,7 @@ def _pool_region(pool_id: str) -> str:
``eu-isoe-west-1``) — Cognito is available in GovCloud, so the parser must
not silently fall through and reproduce the original `iss` bug there.
"""
- if pool_id and "_" in pool_id:
- candidate = pool_id.rsplit("_", 1)[0]
- if re.match(r"^[a-z]+(-[a-z]+)+-\d+$", candidate):
- return candidate
- return get_region()
+ return _region_from_pool_id(pool_id)
def _client_id() -> str:
@@ -1506,15 +1561,16 @@ def _all_pools():
normal account-scoped iteration would miss pools created under a specific
account. Yields (pool_id, pool_dict) pairs.
"""
- # _user_pools._data stores {(account_id, pool_id): pool_dict}
- for (_, pid), pool in _user_pools._data.items():
+ for (_account_id, _region, pid), pool in _user_pools.all_items():
yield pid, pool
def _get_pool_unscoped(pool_id: str):
- """Look up a pool by ID across ALL accounts."""
- for pid, pool in _all_pools():
+ """Look up a pool globally and pin its owning scope for downstream work."""
+ for (account_id, region, pid), pool in _user_pools.all_items():
if pid == pool_id:
+ set_request_account_id(account_id)
+ set_request_region(region)
return pool
return None
@@ -1526,9 +1582,11 @@ def _find_pool_by_client_id(client_id: str):
browsers without AWS credentials, so the normal account-scoped lookup
would miss pools created under a specific account.
"""
- for pid, pool in _all_pools():
+ for (account_id, region, pid), pool in _user_pools.all_items():
client = pool["_clients"].get(client_id)
if client is not None:
+ set_request_account_id(account_id)
+ set_request_region(region)
return pid, pool, client
return None, None, None
@@ -1623,6 +1681,107 @@ async def handle_request(method, path, headers, body, query_params):
# IDP dispatcher
# ---------------------------------------------------------------------------
+_UNSIGNED_IDP_ACTIONS = {
+ "AssociateSoftwareToken",
+ "ChangePassword",
+ "ConfirmForgotPassword",
+ "ConfirmSignUp",
+ "DeleteUser",
+ "ForgotPassword",
+ "GetTokensFromRefreshToken",
+ "GetUser",
+ "GlobalSignOut",
+ "InitiateAuth",
+ "ResendConfirmationCode",
+ "RespondToAuthChallenge",
+ "RevokeToken",
+ "SetUserMFAPreference",
+ "SignUp",
+ "UpdateUserAttributes",
+ "VerifySoftwareToken",
+}
+
+_UNSIGNED_IDENTITY_ACTIONS = {
+ "GetCredentialsForIdentity",
+ "GetId",
+ "GetOpenIdToken",
+ "UnlinkIdentity",
+}
+
+
+def _pool_id_from_token(token: str) -> str:
+ if not isinstance(token, str) or not token:
+ return ""
+ try:
+ claims = _decode_id_token_unverified(token)
+ except (ValueError, TypeError, json.JSONDecodeError):
+ return ""
+ if not isinstance(claims, dict):
+ return ""
+ issuer = claims.get("iss", "")
+ if not isinstance(issuer, str):
+ return ""
+ return issuer.rsplit("/", 1)[-1] if "/" in issuer else ""
+
+
+def _pool_scope_for_client(client_id: str):
+ """Find a client owner within the ambient account without widening tenants."""
+ if not client_id:
+ return None
+ account_id = get_account_id()
+ request_region = get_region()
+ matches = []
+ for (owner_account, region, pool_id), pool in _user_pools.all_items():
+ if owner_account != account_id or client_id not in pool.get("_clients", {}):
+ continue
+ if region == request_region:
+ return pool_id, region
+ matches.append((pool_id, region))
+ return matches[0] if len(matches) == 1 else None
+
+
+def _pin_unsigned_idp_scope(data: dict) -> None:
+ pool_id = data.get("UserPoolId", "")
+
+ if not pool_id:
+ session = _challenge_sessions.get(data.get("Session", ""))
+ if session:
+ pool_id = session.get("pool_id", "")
+
+ if not pool_id:
+ for field in ("AccessToken", "RefreshToken", "Token"):
+ token = data.get(field, "")
+ if not isinstance(token, str) or not token:
+ continue
+ pool_id = _pool_id_from_token(token)
+ if not pool_id:
+ pool_id = (_refresh_tokens.get(token) or {}).get("pool_id", "")
+ if pool_id:
+ break
+
+ if pool_id:
+ set_request_region(_pool_region(pool_id))
+ return
+
+ client_scope = _pool_scope_for_client(data.get("ClientId", ""))
+ if client_scope:
+ _pool_id, region = client_scope
+ set_request_region(region)
+
+
+def _run_idp_handler(handler, action: str, data: dict):
+ if action in _UNSIGNED_IDP_ACTIONS:
+ _pin_unsigned_idp_scope(data)
+ return handler(data)
+
+
+def _run_identity_handler(handler, action: str, data: dict):
+ if action in _UNSIGNED_IDENTITY_ACTIONS:
+ identity_id = data.get("IdentityPoolId") or data.get("IdentityId")
+ if identity_id:
+ set_request_region(_region_from_identity_id(identity_id))
+ return handler(data)
+
async def _dispatch_idp(action: str, data: dict):
handlers = {
# User Pool CRUD
@@ -1713,7 +1872,7 @@ async def _dispatch_idp(action: str, data: dict):
# back into ministack over HTTP) don't deadlock against a blocked event
# loop. The Lambda response path needs the loop free to accept new
# requests while _execute_function is running.
- return await asyncio.to_thread(handler, data)
+ return await asyncio.to_thread(_run_idp_handler, handler, action, data)
# ---------------------------------------------------------------------------
@@ -1744,7 +1903,7 @@ async def _dispatch_identity(action: str, data: dict):
handler = handlers.get(action)
if not handler:
return error_response_json("InvalidAction", f"Unknown Cognito Identity action: {action}", 400)
- return await asyncio.to_thread(handler, data)
+ return await asyncio.to_thread(_run_identity_handler, handler, action, data)
# ===========================================================================
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index e385bc74..a5e34d3c 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3991,6 +3991,73 @@ Outputs:
assert not without_resp["UserPoolClient"].get("ClientSecret"), "GenerateSecret=false should leave ClientSecret empty"
+def test_cfn_cognito_resources_use_the_stack_region():
+ import boto3
+ from botocore.config import Config
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ def _client(service, region):
+ return boto3.client(
+ service,
+ endpoint_url=endpoint,
+ region_name=region,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ config=Config(retries={"mode": "standard"}),
+ )
+
+ west_cfn = _client("cloudformation", "us-west-2")
+ west_cognito = _client("cognito-idp", "us-west-2")
+ east_cognito = _client("cognito-idp", "us-east-1")
+ suffix = _uuid_mod.uuid4().hex[:10]
+ stack_name = f"cfn-cognito-west-{suffix}"
+ domain = f"cfn-cognito-west-{suffix}"
+ template = f"""
+AWSTemplateFormatVersion: '2010-09-09'
+Resources:
+ Pool:
+ Type: AWS::Cognito::UserPool
+ Properties:
+ UserPoolName: {stack_name}
+ Client:
+ Type: AWS::Cognito::UserPoolClient
+ Properties:
+ UserPoolId: !Ref Pool
+ ClientName: west-client
+ Domain:
+ Type: AWS::Cognito::UserPoolDomain
+ Properties:
+ UserPoolId: !Ref Pool
+ Domain: {domain}
+Outputs:
+ PoolId:
+ Value: !Ref Pool
+ ClientId:
+ Value: !Ref Client
+"""
+
+ west_cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ stack = _wait_stack(west_cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ outputs = {output["OutputKey"]: output["OutputValue"] for output in stack["Outputs"]}
+
+ west_cognito.describe_user_pool(UserPoolId=outputs["PoolId"])
+ west_cognito.describe_user_pool_client(
+ UserPoolId=outputs["PoolId"], ClientId=outputs["ClientId"]
+ )
+ assert west_cognito.describe_user_pool_domain(Domain=domain)["DomainDescription"][
+ "UserPoolId"
+ ] == outputs["PoolId"]
+
+ assert outputs["PoolId"] not in {
+ pool["Id"] for pool in east_cognito.list_user_pools(MaxResults=60)["UserPools"]
+ }
+ with pytest.raises(ClientError) as exc:
+ east_cognito.describe_user_pool(UserPoolId=outputs["PoolId"])
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
def test_cfn_cognito_user_pool_group(cfn, cognito_idp):
"""CFN AWS::Cognito::UserPoolGroup creates a group whose Ref resolves to
its GroupName, matching real AWS, and admin_add_user_to_group can then
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index ad1d1748..dda5647c 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2438,10 +2438,18 @@ from conftest import ENDPOINT, make_client
# Helpers
# ---------------------------------------------------------------------------
-def _setup_pool_with_user(cognito_idp, generate_secret=True, force_change_password=False):
+def _setup_pool_with_user(
+ cognito_idp,
+ generate_secret=True,
+ force_change_password=False,
+ lambda_config=None,
+):
"""Create a user pool with a confirmed (or FORCE_CHANGE_PASSWORD) user and an
OAuth-enabled client."""
- pool = cognito_idp.create_user_pool(PoolName='OAuth2TestPool')
+ pool = cognito_idp.create_user_pool(
+ PoolName='OAuth2TestPool',
+ **({"LambdaConfig": lambda_config} if lambda_config else {}),
+ )
pool_id = pool['UserPool']['Id']
client_kwargs = {
@@ -3427,6 +3435,106 @@ def test_oauth2_full_flow():
assert headers.get('location', '') == 'http://localhost:3000/logout'
+def test_oauth2_full_flow_for_non_boot_region_pool():
+ """Public discovery and hosted UI remain unscoped for regional pools."""
+ cognito_idp = _regional_cognito_client("cognito-idp", "eu-central-1")
+ lam = _regional_cognito_client("lambda", "eu-central-1")
+ function_name = f"regional-hosted-pretoken-{_uuid_mod.uuid4().hex[:10]}"
+ handler = (
+ "def handler(event, ctx):\n"
+ " event['response']['claimsAndScopeOverrideDetails'] = {\n"
+ " 'accessTokenGeneration': {\n"
+ " 'claimsToAddOrOverride': {'hosted_region': 'eu-central-1'},\n"
+ " },\n"
+ " }\n"
+ " return event\n"
+ )
+ lam.create_function(
+ FunctionName=function_name,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": _make_pretoken_lambda_zip(handler)},
+ )
+ function_arn = lam.get_function(FunctionName=function_name)["Configuration"][
+ "FunctionArn"
+ ]
+ pool_id, client = _setup_pool_with_user(
+ cognito_idp,
+ lambda_config={
+ "PreTokenGenerationConfig": {
+ "LambdaArn": function_arn,
+ "LambdaVersion": "V2_0",
+ }
+ },
+ )
+ client_id = client["ClientId"]
+
+ with urllib.request.urlopen(
+ f"{ENDPOINT}/{pool_id}/.well-known/jwks.json", timeout=10
+ ) as response:
+ assert json.loads(response.read())["keys"]
+ with urllib.request.urlopen(
+ f"{ENDPOINT}/{pool_id}/.well-known/openid-configuration", timeout=10
+ ) as response:
+ discovery = json.loads(response.read())
+ assert discovery["issuer"] == (
+ f"https://cognito-idp.eu-central-1.amazonaws.com/{pool_id}"
+ )
+
+ authorize_url = (
+ f"{ENDPOINT}/oauth2/authorize?response_type=code"
+ f"&client_id={client_id}"
+ f"&redirect_uri=http://localhost:3000/callback"
+ f"&scope=openid+email&state=regional-state"
+ )
+ status, _, body = _get(authorize_url)
+ assert status == 200
+ assert "<form" in body.decode("utf-8")
+
+ status, headers, _ = _post_form(
+ f"{ENDPOINT}/login",
+ {
+ "username": "testuser",
+ "password": "TestPass1!",
+ "client_id": client_id,
+ "redirect_uri": "http://localhost:3000/callback",
+ "scope": "openid email",
+ "state": "regional-state",
+ "response_type": "code",
+ },
+ follow_redirects=False,
+ )
+ assert status == 302
+ code = urllib.parse.parse_qs(
+ urllib.parse.urlparse(headers["location"]).query
+ )["code"][0]
+
+ status, _, body = _post_form(
+ f"{ENDPOINT}/oauth2/token",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": "http://localhost:3000/callback",
+ "client_id": client_id,
+ "client_secret": client["ClientSecret"],
+ },
+ )
+ assert status == 200
+ tokens = json.loads(body)
+ claims = _decode_jwt_claims(tokens["access_token"])
+ assert claims["iss"] == f"https://cognito-idp.eu-central-1.amazonaws.com/{pool_id}"
+ assert claims["hosted_region"] == "eu-central-1"
+
+ request = urllib.request.Request(
+ f"{ENDPOINT}/oauth2/userInfo",
+ headers={"Authorization": f"Bearer {tokens['access_token']}"},
+ )
+ with urllib.request.urlopen(request, timeout=10) as response:
+ user_info = json.loads(response.read())
+ assert user_info["cognito:username"] == "testuser"
+
+
# ========== from test_cognito_auth_codes_persistence.py ==========
# Two distinct OAuth2 code stores exist in services/cognito.py:
# - _authorization_codes — managed-login PKCE flow (already persisted)
@@ -4152,6 +4260,430 @@ def test_cognito_pool_region_parser_govcloud():
)
+def _regional_cognito_client(service: str, region: str):
+ import boto3
+
+ return boto3.client(
+ service,
+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name=region,
+ )
+
+
+def test_cognito_user_pools_and_domains_are_region_scoped():
+ east = _regional_cognito_client("cognito-idp", "us-east-1")
+ west = _regional_cognito_client("cognito-idp", "us-west-2")
+ suffix = _uuid_mod.uuid4().hex[:10]
+
+ east_pool = east.create_user_pool(PoolName=f"shared-{suffix}")["UserPool"]["Id"]
+ west_pool = west.create_user_pool(PoolName=f"shared-{suffix}")["UserPool"]["Id"]
+
+ east_pool_ids = {
+ pool["Id"]
+ for page in east.get_paginator("list_user_pools").paginate(MaxResults=60)
+ for pool in page["UserPools"]
+ }
+ west_pool_ids = {
+ pool["Id"]
+ for page in west.get_paginator("list_user_pools").paginate(MaxResults=60)
+ for pool in page["UserPools"]
+ }
+ assert east_pool in east_pool_ids
+ assert west_pool not in east_pool_ids
+ assert west_pool in west_pool_ids
+ assert east_pool not in west_pool_ids
+ with pytest.raises(ClientError) as exc:
+ east.describe_user_pool(UserPoolId=west_pool)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ for operation, kwargs in (
+ (east.create_user_pool_client, {"UserPoolId": west_pool, "ClientName": "wrong-region"}),
+ (east.admin_create_user, {"UserPoolId": west_pool, "Username": "wrong-region"}),
+ (east.create_group, {"UserPoolId": west_pool, "GroupName": "wrong-region"}),
+ ):
+ with pytest.raises(ClientError) as exc:
+ operation(**kwargs)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ domain = f"shared-{suffix}"
+ east.create_user_pool_domain(UserPoolId=east_pool, Domain=domain)
+ west.create_user_pool_domain(UserPoolId=west_pool, Domain=domain)
+ assert east.describe_user_pool_domain(Domain=domain)["DomainDescription"]["UserPoolId"] == east_pool
+ assert west.describe_user_pool_domain(Domain=domain)["DomainDescription"]["UserPoolId"] == west_pool
+
+ second_east_pool = east.create_user_pool(PoolName=f"duplicate-{suffix}")["UserPool"]["Id"]
+ with pytest.raises(ClientError) as exc:
+ east.create_user_pool_domain(UserPoolId=second_east_pool, Domain=domain)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+
+
+def test_cognito_unsigned_user_pool_operations_pin_the_owning_region():
+ west = _regional_cognito_client("cognito-idp", "eu-central-1")
+ suffix = _uuid_mod.uuid4().hex[:10]
+ pool_id = west.create_user_pool(PoolName=f"unsigned-{suffix}")["UserPool"]["Id"]
+ client_id = west.create_user_pool_client(
+ UserPoolId=pool_id,
+ ClientName=f"unsigned-{suffix}",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+
+ west.admin_create_user(
+ UserPoolId=pool_id,
+ Username="challenge-user",
+ TemporaryPassword="TempPass1!",
+ )
+ challenge = west.initiate_auth(
+ ClientId=client_id,
+ AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "challenge-user", "PASSWORD": "TempPass1!"},
+ )
+ assert challenge["ChallengeName"] == "NEW_PASSWORD_REQUIRED"
+ west.respond_to_auth_challenge(
+ ClientId=client_id,
+ ChallengeName="NEW_PASSWORD_REQUIRED",
+ Session=challenge["Session"],
+ ChallengeResponses={"USERNAME": "challenge-user", "NEW_PASSWORD": "ChallengePass1!"},
+ )
+
+ west.sign_up(
+ ClientId=client_id,
+ Username="public-user",
+ Password="PublicPass1!",
+ UserAttributes=[{"Name": "email", "Value": f"{suffix}@example.com"}],
+ )
+ west.resend_confirmation_code(ClientId=client_id, Username="public-user")
+ west.confirm_sign_up(ClientId=client_id, Username="public-user", ConfirmationCode="123456")
+ west.forgot_password(ClientId=client_id, Username="public-user")
+ west.confirm_forgot_password(
+ ClientId=client_id,
+ Username="public-user",
+ ConfirmationCode="654321",
+ Password="ResetPass1!",
+ )
+
+ auth = west.initiate_auth(
+ ClientId=client_id,
+ AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "public-user", "PASSWORD": "ResetPass1!"},
+ )["AuthenticationResult"]
+ access_token = auth["AccessToken"]
+ refresh_token = auth["RefreshToken"]
+
+ assert west.get_user(AccessToken=access_token)["Username"] == "public-user"
+ west.update_user_attributes(
+ AccessToken=access_token,
+ UserAttributes=[{"Name": "name", "Value": "Regional User"}],
+ )
+ west.change_password(
+ AccessToken=access_token,
+ PreviousPassword="ResetPass1!",
+ ProposedPassword="ChangedPass1!",
+ )
+ software_token = west.associate_software_token(AccessToken=access_token)
+ assert software_token["SecretCode"]
+ assert west.verify_software_token(
+ AccessToken=access_token,
+ UserCode="123456",
+ )["Status"] == "SUCCESS"
+ west.set_user_mfa_preference(
+ AccessToken=access_token,
+ SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True},
+ )
+ refreshed = west.get_tokens_from_refresh_token(
+ ClientId=client_id,
+ RefreshToken=refresh_token,
+ )
+ assert refreshed["AuthenticationResult"]["AccessToken"]
+ west.revoke_token(Token=refresh_token, ClientId=client_id)
+ west.global_sign_out(AccessToken=access_token)
+
+ west.admin_create_user(UserPoolId=pool_id, Username="delete-user")
+ west.admin_set_user_password(
+ UserPoolId=pool_id,
+ Username="delete-user",
+ Password="DeletePass1!",
+ Permanent=True,
+ )
+ delete_access_token = west.initiate_auth(
+ ClientId=client_id,
+ AuthFlow="USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "delete-user", "PASSWORD": "DeletePass1!"},
+ )["AuthenticationResult"]["AccessToken"]
+ west.delete_user(AccessToken=delete_access_token)
+ with pytest.raises(ClientError) as exc:
+ west.admin_get_user(UserPoolId=pool_id, Username="delete-user")
+ assert exc.value.response["Error"]["Code"] == "UserNotFoundException"
+
+
+def test_cognito_client_and_hosted_scans_preserve_account_boundaries():
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+
+ mod = _cognito_module()
+ original_account = get_account_id()
+ original_region = get_region()
+ owner_account = "111111111111"
+ foreign_account = "222222222222"
+ pool_id = "us-west-2_accountscope"
+ client_id = "account-scoped-client"
+
+ try:
+ mod.reset()
+ set_request_account_id(owner_account)
+ set_request_region("us-west-2")
+ mod._user_pools[pool_id] = {"_clients": {client_id: {}}}
+
+ set_request_account_id(foreign_account)
+ set_request_region("us-east-1")
+ assert mod._pool_scope_for_client(client_id) is None
+
+ set_request_account_id(owner_account)
+ assert mod._pool_scope_for_client(client_id) == (pool_id, "us-west-2")
+
+ set_request_account_id(foreign_account)
+ set_request_region("us-east-1")
+ assert mod._get_pool_unscoped(pool_id) is mod._user_pools.get_scoped(
+ owner_account, "us-west-2", pool_id
+ )
+ assert get_account_id() == owner_account
+ assert get_region() == "us-west-2"
+
+ set_request_account_id(foreign_account)
+ set_request_region("us-east-1")
+ found_pool_id, found_pool, found_client = mod._find_pool_by_client_id(
+ client_id
+ )
+ assert found_pool_id == pool_id
+ assert found_pool is mod._user_pools.get_scoped(
+ owner_account, "us-west-2", pool_id
+ )
+ assert found_client == {}
+ assert get_account_id() == owner_account
+ assert get_region() == "us-west-2"
+ finally:
+ mod.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+ ("action", "payload_kind"),
+ (
+ ("GetUser", "user_pool_id"),
+ ("RespondToAuthChallenge", "session"),
+ ("GetUser", "access_token"),
+ ("GetTokensFromRefreshToken", "refresh_token"),
+ ("RevokeToken", "token"),
+ ("SignUp", "client_id"),
+ ),
+)
+def test_cognito_unsigned_idp_operations_pin_each_payload_path(
+ action, payload_kind
+):
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+
+ mod = _cognito_module()
+ original_account = get_account_id()
+ original_region = get_region()
+ owner_account = "111111111111"
+ owner_region = "eu-central-1"
+ pool_id = f"{owner_region}_unsignedpin"
+ client_id = "unsigned-pin-client"
+ session = "unsigned-pin-session"
+ opaque_token = "unsigned-pin-opaque-token"
+ header = base64.urlsafe_b64encode(b'{"alg":"none"}').rstrip(b"=").decode()
+ claims = base64.urlsafe_b64encode(
+ json.dumps(
+ {"iss": f"https://cognito-idp.{owner_region}.amazonaws.com/{pool_id}"}
+ ).encode()
+ ).rstrip(b"=").decode()
+ access_token = f"{header}.{claims}.signature"
+ payloads = {
+ "user_pool_id": {"UserPoolId": pool_id},
+ "session": {"Session": session},
+ "access_token": {"AccessToken": access_token},
+ "refresh_token": {"RefreshToken": opaque_token},
+ "token": {"Token": opaque_token},
+ "client_id": {"ClientId": client_id},
+ }
+
+ try:
+ mod.reset()
+ set_request_account_id(owner_account)
+ set_request_region(owner_region)
+ mod._user_pools[pool_id] = {"_clients": {client_id: {}}}
+ mod._challenge_sessions[session] = {"pool_id": pool_id}
+ mod._refresh_tokens[opaque_token] = {"pool_id": pool_id}
+
+ set_request_region("us-east-1")
+ assert mod._run_idp_handler(
+ lambda _data: (get_account_id(), get_region()),
+ action,
+ payloads[payload_kind],
+ ) == (owner_account, owner_region)
+ finally:
+ mod.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_cognito_unsigned_identity_operations_pin_the_owning_region():
+ west = _regional_cognito_client("cognito-identity", "us-west-2")
+ east = _regional_cognito_client("cognito-identity", "us-east-1")
+ pool_id = west.create_identity_pool(
+ IdentityPoolName=f"regional-{_uuid_mod.uuid4().hex[:10]}",
+ AllowUnauthenticatedIdentities=True,
+ )["IdentityPoolId"]
+ pool_arn = _identity_pool_arn(pool_id, region="us-west-2")
+ west.tag_resource(ResourceArn=pool_arn, Tags={"scope": "west"})
+ assert west.list_tags_for_resource(ResourceArn=pool_arn)["Tags"] == {
+ "scope": "west"
+ }
+ with pytest.raises(ClientError) as exc:
+ east.list_tags_for_resource(ResourceArn=pool_arn)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ identity_id = west.get_id(
+ AccountId="000000000000",
+ IdentityPoolId=pool_id,
+ )["IdentityId"]
+ assert identity_id.startswith("us-west-2:")
+ assert west.get_credentials_for_identity(IdentityId=identity_id)["Credentials"]["AccessKeyId"]
+ assert west.get_open_id_token(IdentityId=identity_id)["Token"]
+ west.unlink_identity(IdentityId=identity_id, Logins={}, LoginsToRemove=[])
+
+ from ministack.core.responses import get_region, set_request_region
+
+ mod = _cognito_module()
+ original_region = get_region()
+ try:
+ for action, data in (
+ ("GetId", {"IdentityPoolId": pool_id}),
+ ("GetCredentialsForIdentity", {"IdentityId": identity_id}),
+ ("GetOpenIdToken", {"IdentityId": identity_id}),
+ ("UnlinkIdentity", {"IdentityId": identity_id}),
+ ):
+ set_request_region("us-east-1")
+ assert mod._run_identity_handler(
+ lambda _data: get_region(), action, data
+ ) == "us-west-2"
+ finally:
+ set_request_region(original_region)
+
+ assert pool_id not in {
+ pool["IdentityPoolId"]
+ for pool in east.list_identity_pools(MaxResults=60)["IdentityPools"]
+ }
+ with pytest.raises(ClientError) as exc:
+ east.describe_identity_pool(IdentityPoolId=pool_id)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_cognito_unsigned_token_pinning_rejects_non_object_claims():
+ cognito_idp = _regional_cognito_client("cognito-idp", "us-east-1")
+
+ def _token(payload):
+ header = base64.urlsafe_b64encode(b'{"alg":"none"}').rstrip(b"=").decode()
+ body = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=").decode()
+ return f"{header}.{body}.signature"
+
+ for payload in ([], {"iss": 123}):
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.get_user(AccessToken=_token(payload))
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+
+ for token in ([], {}, 123, True):
+ request = urllib.request.Request(
+ ENDPOINT,
+ data=json.dumps({"AccessToken": token}).encode(),
+ headers={
+ "Content-Type": "application/x-amz-json-1.1",
+ "X-Amz-Target": "AWSCognitoIdentityProviderService.GetUser",
+ },
+ method="POST",
+ )
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(request, timeout=10)
+ assert exc.value.code == 400
+ assert json.loads(exc.value.read())["__type"].endswith(
+ "NotAuthorizedException"
+ )
+
+
+def test_cognito_legacy_state_self_places_by_pool_ids():
+ from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+
+ mod = _cognito_module()
+ original_account = get_account_id()
+ original_region = get_region()
+ account = "111111111111"
+ user_pool_id = "us-west-2_legacy123"
+ identity_pool_id = "us-west-2:00000000-0000-4000-8000-000000000001"
+
+ legacy_user_pools = AccountScopedDict()
+ legacy_user_pools._data[(account, user_pool_id)] = {"Id": user_pool_id, "Name": "legacy"}
+ legacy_domains = AccountScopedDict()
+ legacy_domains._data[(account, "legacy-domain")] = user_pool_id
+ legacy_identity_pools = AccountScopedDict()
+ legacy_identity_pools._data[(account, identity_pool_id)] = {
+ "IdentityPoolId": identity_pool_id,
+ "IdentityPoolName": "legacy",
+ }
+ legacy_identity_tags = AccountScopedDict()
+ legacy_identity_tags._data[(account, identity_pool_id)] = {"env": "legacy"}
+
+ try:
+ mod.reset()
+ set_request_account_id(account)
+ set_request_region("us-east-1")
+ mod.restore_state({
+ "user_pools": legacy_user_pools,
+ "pool_domain_map": legacy_domains,
+ "identity_pools": legacy_identity_pools,
+ "identity_tags": legacy_identity_tags,
+ })
+
+ assert mod._user_pools.get_scoped(account, "us-west-2", user_pool_id)["Name"] == "legacy"
+ assert mod._user_pools.get_scoped(account, "us-east-1", user_pool_id) is None
+ assert mod._pool_domain_map.get_scoped(account, "us-west-2", "legacy-domain") == user_pool_id
+ assert mod._identity_pools.get_scoped(account, "us-west-2", identity_pool_id)[
+ "IdentityPoolName"
+ ] == "legacy"
+ assert mod._identity_tags.get_scoped(account, "us-west-2", identity_pool_id) == {
+ "env": "legacy"
+ }
+
+ v3 = AccountRegionScopedDict()
+ v3.set_scoped(account, "eu-central-1", "eu-central-1_v3", {"Name": "v3"})
+ mod.reset()
+ mod.restore_state({"user_pools": v3})
+ assert mod._user_pools.get_scoped(account, "eu-central-1", "eu-central-1_v3") == {
+ "Name": "v3"
+ }
+ finally:
+ mod.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
def test_cognito_pool_arn_uses_pool_region():
"""`_pool_arn` must encode the pool's region, not the request region.
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 7d715301..848510ff 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -3883,6 +3883,93 @@ def test_waf_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path)
assert persistence.load_state("waf") is None
+def test_cognito_region_scoped_state_round_trips_and_is_rejected_by_v2_reader(
+ monkeypatch, tmp_path
+):
+ import json as _json
+
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import cognito
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account = "111111111111"
+ pool_id = "us-west-2_roundtrip"
+ identity_pool_id = "us-west-2:00000000-0000-4000-8000-000000000002"
+
+ def _legacy_store(key, value):
+ store = AccountScopedDict()
+ store._data[(account, key)] = value
+ return store
+
+ legacy_payload = {
+ "user_pools": _legacy_store(
+ pool_id, {"Id": pool_id, "Name": "roundtrip"}
+ ),
+ "pool_domain_map": _legacy_store("roundtrip-domain", pool_id),
+ "identity_pools": _legacy_store(
+ identity_pool_id,
+ {
+ "IdentityPoolId": identity_pool_id,
+ "IdentityPoolName": "roundtrip",
+ },
+ ),
+ "identity_tags": _legacy_store(identity_pool_id, {"scope": "west"}),
+ }
+ (tmp_path / "cognito.json").write_text(
+ _json.dumps(
+ {"__ministack_format__": 2, "payload": legacy_payload},
+ default=persistence._json_default,
+ )
+ )
+
+ try:
+ set_request_account_id(account)
+ set_request_region("us-east-1")
+ cognito.reset()
+ cognito.restore_state(persistence.load_state("cognito"))
+
+ assert cognito._user_pools.get_scoped(
+ account, "us-west-2", pool_id
+ )["Name"] == "roundtrip"
+ assert cognito._user_pools.get_scoped(
+ account, "us-east-1", pool_id
+ ) is None
+ assert cognito._pool_domain_map.get_scoped(
+ account, "us-west-2", "roundtrip-domain"
+ ) == pool_id
+ assert cognito._identity_pools.get_scoped(
+ account, "us-west-2", identity_pool_id
+ )["IdentityPoolName"] == "roundtrip"
+ assert cognito._identity_tags.get_scoped(
+ account, "us-west-2", identity_pool_id
+ ) == {"scope": "west"}
+
+ persistence.save_state("cognito", cognito.get_state())
+ raw = _json.loads((tmp_path / "cognito.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded = persistence.load_state("cognito")["user_pools"]
+ assert loaded.get_scoped(account, "us-west-2", pool_id)[
+ "Name"
+ ] == "roundtrip"
+
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("cognito") is None
+ 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
diff --git a/tests/test_tagging.py b/tests/test_tagging.py
index 7955c877..85cddd92 100644
--- a/tests/test_tagging.py
+++ b/tests/test_tagging.py
@@ -392,6 +392,41 @@ def test_tagging_get_resources_cognito_identity(tagging, cognito_identity):
assert any(pool_id in a for a in arns)
+def test_tagging_get_resources_cognito_is_region_scoped():
+ east_idp = _regional_client("cognito-idp", "us-east-1")
+ west_idp = _regional_client("cognito-idp", "us-west-2")
+ east_tagging = _regional_client("resourcegroupstaggingapi", "us-east-1")
+ west_tagging = _regional_client("resourcegroupstaggingapi", "us-west-2")
+ tag_value = f"cognito-region-{_uid()}"
+
+ east_pool = east_idp.create_user_pool(
+ PoolName=f"east-{tag_value}",
+ UserPoolTags={_TAG_KEY: tag_value},
+ )["UserPool"]
+ west_pool = west_idp.create_user_pool(
+ PoolName=f"west-{tag_value}",
+ UserPoolTags={_TAG_KEY: tag_value},
+ )["UserPool"]
+
+ east_arns = {
+ resource["ResourceARN"]
+ for resource in east_tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": [tag_value]}]
+ )["ResourceTagMappingList"]
+ }
+ west_arns = {
+ resource["ResourceARN"]
+ for resource in west_tagging.get_resources(
+ TagFilters=[{"Key": _TAG_KEY, "Values": [tag_value]}]
+ )["ResourceTagMappingList"]
+ }
+
+ assert east_pool["Arn"] in east_arns
+ assert west_pool["Arn"] not in east_arns
+ assert west_pool["Arn"] in west_arns
+ assert east_pool["Arn"] not in west_arns
+
+
def test_tagging_get_resources_appsync(tagging, appsync):
api_id = appsync.create_graphql_api(
name="tg-appsync-api",