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
Add Cognito resource server support (#1126)
ryan-bennett0e585749b22c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 97877e95..87498644 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Cognito — resource servers** (`CreateResourceServer`, `UpdateResourceServer`, `DescribeResourceServer`, `DeleteResourceServer`, `ListResourceServers`) plus `AWS::Cognito::UserPoolResourceServer` CloudFormation support. Previously every resource-server action returned `InvalidAction: Unknown Cognito IDP action`, and the CFN resource type failed the whole stack with `Unsupported resource type`, so any app pool defining custom OAuth scopes (`{identifier}/{scopeName}`, e.g. for `HttpJwtAuthorizer` `authorizationScopes` gating on API Gateway) couldn't deploy against MiniStack at all. Resource servers are keyed by their caller-supplied `Identifier` within a pool, matching real AWS, and `Ref` on the CFN resource returns that `Identifier`. Contributed by @ryan-bennett.+## [1.4.4] — 2026-07-22### Addeddiff --git a/README.md b/README.mdindex fa8e6416..bb374d2e 100644--- a/README.md+++ b/README.md@@ -498,6 +498,7 @@ subnet = ec2.create_subnet(| `AWS::SecretsManager::Secret` | Secret ARN | — || `AWS::Cognito::UserPool` | Pool ID | Arn, ProviderName || `AWS::Cognito::UserPoolClient` | Client ID | — |+| `AWS::Cognito::UserPoolResourceServer` | Identifier | — || `AWS::Cognito::IdentityPool` | Pool ID | — || `AWS::Cognito::UserPoolDomain` | Domain | — || `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri |@@ -562,7 +563,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, 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, 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 |+| **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, 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 || **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, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL queries/mutations execute against DynamoDB resolvers; Lambda resolvers supported. 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 e42bd062..0d033f49 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2481,6 +2481,7 @@ def _cognito_user_pool_create(logical_id, props, stack_name):"_clients": {},"_users": {},"_groups": {},+ "_resource_servers": {},}_cognito._user_pools[pid] = poolarn = _cognito._pool_arn(pid)@@ -2529,6 +2530,31 @@ def _cognito_user_pool_client_delete(physical_id, props):pool["_clients"].pop(physical_id, None)+# --- Cognito UserPoolResourceServer ---++def _cognito_user_pool_resource_server_create(logical_id, props, stack_name):+ pid = props.get("UserPoolId", "")+ pool = _cognito._user_pools.get(pid)+ if not pool:+ raise ValueError(f"UserPool {pid} not found for UserPoolResourceServer")++ identifier = props.get("Identifier", "")+ server = _cognito._resource_server_dict(+ pid, identifier, props.get("Name", identifier), props.get("Scopes", []),+ )+ # Ref on this resource type returns the Identifier (matches real AWS —+ # see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolresourceserver.html#aws-resource-cognito-userpoolresourceserver-return-values).+ _cognito._pool_resource_servers(pool)[identifier] = server+ return identifier, {}+++def _cognito_user_pool_resource_server_delete(physical_id, props):+ pid = props.get("UserPoolId", "")+ pool = _cognito._user_pools.get(pid)+ if pool:+ _cognito._pool_resource_servers(pool).pop(physical_id, None)++# --- Cognito UserPoolGroup ---def _cognito_user_pool_group_create(logical_id, props, stack_name):@@ -4673,6 +4699,7 @@ _RESOURCE_HANDLERS = {"AWS::SecretsManager::Secret": {"create": _sm_secret_create, "delete": _sm_secret_delete},"AWS::Cognito::UserPool": {"create": _cognito_user_pool_create, "delete": _cognito_user_pool_delete},"AWS::Cognito::UserPoolClient": {"create": _cognito_user_pool_client_create, "delete": _cognito_user_pool_client_delete},+ "AWS::Cognito::UserPoolResourceServer": {"create": _cognito_user_pool_resource_server_create, "delete": _cognito_user_pool_resource_server_delete},"AWS::Cognito::UserPoolGroup": {"create": _cognito_user_pool_group_create, "delete": _cognito_user_pool_group_delete},"AWS::Cognito::IdentityPool": {"create": _cognito_identity_pool_create, "delete": _cognito_identity_pool_delete},"AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 7c3a7c67..fd4bd6bc 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -224,6 +224,7 @@ _user_pools = AccountScopedDict()# _users: {username -> user_dict},# _groups: {group_name -> group_dict},# _identity_providers: {provider_name -> provider_dict},+# _resource_servers: {identifier -> resource_server_dict},# }_pool_domain_map = AccountScopedDict() # domain -> pool_id@@ -1468,6 +1469,12 @@ async def _dispatch_idp(action: str, data: dict):"DescribeUserPoolClient": _describe_user_pool_client,"ListUserPoolClients": _list_user_pool_clients,"UpdateUserPoolClient": _update_user_pool_client,+ # Resource Servers+ "CreateResourceServer": _create_resource_server,+ "UpdateResourceServer": _update_resource_server,+ "DescribeResourceServer": _describe_resource_server,+ "DeleteResourceServer": _delete_resource_server,+ "ListResourceServers": _list_resource_servers,# User management"AdminCreateUser": _admin_create_user,"AdminDeleteUser": _admin_delete_user,@@ -1623,6 +1630,7 @@ def _create_user_pool(data):"_users": {},"_groups": {},"_identity_providers": {},+ "_resource_servers": {},}if data.get("DeviceConfiguration"):pool["DeviceConfiguration"] = data["DeviceConfiguration"]@@ -1812,6 +1820,129 @@ def _update_user_pool_client(data):return json_response({"UserPoolClient": {k: v for k, v in client.items() if v is not None}})+# ---------------------------------------------------------------------------+# Resource Servers+# ---------------------------------------------------------------------------+# Scoped to what CDK/Terraform actually exercise: CRUD + list, keyed by the+# caller-supplied Identifier (not a separately generated id — that matches+# real AWS, where Identifier is also the resource server's primary key+# within a pool and is reused directly in OAuth scope strings as+# "{Identifier}/{ScopeName}").++def _resource_server_dict(pool_id, identifier, name, scopes):+ return {+ "UserPoolId": pool_id,+ "Identifier": identifier,+ "Name": name,+ "Scopes": scopes,+ }+++def _pool_resource_servers(pool):+ # setdefault, not direct indexing — pools created before this field+ # existed (or via a CFN provisioner that builds its own pool dict, e.g.+ # _cognito_user_pool_create) may not have "_resource_servers" yet.+ return pool.setdefault("_resource_servers", {})+++def _create_resource_server(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ resource_servers = _pool_resource_servers(pool)++ identifier = data.get("Identifier")+ if not identifier:+ return error_response_json(+ "InvalidParameterException", "Identifier is required.", 400,+ )+ if identifier in resource_servers:+ return error_response_json(+ "InvalidParameterException",+ f"Resource server {identifier} already exists.", 400,+ )++ server = _resource_server_dict(+ pid, identifier, data.get("Name", identifier), data.get("Scopes", []),+ )+ resource_servers[identifier] = server+ return json_response({"ResourceServer": server})+++def _update_resource_server(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ identifier = data.get("Identifier")+ server = _pool_resource_servers(pool).get(identifier)+ if not server:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource server {identifier} does not exist.", 400,+ )++ if "Name" in data:+ server["Name"] = data["Name"]+ if "Scopes" in data:+ server["Scopes"] = data["Scopes"]+ return json_response({"ResourceServer": server})+++def _describe_resource_server(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ identifier = data.get("Identifier")+ server = _pool_resource_servers(pool).get(identifier)+ if not server:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource server {identifier} does not exist.", 400,+ )+ return json_response({"ResourceServer": server})+++def _delete_resource_server(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ identifier = data.get("Identifier")+ resource_servers = _pool_resource_servers(pool)+ if identifier not in resource_servers:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource server {identifier} does not exist.", 400,+ )+ del resource_servers[identifier]+ return json_response({})+++def _list_resource_servers(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ max_results = min(data.get("MaxResults", 50), 50)+ next_token = data.get("NextToken")+ servers = sorted(+ _pool_resource_servers(pool).values(), key=lambda s: s["Identifier"],+ )+ start = int(next_token) if next_token else 0+ page = servers[start:start + max_results]+ resp = {"ResourceServers": page}+ if start + max_results < len(servers):+ resp["NextToken"] = str(start + max_results)+ return json_response(resp)++def _password_policy_errors(pool, password):"""Return a list of PasswordPolicy violation strings, or [] if compliant."""policy = pool.get("Policies", {}).get("PasswordPolicy", {})diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 21447f7b..c7305f20 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -87,6 +87,74 @@ def test_cognito_list_user_pool_clients(cognito_idp):assert "App1" in namesassert "App2" in names+def test_cognito_create_and_describe_resource_server(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerPool")["UserPool"]["Id"]+ resp = cognito_idp.create_resource_server(+ UserPoolId=pid,+ Identifier="API",+ Name="API",+ Scopes=[{"ScopeName": "resource.get", "ScopeDescription": "Read access"}],+ )+ server = resp["ResourceServer"]+ assert server["Identifier"] == "API"+ assert server["Scopes"] == [{"ScopeName": "resource.get", "ScopeDescription": "Read access"}]++ desc = cognito_idp.describe_resource_server(UserPoolId=pid, Identifier="API")["ResourceServer"]+ assert desc["Identifier"] == "API"+ assert desc["Name"] == "API"++def test_cognito_create_resource_server_duplicate_identifier_error(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerDupPool")["UserPool"]["Id"]+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API", Name="API")+ with pytest.raises(ClientError) as exc:+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API", Name="API")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"++def test_cognito_list_resource_servers(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerListPool")["UserPool"]["Id"]+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API1", Name="API1")+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API2", Name="API2")+ identifiers = [+ s["Identifier"]+ for s in cognito_idp.list_resource_servers(UserPoolId=pid, MaxResults=50)["ResourceServers"]+ ]+ assert "API1" in identifiers+ assert "API2" in identifiers++def test_cognito_update_resource_server(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerUpdatePool")["UserPool"]["Id"]+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API", Name="Old Name")+ updated = cognito_idp.update_resource_server(+ UserPoolId=pid,+ Identifier="API",+ Name="New Name",+ Scopes=[{"ScopeName": "resource.put", "ScopeDescription": "Write access"}],+ )["ResourceServer"]+ assert updated["Name"] == "New Name"+ assert updated["Scopes"] == [{"ScopeName": "resource.put", "ScopeDescription": "Write access"}]++def test_cognito_delete_resource_server(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerDeletePool")["UserPool"]["Id"]+ cognito_idp.create_resource_server(UserPoolId=pid, Identifier="API", Name="API")+ cognito_idp.delete_resource_server(UserPoolId=pid, Identifier="API")+ identifiers = [+ s["Identifier"]+ for s in cognito_idp.list_resource_servers(UserPoolId=pid, MaxResults=50)["ResourceServers"]+ ]+ assert "API" not in identifiers++def test_cognito_resource_server_not_found_errors(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResourceServerNotFoundPool")["UserPool"]["Id"]+ with pytest.raises(ClientError) as exc:+ cognito_idp.describe_resource_server(UserPoolId=pid, Identifier="Missing")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ with pytest.raises(ClientError) as exc:+ cognito_idp.update_resource_server(UserPoolId=pid, Identifier="Missing", Name="x")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ with pytest.raises(ClientError) as exc:+ cognito_idp.delete_resource_server(UserPoolId=pid, Identifier="Missing")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+def test_cognito_admin_create_and_get_user(cognito_idp):pid = cognito_idp.create_user_pool(PoolName="AdminUserPool")["UserPool"]["Id"]cognito_idp.admin_create_user(