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 user pools + identity pools + pipy module, 525 tests (v… (#18)
Nahuel Nucerab22a11c543a2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 86d2c8a1..96b00a99 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -35,7 +35,7 @@ jobs:- name: Start MiniStackrun: |- REDIS_HOST=localhost python -m uvicorn app:app --host 0.0.0.0 --port 4566 &+ REDIS_HOST=localhost python -m uvicorn ministack.app:app --host 0.0.0.0 --port 4566 &sleep 3curl -sf http://localhost:4566/_localstack/healthdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80227e48..ec07d24a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,54 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.0] — 2026-03-28++### Added+- **Amazon Cognito** (`ministack/services/cognito.py`) — full User Pool and Identity Pool emulation+ - **User Pools (cognito-idp)**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool+ - **User Pool Clients**: CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient+ - **User management**: AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers (with filter support: `=`, `^=`, `!=`), AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut+ - **Auth flows**: AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge — ADMIN_USER_PASSWORD_AUTH, ADMIN_NO_SRP_AUTH, USER_PASSWORD_AUTH, REFRESH_TOKEN_AUTH / REFRESH_TOKEN (both accepted), USER_SRP_AUTH (returns PASSWORD_VERIFIER challenge); FORCE_CHANGE_PASSWORD challenge on first login+ - **Self-service**: SignUp (always UNCONFIRMED — AutoVerifiedAttributes verifies the attribute, not the account), ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword (decodes access token and updates stored password), GetUser, UpdateUserAttributes, DeleteUser, GlobalSignOut, RevokeToken+ - **Groups**: CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents+ - **Domain**: CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain+ - **MFA**: GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken+ - **Tags**: TagResource, UntagResource, ListTagsForResource+ - **Identity Pools (cognito-identity)**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource+ - **OAuth2**: `POST /oauth2/token` — client_credentials flow; returns stub Bearer token+ - Stub JWT tokens: structurally valid base64url JWTs (non-cryptographic); IDP pool ARN format `arn:aws:cognito-idp:region:account:userpool/{id}`; Identity pool ID format `region:{uuid}`+ - `_user_from_token` shared helper — decodes stub JWT payload to find user by `sub`, used by GetUser, UpdateUserAttributes, DeleteUser, ChangePassword, and REFRESH_TOKEN_AUTH+ - Wired into router, SERVICE_HANDLERS, SERVICE_NAME_ALIASES, `_reset_all_state()`, and both credential scopes (`cognito-idp`, `cognito-identity`)+ - 43 integration tests covering full CRUD lifecycle for User Pools, Pool Clients, Users, Auth flows, Refresh tokens, Groups, Domains, MFA, Tags, and Identity Pools++### Changed+- **Package restructure**: all source code moved into `ministack/` package (`ministack/app.py`, `ministack/core/`, `ministack/services/`) — fixes `pip install ministack` entrypoint crash (`app:main` was unresolvable because `app.py` was not included in the wheel)+- **Entrypoint**: `ministack = "app:main"` → `ministack = "ministack.app:main"`+- **ASGI module**: `app:app` → `ministack.app:app` in Dockerfile and CI+- **PyPI trusted publishing**: OIDC workflow added (`pypi-publish.yml`) — no API token needed, publishes on `v*.*.*` tag push++### Fixed+- **Lambda `GetFunctionConcurrency`**: returns `{}` instead of 404 after `DeleteFunctionConcurrency` — matches AWS behaviour where an unset concurrency limit returns an empty response+- **Cognito `GetCredentialsForIdentity`**: response field is `SecretKey` (correct boto3 wire name) — was incorrectly named `SecretAccessKey`+- **ElastiCache `ModifyCacheParameterGroup` / `ResetCacheParameterGroup`**: parameter list key was `ParameterNameValues.member.{n}.*` — corrected to `ParameterNameValues.ParameterNameValue.{n}.*` matching actual boto3 Query API serialisation+- **RDS / ElastiCache / ECS `reset()`**: `container.remove()` → `container.remove(v=True)` — Docker volumes created by stopped containers are now removed along with the container, preventing anonymous volume accumulation across test runs+- **RDS `containers.run()`**: added `tmpfs` mount for `/var/lib/postgresql/data` and `/var/lib/mysql` — postgres/mysql data lives in container RAM; no anonymous Docker volumes created per instance+- **Docker Compose**: added `build: .` so `docker compose up --build` uses local source instead of always pulling from Docker Hub++### Infrastructure+- **`Makefile` `purge` target**: kills all containers labelled `ministack`, prunes dangling volumes, and clears `./data/s3/` — safe to run alongside other projects (filter is label-scoped, not image-scoped)++### Tests+- 3 package structure tests: `test_package_core_importable`, `test_package_services_importable`, `test_app_asgi_callable`+- Merged all 97 tests from `test_qa_comprehensive.py` into `test_services.py` — single test file, `test_qa_comprehensive.py` deleted+- Fixed `test_cognito_get_id_and_credentials`: `SecretAccessKey` → `SecretKey`+- Fixed `test_apigwv1_usage_plan_key_crud`: `Name`/`Enabled` → `name`/`enabled` (boto3 lowercase params)+- Fixed `test_lambda_reset_terminates_workers`: timeout 5 s → 15 s with 3-attempt retry+- Fixed `test_rds_snapshot_crud` / `test_rds_deletion_protection`: added `finally` cleanup so RDS containers are deleted after each test+- 613 integration tests — all passing against Docker image++---+## [1.0.8] — 2026-03-28### Addeddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ce2cf8ac..aaef2381 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,23 +1,45 @@# Contributing to MiniStack-Thanks for wanting to contribute. The codebase is intentionally simple — each AWS service is a single self-contained Python file. Adding a new service or fixing a bug should take minutes, not hours.+Thanks for wanting to contribute. The codebase is intentionally simple — each AWS service is a single self-contained Python file inside `ministack/services/`. Adding a new service or fixing a bug should take minutes, not hours.++## Project Structure++```+ministack/+├── ministack/+│ ├── app.py # ASGI entry point, service routing, reset endpoint+│ ├── core/+│ │ ├── responses.py # json_response, error_response_json, new_uuid+│ │ ├── router.py # detect_service(), SERVICE_PATTERNS+│ │ ├── lambda_runtime.py+│ │ └── persistence.py+│ └── services/+│ ├── s3.py, sqs.py, sns.py, dynamodb.py, ...+│ └── cognito.py # example of a two-client service file+├── tests/+│ ├── conftest.py # pytest fixtures (boto3 clients)+│ └── test_services.py # all integration tests+├── Dockerfile+├── pyproject.toml+└── CHANGELOG.md+```## Adding a New ServiceEvery service follows the same 4-step pattern:-### 1. Create `services/myservice.py`+### 1. Create `ministack/services/myservice.py````python"""MyService Emulator.-JSON-based API via X-Amz-Target (or Query API).+JSON-based API via X-Amz-Target.Supports: OperationOne, OperationTwo, ..."""import jsonimport logging-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("myservice")@@ -48,24 +70,26 @@ async def handle_request(method, path, headers, body, query_params):def _operation_one(data):- # implementreturn json_response({"result": "ok"})def _operation_two(data):- # implementreturn json_response({})+++def reset():+ _state.clear()```**Protocol guide:**-- JSON services (DynamoDB, SecretsManager, Glue, Athena, etc.) — use `json_response` / `error_response_json`, route via `X-Amz-Target`+- JSON services (DynamoDB, SecretsManager, Glue, Athena, Cognito, etc.) — use `json_response` / `error_response_json`, route via `X-Amz-Target`- XML services (S3, SQS, SNS, IAM, RDS, ElastiCache) — build XML responses, route via `Action` query param-- REST services (Lambda, ECS) — route via URL path+- REST services (Lambda, ECS, Route53) — route via URL path-### 2. Register in `app.py`+### 2. Register in `ministack/app.py````python-from services import myservice+from ministack.services import myserviceSERVICE_HANDLERS = {# ... existing ...@@ -73,7 +97,9 @@ SERVICE_HANDLERS = {}```-### 3. Add detection to `core/router.py`+Also add `(myservice, myservice.reset)` to the list in `_reset_all_state()`.++### 3. Add detection to `ministack/core/router.py````pythonSERVICE_PATTERNS = {@@ -85,19 +111,23 @@ SERVICE_PATTERNS = {}```-And add any `Action`-based operations to `action_service_map` in `detect_service()`.+Add any credential scope or `Action`-based routing as needed.-### 4. Add tests to `tests/test_services.py`+### 4. Add a fixture to `tests/conftest.py````python-@test("MyService: basic operation")-def test_myservice_basic():- svc = boto3.client("myservice", **kwargs)- resp = svc.operation_one(Param="value")- assert resp["result"] == "ok"[email protected](scope="session")+def mysvc():+ return make_client("myservice")```-Add your test function to the `tests` list in `main()`.+### 5. Add tests to `tests/test_services.py`++```python+def test_myservice_operation_one(mysvc):+ resp = mysvc.operation_one(Param="value")+ assert resp["result"] == "ok"+```---@@ -107,34 +137,37 @@ Add your test function to the `tests` list in `main()`.# Start the stackdocker compose up -d-# Install deps-pip install boto3 pytest pytest-cov duckdb+# Install test dependencies+pip install boto3 pytest duckdb docker cbor2# Run all testspytest tests/ -v-# Run a specific test-pytest tests/ -v -k "test_myservice"+# Run a specific service+pytest tests/ -v -k "cognito"```---## Code Conventions-- **One file per service** — keep everything for a service in `services/myservice.py`+- **One file per service** — keep everything for a service in `ministack/services/myservice.py`+- **Imports** — always `from ministack.core.responses import ...`, never `from core.responses import ...`- **In-memory state** — use module-level dicts (`_things: dict = {}`)+- **reset()** — every service must expose a `reset()` that clears all module-level state; it's called by `/_ministack/reset`- **No external AWS deps** — no `boto3`, `botocore`, or `aws-sdk` in service code-- **Minimal dependencies** — `duckdb` and `docker` are optional; guard with try/except+- **Minimal dependencies** — `duckdb` and `docker` are optional; guard with `try/except ImportError`- **Error responses** — match real AWS error codes and HTTP status codes as closely as possible-- **Logging** — use `logger = logging.getLogger("servicename")` and log at DEBUG for request details, INFO for significant events, WARNING for degraded behavior+- **Logging** — `logger = logging.getLogger("servicename")`; DEBUG for request details, INFO for significant events---## Pull Request Checklist-- [ ] New service file in `services/`-- [ ] Registered in `app.py` SERVICE_HANDLERS-- [ ] Detection patterns added to `core/router.py`+- [ ] New service file in `ministack/services/`+- [ ] Registered in `ministack/app.py` SERVICE_HANDLERS and `_reset_all_state()`+- [ ] Detection patterns added to `ministack/core/router.py`+- [ ] Fixture added to `tests/conftest.py`- [ ] Tests added and passing (`pytest tests/ -v`)- [ ] Service added to the table in `README.md`- [ ] Entry added to `CHANGELOG.md`@@ -145,14 +178,13 @@ pytest tests/ -v -k "test_myservice"High-value contributions right now:-- **API Gateway REST API (v1)** — resource trees, methods, integration types, deployment stages; HTTP API v2 is already implemented-- **Cognito** — user pools, sign-up/sign-in, token issuance-- **Route53** — hosted zones, record sets, health checks- **ACM** — certificate provisioning and validation stubs-- **Firehose** — delivery streams to S3/Elasticsearch-- **More S3 operations** — object lock, replication configuration, website hosting-- **Virtual-hosted style S3** — `bucket.localhost:4566` routing in addition to path-style+- **CloudFormation** — basic stack CRUD with resource mapping to existing services+- **More S3 operations** — object lock, replication configuration, website hosting, object tagging- **Athena without DuckDB** — graceful degradation or lighter SQL engine option+- **SES v2** — `ses:SendEmail` with the v2 API shapes+- **Lambda layers** — `PublishLayerVersion`, `GetLayerVersion`, `ListLayerVersions`+- **More Cognito flows** — hosted UI, federated identity providers---diff --git a/Dockerfile b/Dockerfileindex c46eeab4..463f0bcc 100644--- a/Dockerfile+++ b/Dockerfile@@ -15,9 +15,7 @@ RUN pip install --no-cache-dir --upgrade pip && \"cbor2>=5.4.0" \"docker>=7.0.0"-COPY core/ core/-COPY services/ services/-COPY app.py .+COPY ministack/ ministack/RUN addgroup -S ministack && adduser -S ministack -G ministackRUN mkdir -p /tmp/localstack-data/s3 && chown -R ministack:ministack /tmp/localstack-data@@ -41,4 +39,4 @@ EXPOSE 4566HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_localstack/health')" || exit 1-ENTRYPOINT ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "4566"]+ENTRYPOINT ["python", "-m", "uvicorn", "ministack.app:app", "--host", "0.0.0.0", "--port", "4566"]diff --git a/Makefile b/Makefileindex b33fb051..c2aa1d10 100644--- a/Makefile+++ b/Makefile@@ -76,3 +76,9 @@ test: runclean: stopdocker rmi $(IMAGE_NAME) 2>/dev/null || true++purge: stop-compose+ docker rm -f $$(docker ps -aq --filter "label=ministack") 2>/dev/null || true+ docker volume prune -f+ rm -rf ./data/s3/*+ @echo "Orphaned ministack containers, dangling volumes, and S3 data cleared"diff --git a/README.md b/README.mdindex 5265cdd0..a72a4777 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.-- **24 AWS services** emulated on a single port (4566)+- **25 AWS services** emulated on a single port (4566)- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM@@ -36,17 +36,20 @@ LocalStack recently moved its core services behind a paid plan. If you relied on## Quick Start```bash-# Option 1: Docker Hub (recommended)+# Option 1: PyPI (simplest)+pip install ministack+ministack+# Runs on http://localhost:4566 — use GATEWAY_PORT=XXXX to change++# Option 2: Docker Hubdocker run -p 4566:4566 nahuelnucera/ministack-# Option 2: Clone and build+# Option 3: Clone and buildgit clone https://github.com/Nahuel990/ministackcd ministack--# Start with Docker Compose (includes Redis sidecar)docker compose up -d-# Verify+# Verify (any option)curl http://localhost:4566/_localstack/health```@@ -57,24 +60,28 @@ That's it. No account, no API key, no sign-up.## Using with AWS CLI```bash-# Configure a local profile (one-time)-aws configure --profile local-# AWS Access Key ID: test-# AWS Secret Access Key: test-# Default region: us-east-1-# Default output format: json+# Option A — environment variables (no profile needed)+export AWS_ACCESS_KEY_ID=test+export AWS_SECRET_ACCESS_KEY=test+export AWS_DEFAULT_REGION=us-east-1-# Use --endpoint-url on any commandaws --endpoint-url=http://localhost:4566 s3 mb s3://my-bucket-aws --endpoint-url=http://localhost:4566 s3 cp ./file.txt s3://my-bucket/aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name my-queueaws --endpoint-url=http://localhost:4566 dynamodb list-tablesaws --endpoint-url=http://localhost:4566 sts get-caller-identity-# Or set the endpoint globally for a session-export AWS_ENDPOINT_URL=http://localhost:4566-aws s3 ls-aws sqs list-queues+# Option B — named profile (must pass --profile on every command)+aws configure --profile local+# AWS Access Key ID: test+# AWS Secret Access Key: test+# Default region: us-east-1+# Default output format: json++aws --profile local --endpoint-url=http://localhost:4566 s3 mb s3://my-bucket+aws --profile local --endpoint-url=http://localhost:4566 s3 cp ./file.txt s3://my-bucket/+aws --profile local --endpoint-url=http://localhost:4566 sqs create-queue --queue-name my-queue+aws --profile local --endpoint-url=http://localhost:4566 dynamodb list-tables+aws --profile local --endpoint-url=http://localhost:4566 sts get-caller-identity```### awslocal wrapper@@ -201,6 +208,7 @@ sfn.create_state_machine(| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata || **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` || **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |+| **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, 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; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); MFA config stored in-memory |---@@ -383,12 +391,14 @@ MiniStack keeps Python Lambda functions warm between invocations. After the firs│ ┌──────────────▼──────────────────┐ ││ │ Service Handlers │ ││ │ │ │- │ │ S3 SQS SNS DynamoDB │ │- │ │ Lambda IAM STS Secrets │ │- │ │ SSM EventBridge Kinesis │ │- │ │ CloudWatch SES StepFunctions │ │- │ │ ECS RDS ElastiCache │ │- │ │ Glue Athena API Gateway │ │+ │ │ S3 SQS SNS DynamoDB │ │+ │ │ Lambda IAM STS Secrets │ │+ │ │ SSM EventBridge Kinesis │ │+ │ │ CW Logs CW Metrics SES │ │+ │ │ Step Functions API GW v1/v2 │ │+ │ │ ECS RDS ElastiCache Glue │ │+ │ │ Athena Firehose Route53 │ │+ │ │ Cognito │ ││ └──────────────────────────────────┘ ││ ││ In-Memory Storage + Optional Docker │@@ -411,19 +421,19 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (479 tests across all 24 services)+# Run the full test suite (613 tests across all 25 services)pytest tests/ -v```Expected output:```-collected 479 items+collected 613 itemstests/test_services.py::test_s3_create_bucket PASSED...-tests/test_services.py::test_apigwv1_execute_mock_response_parameters PASSED+tests/test_services.py::test_app_asgi_callable PASSED-479 passed in ~60s+613 passed in ~60s```---@@ -463,6 +473,10 @@ provider "aws" {events = "http://localhost:4566"ses = "http://localhost:4566"apigateway = "http://localhost:4566"+ firehose = "http://localhost:4566"+ route53 = "http://localhost:4566"+ cognitoidp = "http://localhost:4566"+ cognitoidentity = "http://localhost:4566"}}```@@ -511,7 +525,7 @@ config:| **API Gateway v1 (REST API)** | ✅ | ✅ | ✅ || **Firehose** | ✅ | ✅ | ✅ || **Route53** | ✅ | ✅ | ✅ |-| Cognito | ❌ | ✅ | ✅ |+| **Cognito** | ✅ | ✅ | ✅ || CloudFormation | ❌ | partial | ✅ || Cost | **Free** | Was free, now paid | $35+/mo || Docker image size | ~150MB | ~1GB | ~1GB |@@ -523,12 +537,14 @@ config:## Contributing-PRs welcome. The codebase is intentionally simple — each service is a single self-contained Python file in `services/`. Adding a new service means:+PRs welcome. The codebase is intentionally simple — each service is a single self-contained Python file in `ministack/services/`. Adding a new service means:++1. Create `ministack/services/myservice.py` with an `async def handle_request(...)` function and a `reset()` function+2. Add it to `SERVICE_HANDLERS` in `ministack/app.py`+3. Add detection patterns to `ministack/core/router.py`+4. Add a fixture to `tests/conftest.py` and tests to `tests/test_services.py`-1. Create `services/myservice.py` with an `async def handle_request(...)` function-2. Add it to `SERVICE_HANDLERS` in `app.py`-3. Add detection patterns to `core/router.py`-4. Add tests to `tests/test_services.py`+See [CONTRIBUTING.md](CONTRIBUTING.md) for a full walkthrough.---diff --git a/docker-compose.yml b/docker-compose.ymlindex b82a6b5c..48ccd092 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -2,6 +2,7 @@ version: "3.8"services:ministack:+ build: .image: nahuelnucera/ministack:latestcontainer_name: ministackports:diff --git a/core/__init__.py b/ministack/__init__.pysimilarity index 100%rename from core/__init__.pyrename to ministack/__init__.pydiff --git a/app.py b/ministack/app.pysimilarity index 90%rename from app.pyrename to ministack/app.pyindex 665f8197..b4532a72 100644--- a/app.py+++ b/ministack/app.py@@ -20,16 +20,17 @@ _EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\.localhost(?::\d+)?$"# Must not match execute-api or other known sub-services_S3_VHOST_RE = re.compile(r"^([^.]+)\.localhost(?::\d+)?$")-from core.router import detect_service, extract_region, extract_account_id-from core.persistence import save_all, load_state, PERSIST_STATE-from services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logs-from services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions-from services import ecs, rds, elasticache, glue, athena-from services import apigateway-from services import firehose-from services import apigateway_v1-from services import route53-from services.iam_sts import handle_iam_request, handle_sts_request+from ministack.core.router import detect_service, extract_region, extract_account_id+from ministack.core.persistence import save_all, load_state, PERSIST_STATE+from ministack.services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logs+from ministack.services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions+from ministack.services import ecs, rds, elasticache, glue, athena+from ministack.services import apigateway+from ministack.services import firehose+from ministack.services import apigateway_v1+from ministack.services import route53+from ministack.services import cognito+from ministack.services.iam_sts import handle_iam_request, handle_sts_requestLOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()logging.basicConfig(@@ -63,6 +64,8 @@ SERVICE_HANDLERS = {"apigateway": apigateway.handle_request,"firehose": firehose.handle_request,"route53": route53.handle_request,+ "cognito-idp": cognito.handle_request,+ "cognito-identity": cognito.handle_request,}SERVICE_NAME_ALIASES = {@@ -75,6 +78,8 @@ SERVICE_NAME_ALIASES = {"apigatewayv2": "apigateway","kinesis-firehose": "firehose","route53": "route53",+ "cognito-idp": "cognito-idp",+ "cognito-identity": "cognito-identity",}@@ -110,7 +115,8 @@ BANNER = r"""Local AWS Service Emulator — Port {port}Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,- ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53+ ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,+ Cognito"""@@ -348,9 +354,9 @@ def _run_init_scripts():def _reset_all_state():"""Wipe all in-memory state across every service module, and persisted files if enabled."""import shutil- from services.iam_sts import reset as _iam_reset- from core.persistence import STATE_DIR, PERSIST_STATE- from services.s3 import DATA_DIR as S3_DATA_DIR, PERSIST as S3_PERSIST+ from ministack.services.iam_sts import reset as _iam_reset+ from ministack.core.persistence import STATE_DIR, PERSIST_STATE+ from ministack.services.s3 import DATA_DIR as S3_DATA_DIR, PERSIST as S3_PERSISTfor mod, fn in [(s3, s3.reset), (sqs, sqs.reset), (sns, sns.reset),@@ -365,6 +371,7 @@ def _reset_all_state():(apigateway_v1, apigateway_v1.reset),(firehose, firehose.reset),(route53, route53.reset),+ (cognito, cognito.reset),]:try:fn()@@ -402,8 +409,15 @@ def _reset_all_state():def main():import uvicorn+ import socketport = int(_resolve_port())- uvicorn.run("app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ if s.connect_ex(("127.0.0.1", port)) == 0:+ print(f"ERROR: Port {port} is already in use. Is MiniStack already running (Docker or another process)?\n"+ f" Stop it with: docker compose down\n"+ f" Or use a different port: GATEWAY_PORT=4567 ministack")+ raise SystemExit(1)+ uvicorn.run("ministack.app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())if __name__ == "__main__":diff --git a/services/__init__.py b/ministack/core/__init__.pysimilarity index 100%rename from services/__init__.pyrename to ministack/core/__init__.pydiff --git a/core/lambda_runtime.py b/ministack/core/lambda_runtime.pysimilarity index 100%rename from core/lambda_runtime.pyrename to ministack/core/lambda_runtime.pydiff --git a/core/persistence.py b/ministack/core/persistence.pysimilarity index 100%rename from core/persistence.pyrename to ministack/core/persistence.pydiff --git a/core/responses.py b/ministack/core/responses.pysimilarity index 100%rename from core/responses.pyrename to ministack/core/responses.pydiff --git a/core/router.py b/ministack/core/router.pysimilarity index 96%rename from core/router.pyrename to ministack/core/router.pyindex 584be15a..dd1679f1 100644--- a/core/router.py+++ b/ministack/core/router.py@@ -108,6 +108,14 @@ SERVICE_PATTERNS = {"host_patterns": [r"route53\."],"path_patterns": [r"^/2013-04-01/"],},+ "cognito-idp": {+ "target_prefixes": ["AWSCognitoIdentityProviderService"],+ "host_patterns": [r"cognito-idp\."],+ },+ "cognito-identity": {+ "target_prefixes": ["AWSCognitoIdentityService"],+ "host_patterns": [r"cognito-identity\."],+ },}@@ -148,6 +156,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"athena": "athena","kinesis-firehose": "firehose","route53": "route53",+ "cognito-idp": "cognito-idp",+ "cognito-identity": "cognito-identity",}if svc_name in scope_map:return scope_map[svc_name]@@ -269,6 +279,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "apigateway"if path_lower.startswith("/2015-03-31/functions"):return "lambda"+ if path_lower.startswith("/oauth2/token"):+ return "cognito-idp"if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):return "ecs"# smithy-rpc-v2-cbor path: /service/ServiceName/operation/ActionNamediff --git a/ministack/services/__init__.py b/ministack/services/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/services/apigateway.py b/ministack/services/apigateway.pysimilarity index 99%rename from services/apigateway.pyrename to ministack/services/apigateway.pyindex 9e1f6f20..af7c421d 100644--- a/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -45,7 +45,7 @@ import timeimport loggingimport re-from core.responses import new_uuid, error_response_json+from ministack.core.responses import new_uuid, error_response_jsonlogger = logging.getLogger("apigateway")@@ -110,7 +110,7 @@ async def handle_request(method, path, headers, body, query_params):# Dispatch v1 REST API requests firstparts = [p for p in path.strip("/").split("/") if p]if parts and parts[0] in ("restapis", "apikeys", "usageplans", "domainnames", "tags"):- from services import apigateway_v1+ from ministack.services import apigateway_v1return await apigateway_v1.handle_request(method, path, headers, body, query_params)try:@@ -314,8 +314,8 @@ def _path_matches(route_path: str, request_path: str) -> bool:async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route_key="$default"):"""Invoke a Lambda function using the API Gateway v2 proxy event format."""- from services import lambda_svc- from core.lambda_runtime import get_or_create_worker+ from ministack.services import lambda_svc+ from ministack.core.lambda_runtime import get_or_create_workeruri = integration.get("integrationUri", "")# integrationUri is a Lambda ARN; the function name is the last segmentdiff --git a/services/apigateway_v1.py b/ministack/services/apigateway_v1.pysimilarity index 99%rename from services/apigateway_v1.pyrename to ministack/services/apigateway_v1.pyindex 8333ce7f..e12d5a72 100644--- a/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -72,7 +72,7 @@ import timeimport datetimeimport logging-from core.responses import new_uuid+from ministack.core.responses import new_uuiddef _now_iso():@@ -220,8 +220,8 @@ def _match_recursive(resources, parent_id, segments, params):async def _call_lambda(func_name, event):"""Invoke a Lambda function and return the parsed response dict."""- from services import lambda_svc- from core.lambda_runtime import get_or_create_worker+ from ministack.services import lambda_svc+ from ministack.core.lambda_runtime import get_or_create_workerif func_name not in lambda_svc._functions:return None, f"Lambda function '{func_name}' not found"diff --git a/services/athena.py b/ministack/services/athena.pysimilarity index 99%rename from services/athena.pyrename to ministack/services/athena.pyindex 4bb533e1..eb495aa3 100644--- a/services/athena.py+++ b/ministack/services/athena.py@@ -20,7 +20,7 @@ import timeimport loggingimport threading-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("athena")diff --git a/services/cloudwatch.py b/ministack/services/cloudwatch.pysimilarity index 99%rename from services/cloudwatch.pyrename to ministack/services/cloudwatch.pyindex 3917d69a..755d3434 100644--- a/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -18,7 +18,7 @@ from datetime import datetime, timezonefrom urllib.parse import parse_qsfrom collections import defaultdict-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("cloudwatch")diff --git a/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pysimilarity index 99%rename from services/cloudwatch_logs.pyrename to ministack/services/cloudwatch_logs.pyindex 4ac4e177..77f776bb 100644--- a/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -19,7 +19,7 @@ import timeimport loggingimport base64-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("logs")diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pynew file mode 100644index 00000000..8e37349b--- /dev/null+++ b/ministack/services/cognito.py@@ -0,0 +1,1796 @@+"""+Amazon Cognito Service Emulator.++Covers two boto3 clients:+ cognito-idp — User Pools (X-Amz-Target: AWSCognitoIdentityProviderService.*)+ cognito-identity — Identity Pools (X-Amz-Target: AWSCognitoIdentityService.*)++User Pools operations:+ CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool,+ CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient,+ ListUserPoolClients, UpdateUserPoolClient,+ AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers,+ AdminSetUserPassword, AdminUpdateUserAttributes,+ AdminInitiateAuth, AdminRespondToAuthChallenge,+ InitiateAuth, RespondToAuthChallenge, SignUp, ConfirmSignUp,+ ForgotPassword, ConfirmForgotPassword, ChangePassword,+ GetUser, UpdateUserAttributes, DeleteUser,+ AdminAddUserToGroup, AdminRemoveUserFromGroup,+ AdminListGroupsForUser, AdminListUserAuthEvents,+ CreateGroup, DeleteGroup, GetGroup, ListGroups,+ AdminConfirmSignUp, AdminDisableUser, AdminEnableUser,+ AdminResetUserPassword, AdminUserGlobalSignOut,+ GlobalSignOut, RevokeToken,+ CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain,+ GetUserPoolMfaConfig, SetUserPoolMfaConfig,+ AssociateSoftwareToken, VerifySoftwareToken,+ TagResource, UntagResource, ListTagsForResource.++Identity Pools operations:+ CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool,+ ListIdentityPools, UpdateIdentityPool,+ GetId, GetCredentialsForIdentity, GetOpenIdToken,+ SetIdentityPoolRoles, GetIdentityPoolRoles,+ ListIdentities, DescribeIdentity, MergeDeveloperIdentities,+ UnlinkDeveloperIdentity, UnlinkIdentity,+ TagResource, UntagResource, ListTagsForResource.++Wire protocol:+ Both services use JSON with X-Amz-Target header.+ cognito-idp credential scope: cognito-idp+ cognito-identity credential scope: cognito-identity+ Routing is handled in app.py via two separate SERVICE_HANDLERS entries.+"""++import json+import time+import base64+import logging+import secrets+import string+from datetime import datetime, timezone+from urllib.parse import parse_qs++from ministack.core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("cognito")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++# ---------------------------------------------------------------------------+# In-memory state — User Pools (cognito-idp)+# ---------------------------------------------------------------------------++_user_pools: dict = {}+# pool_id -> {+# Id, Name, Arn, CreationDate, LastModifiedDate, Status,+# Policies, Schema, AutoVerifiedAttributes, UsernameAttributes,+# MfaConfiguration, EstimatedNumberOfUsers,+# AdminCreateUserConfig, UserPoolTags,+# Domain (str|None),+# _clients: {client_id -> client_dict},+# _users: {username -> user_dict},+# _groups: {group_name -> group_dict},+# }++_pool_domain_map: dict = {} # domain -> pool_id++# ---------------------------------------------------------------------------+# In-memory state — Identity Pools (cognito-identity)+# ---------------------------------------------------------------------------++_identity_pools: dict = {}+# identity_pool_id -> {+# IdentityPoolId, IdentityPoolName, AllowUnauthenticatedIdentities,+# SupportedLoginProviders, DeveloperProviderName,+# OpenIdConnectProviderARNs, CognitoIdentityProviders,+# SamlProviderARNs, IdentityPoolTags,+# _roles: {authenticated: arn, unauthenticated: arn},+# _identities: {identity_id -> identity_dict},+# }++_identity_tags: dict = {} # identity_pool_id -> {key: value}+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _now_epoch() -> float:+ return datetime.now(timezone.utc).timestamp()+++def _pool_arn(pool_id: str) -> str:+ return f"arn:aws:cognito-idp:{REGION}:{ACCOUNT_ID}:userpool/{pool_id}"+++def _pool_id() -> str:+ suffix = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(26))+ return f"{REGION}_{suffix[:9]}"+++def _client_id() -> str:+ return "".join(secrets.choice(string.digits + string.ascii_letters) for _ in range(26))+++def _client_secret() -> str:+ return base64.b64encode(secrets.token_bytes(48)).decode()+++def _identity_pool_id() -> str:+ return f"{REGION}:{new_uuid()}"+++def _identity_id(pool_id: str) -> str:+ return f"{REGION}:{new_uuid()}"+++def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access") -> str:+ """Return a plausible-looking but non-cryptographic JWT stub."""+ header = base64.urlsafe_b64encode(+ json.dumps({"alg": "RS256", "kid": "ministack"}).encode()+ ).rstrip(b"=").decode()+ now = int(time.time())+ payload = base64.urlsafe_b64encode(+ json.dumps({+ "sub": sub,+ "iss": f"https://cognito-idp.{REGION}.amazonaws.com/{pool_id}",+ "client_id": client_id,+ "token_use": token_type,+ "iat": now,+ "exp": now + 3600,+ "jti": new_uuid(),+ }).encode()+ ).rstrip(b"=").decode()+ sig = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()+ return f"{header}.{payload}.{sig}"+++def _user_from_token(token: str, pool: dict):+ """Decode a stub JWT and return the matching user from pool, or None."""+ try:+ payload_b64 = token.split(".")[1]+ payload = json.loads(base64.urlsafe_b64decode(payload_b64 + "=="))+ sub = payload.get("sub", "")+ for user in pool["_users"].values():+ if _attr_list_to_dict(user.get("Attributes", [])).get("sub") == sub:+ return user+ except Exception:+ pass+ return None+++def _resolve_pool(pool_id: str):+ pool = _user_pools.get(pool_id)+ if not pool:+ return None, error_response_json(+ "ResourceNotFoundException",+ f"User pool {pool_id} does not exist.", 400,+ )+ return pool, None+++def _resolve_user(pool: dict, username: str):+ user = pool["_users"].get(username)+ if not user:+ return None, error_response_json(+ "UserNotFoundException",+ f"User {username} does not exist.", 400,+ )+ return user, None+++def _user_out(user: dict) -> dict:+ """Serialise a user dict for API responses."""+ return {+ "Username": user["Username"],+ "Attributes": user.get("Attributes", []),+ "UserCreateDate": user.get("UserCreateDate", _now_epoch()),+ "UserLastModifiedDate": user.get("UserLastModifiedDate", _now_epoch()),+ "Enabled": user.get("Enabled", True),+ "UserStatus": user.get("UserStatus", "CONFIRMED"),+ "MFAOptions": user.get("MFAOptions", []),+ }+++def _attr_list_to_dict(attrs: list) -> dict:+ return {a["Name"]: a["Value"] for a in attrs if "Name" in a}+++def _dict_to_attr_list(d: dict) -> list:+ return [{"Name": k, "Value": v} for k, v in d.items()]+++def _merge_attributes(existing: list, updates: list) -> list:+ d = _attr_list_to_dict(existing)+ d.update(_attr_list_to_dict(updates))+ return _dict_to_attr_list(d)+++# ---------------------------------------------------------------------------+# Entry points — two separate handle_request functions+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body, query_params):+ """Unified entry point — dispatches to IDP or Identity based on target prefix."""+ target = headers.get("x-amz-target", "")++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ if target.startswith("AWSCognitoIdentityService."):+ action = target.split(".")[-1]+ return _dispatch_identity(action, data)++ if target.startswith("AWSCognitoIdentityProviderService."):+ action = target.split(".")[-1]+ return _dispatch_idp(action, data)++ # Path-based fallback for REST-style calls (e.g. /oauth2/token)+ if path.startswith("/oauth2/token"):+ return _oauth2_token(data, query_params, body)++ return error_response_json("InvalidAction", f"Unknown Cognito target: {target}", 400)+++# ---------------------------------------------------------------------------+# IDP dispatcher+# ---------------------------------------------------------------------------++def _dispatch_idp(action: str, data: dict):+ handlers = {+ # User Pool CRUD+ "CreateUserPool": _create_user_pool,+ "DeleteUserPool": _delete_user_pool,+ "DescribeUserPool": _describe_user_pool,+ "ListUserPools": _list_user_pools,+ "UpdateUserPool": _update_user_pool,+ # User Pool Client CRUD+ "CreateUserPoolClient": _create_user_pool_client,+ "DeleteUserPoolClient": _delete_user_pool_client,+ "DescribeUserPoolClient": _describe_user_pool_client,+ "ListUserPoolClients": _list_user_pool_clients,+ "UpdateUserPoolClient": _update_user_pool_client,+ # User management+ "AdminCreateUser": _admin_create_user,+ "AdminDeleteUser": _admin_delete_user,+ "AdminGetUser": _admin_get_user,+ "ListUsers": _list_users,+ "AdminSetUserPassword": _admin_set_user_password,+ "AdminUpdateUserAttributes": _admin_update_user_attributes,+ "AdminConfirmSignUp": _admin_confirm_sign_up,+ "AdminDisableUser": _admin_disable_user,+ "AdminEnableUser": _admin_enable_user,+ "AdminResetUserPassword": _admin_reset_user_password,+ "AdminUserGlobalSignOut": _admin_user_global_sign_out,+ "AdminListGroupsForUser": _admin_list_groups_for_user,+ "AdminListUserAuthEvents": _admin_list_user_auth_events,+ "AdminAddUserToGroup": _admin_add_user_to_group,+ "AdminRemoveUserFromGroup": _admin_remove_user_from_group,+ # Auth flows+ "AdminInitiateAuth": _admin_initiate_auth,+ "AdminRespondToAuthChallenge": _admin_respond_to_auth_challenge,+ "InitiateAuth": _initiate_auth,+ "RespondToAuthChallenge": _respond_to_auth_challenge,+ "GlobalSignOut": _global_sign_out,+ "RevokeToken": _revoke_token,+ # Self-service+ "SignUp": _sign_up,+ "ConfirmSignUp": _confirm_sign_up,+ "ForgotPassword": _forgot_password,+ "ConfirmForgotPassword": _confirm_forgot_password,+ "ChangePassword": _change_password,+ "GetUser": _get_user,+ "UpdateUserAttributes": _update_user_attributes,+ "DeleteUser": _delete_user,+ # Groups+ "CreateGroup": _create_group,+ "DeleteGroup": _delete_group,+ "GetGroup": _get_group,+ "ListGroups": _list_groups,+ "ListUsersInGroup": _list_users_in_group,+ # Domain+ "CreateUserPoolDomain": _create_user_pool_domain,+ "DeleteUserPoolDomain": _delete_user_pool_domain,+ "DescribeUserPoolDomain": _describe_user_pool_domain,+ # MFA+ "GetUserPoolMfaConfig": _get_user_pool_mfa_config,+ "SetUserPoolMfaConfig": _set_user_pool_mfa_config,+ "AssociateSoftwareToken": _associate_software_token,+ "VerifySoftwareToken": _verify_software_token,+ # Tags+ "TagResource": _idp_tag_resource,+ "UntagResource": _idp_untag_resource,+ "ListTagsForResource": _idp_list_tags_for_resource,+ }+ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown Cognito IDP action: {action}", 400)+ return handler(data)+++# ---------------------------------------------------------------------------+# Identity Pool dispatcher+# ---------------------------------------------------------------------------++def _dispatch_identity(action: str, data: dict):+ handlers = {+ "CreateIdentityPool": _create_identity_pool,+ "DeleteIdentityPool": _delete_identity_pool,+ "DescribeIdentityPool": _describe_identity_pool,+ "ListIdentityPools": _list_identity_pools,+ "UpdateIdentityPool": _update_identity_pool,+ "GetId": _get_id,+ "GetCredentialsForIdentity": _get_credentials_for_identity,+ "GetOpenIdToken": _get_open_id_token,+ "SetIdentityPoolRoles": _set_identity_pool_roles,+ "GetIdentityPoolRoles": _get_identity_pool_roles,+ "ListIdentities": _list_identities,+ "DescribeIdentity": _describe_identity,+ "MergeDeveloperIdentities": _merge_developer_identities,+ "UnlinkDeveloperIdentity": _unlink_developer_identity,+ "UnlinkIdentity": _unlink_identity,+ "TagResource": _identity_tag_resource,+ "UntagResource": _identity_untag_resource,+ "ListTagsForResource": _identity_list_tags_for_resource,+ }+ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown Cognito Identity action: {action}", 400)+ return handler(data)+++# ===========================================================================+# USER POOL CRUD+# ===========================================================================++def _create_user_pool(data):+ name = data.get("PoolName")+ if not name:+ return error_response_json("InvalidParameterException", "PoolName is required.", 400)++ pid = _pool_id()+ now = _now_epoch()+ pool = {+ "Id": pid,+ "Name": name,+ "Arn": _pool_arn(pid),+ "CreationDate": now,+ "LastModifiedDate": now,+ "Policies": data.get("Policies", {+ "PasswordPolicy": {+ "MinimumLength": 8,+ "RequireUppercase": True,+ "RequireLowercase": True,+ "RequireNumbers": True,+ "RequireSymbols": True,+ "TemporaryPasswordValidityDays": 7,+ }+ }),+ "Schema": data.get("Schema", []),+ "AutoVerifiedAttributes": data.get("AutoVerifiedAttributes", []),+ "AliasAttributes": data.get("AliasAttributes", []),+ "UsernameAttributes": data.get("UsernameAttributes", []),+ "SmsVerificationMessage": data.get("SmsVerificationMessage", ""),+ "EmailVerificationMessage": data.get("EmailVerificationMessage", ""),+ "EmailVerificationSubject": data.get("EmailVerificationSubject", ""),+ "SmsAuthenticationMessage": data.get("SmsAuthenticationMessage", ""),+ "MfaConfiguration": data.get("MfaConfiguration", "OFF"),+ "DeviceConfiguration": data.get("DeviceConfiguration", {}),+ "EstimatedNumberOfUsers": 0,+ "EmailConfiguration": data.get("EmailConfiguration", {}),+ "SmsConfiguration": data.get("SmsConfiguration", {}),+ "UserPoolTags": data.get("UserPoolTags", {}),+ "AdminCreateUserConfig": data.get("AdminCreateUserConfig", {+ "AllowAdminCreateUserOnly": False,+ "UnusedAccountValidityDays": 7,+ }),+ "UsernameConfiguration": data.get("UsernameConfiguration", {"CaseSensitive": False}),+ "AccountRecoverySetting": data.get("AccountRecoverySetting", {}),+ "UserPoolAddOns": data.get("UserPoolAddOns", {}),+ "VerificationMessageTemplate": data.get("VerificationMessageTemplate", {}),+ "Domain": None,+ "_clients": {},+ "_users": {},+ "_groups": {},+ }+ _user_pools[pid] = pool+ logger.info("Cognito: CreateUserPool %s (%s)", name, pid)+ return json_response({"UserPool": _pool_out(pool)})+++def _delete_user_pool(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ if pool.get("Domain"):+ _pool_domain_map.pop(pool["Domain"], None)+ del _user_pools[pid]+ return json_response({})+++def _describe_user_pool(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ return json_response({"UserPool": _pool_out(pool)})+++def _list_user_pools(data):+ max_results = min(data.get("MaxResults", 60), 60)+ next_token = data.get("NextToken")+ pools = sorted(_user_pools.values(), key=lambda p: p["CreationDate"])+ start = int(next_token) if next_token else 0+ page = pools[start:start + max_results]+ resp = {+ "UserPools": [+ {"Id": p["Id"], "Name": p["Name"],+ "LastModifiedDate": p["LastModifiedDate"], "CreationDate": p["CreationDate"]}+ for p in page+ ]+ }+ if start + max_results < len(pools):+ resp["NextToken"] = str(start + max_results)+ return json_response(resp)+++def _update_user_pool(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ updatable = {+ "Policies", "AutoVerifiedAttributes", "SmsVerificationMessage",+ "EmailVerificationMessage", "EmailVerificationSubject",+ "SmsAuthenticationMessage", "MfaConfiguration", "DeviceConfiguration",+ "EmailConfiguration", "SmsConfiguration", "UserPoolTags",+ "AdminCreateUserConfig", "UserPoolAddOns", "VerificationMessageTemplate",+ "AccountRecoverySetting",+ }+ for k in updatable:+ if k in data:+ pool[k] = data[k]+ pool["LastModifiedDate"] = _now_epoch()+ return json_response({})+++def _pool_out(pool: dict) -> dict:+ return {k: v for k, v in pool.items() if not k.startswith("_")}+++# ===========================================================================+# USER POOL CLIENT CRUD+# ===========================================================================++def _create_user_pool_client(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ cid = _client_id()+ now = _now_epoch()+ generate_secret = data.get("GenerateSecret", False)+ client = {+ "UserPoolId": pid,+ "ClientName": data.get("ClientName", ""),+ "ClientId": cid,+ "ClientSecret": _client_secret() if generate_secret else None,+ "CreationDate": now,+ "LastModifiedDate": now,+ "RefreshTokenValidity": data.get("RefreshTokenValidity", 30),+ "AccessTokenValidity": data.get("AccessTokenValidity", 60),+ "IdTokenValidity": data.get("IdTokenValidity", 60),+ "TokenValidityUnits": data.get("TokenValidityUnits", {}),+ "ReadAttributes": data.get("ReadAttributes", []),+ "WriteAttributes": data.get("WriteAttributes", []),+ "ExplicitAuthFlows": data.get("ExplicitAuthFlows", []),+ "SupportedIdentityProviders": data.get("SupportedIdentityProviders", []),+ "CallbackURLs": data.get("CallbackURLs", []),+ "LogoutURLs": data.get("LogoutURLs", []),+ "DefaultRedirectURI": data.get("DefaultRedirectURI", ""),+ "AllowedOAuthFlows": data.get("AllowedOAuthFlows", []),+ "AllowedOAuthScopes": data.get("AllowedOAuthScopes", []),+ "AllowedOAuthFlowsUserPoolClient": data.get("AllowedOAuthFlowsUserPoolClient", False),+ "AnalyticsConfiguration": data.get("AnalyticsConfiguration", {}),+ "PreventUserExistenceErrors": data.get("PreventUserExistenceErrors", "ENABLED"),+ "EnableTokenRevocation": data.get("EnableTokenRevocation", True),+ "EnablePropagateAdditionalUserContextData": data.get("EnablePropagateAdditionalUserContextData", False),+ "AuthSessionValidity": data.get("AuthSessionValidity", 3),+ }+ pool["_clients"][cid] = client+ out = {k: v for k, v in client.items() if v is not None}+ return json_response({"UserPoolClient": out})+++def _delete_user_pool_client(data):+ pid = data.get("UserPoolId")+ cid = data.get("ClientId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ if cid not in pool["_clients"]:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)+ del pool["_clients"][cid]+ return json_response({})+++def _describe_user_pool_client(data):+ pid = data.get("UserPoolId")+ cid = data.get("ClientId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ client = pool["_clients"].get(cid)+ if not client:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)+ return json_response({"UserPoolClient": {k: v for k, v in client.items() if v is not None}})+++def _list_user_pool_clients(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ max_results = min(data.get("MaxResults", 60), 60)+ next_token = data.get("NextToken")+ clients = sorted(pool["_clients"].values(), key=lambda c: c["CreationDate"])+ start = int(next_token) if next_token else 0+ page = clients[start:start + max_results]+ resp = {+ "UserPoolClients": [+ {"ClientId": c["ClientId"], "UserPoolId": pid, "ClientName": c["ClientName"]}+ for c in page+ ]+ }+ if start + max_results < len(clients):+ resp["NextToken"] = str(start + max_results)+ return json_response(resp)+++def _update_user_pool_client(data):+ pid = data.get("UserPoolId")+ cid = data.get("ClientId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ client = pool["_clients"].get(cid)+ if not client:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)+ updatable = {+ "ClientName", "RefreshTokenValidity", "AccessTokenValidity", "IdTokenValidity",+ "TokenValidityUnits", "ReadAttributes", "WriteAttributes", "ExplicitAuthFlows",+ "SupportedIdentityProviders", "CallbackURLs", "LogoutURLs", "DefaultRedirectURI",+ "AllowedOAuthFlows", "AllowedOAuthScopes", "AllowedOAuthFlowsUserPoolClient",+ "AnalyticsConfiguration", "PreventUserExistenceErrors", "EnableTokenRevocation",+ "EnablePropagateAdditionalUserContextData", "AuthSessionValidity",+ }+ for k in updatable:+ if k in data:+ client[k] = data[k]+ client["LastModifiedDate"] = _now_epoch()+ return json_response({"UserPoolClient": {k: v for k, v in client.items() if v is not None}})+++# ===========================================================================+# USER MANAGEMENT+# ===========================================================================++def _admin_create_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ username = data.get("Username")+ if not username:+ return error_response_json("InvalidParameterException", "Username is required.", 400)+ if username in pool["_users"]:+ return error_response_json(+ "UsernameExistsException",+ f"User account already exists.", 400,+ )++ now = _now_epoch()+ temp_password = data.get("TemporaryPassword") or _generate_temp_password()+ attrs = data.get("UserAttributes", [])+ # Ensure sub attribute+ attr_dict = _attr_list_to_dict(attrs)+ if "sub" not in attr_dict:+ attr_dict["sub"] = new_uuid()+ attrs = _dict_to_attr_list(attr_dict)++ user = {+ "Username": username,+ "Attributes": attrs,+ "UserCreateDate": now,+ "UserLastModifiedDate": now,+ "Enabled": True,+ "UserStatus": "FORCE_CHANGE_PASSWORD",+ "MFAOptions": [],+ "_password": temp_password,+ "_groups": [],+ "_tokens": [],+ }+ pool["_users"][username] = user+ pool["EstimatedNumberOfUsers"] = len(pool["_users"])+ logger.info("Cognito: AdminCreateUser %s in pool %s", username, pid)+ return json_response({"User": _user_out(user)})+++def _admin_delete_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ del pool["_users"][username]+ pool["EstimatedNumberOfUsers"] = len(pool["_users"])+ return json_response({})+++def _admin_get_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ out = _user_out(user)+ # AdminGetUser uses UserAttributes, not Attributes (per AWS API shape)+ out["UserAttributes"] = out.pop("Attributes", [])+ out["UserMFASettingList"] = []+ out["PreferredMfaSetting"] = ""+ return json_response(out)+++def _list_users(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ limit = min(data.get("Limit", 60), 60)+ pagination_token = data.get("PaginationToken")+ filter_str = data.get("Filter", "")++ users = list(pool["_users"].values())++ # Simple filter: "attribute_name = \"value\"" or "attribute_name ^= \"value\""+ if filter_str:+ users = _apply_user_filter(users, filter_str)++ start = 0+ try:+ start = int(pagination_token) if pagination_token else 0+ except (ValueError, TypeError):+ start = 0+ page = users[start:start + limit]+ resp = {"Users": [_user_out(u) for u in page]}+ if start + limit < len(users):+ resp["PaginationToken"] = str(start + limit)+ return json_response(resp)+++def _admin_set_user_password(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["_password"] = data.get("Password", "")+ permanent = data.get("Permanent", False)+ if permanent:+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_update_user_attributes(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["Attributes"] = _merge_attributes(+ user.get("Attributes", []),+ data.get("UserAttributes", []),+ )+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_confirm_sign_up(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_disable_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["Enabled"] = False+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_enable_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["Enabled"] = True+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_reset_user_password(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["UserStatus"] = "RESET_REQUIRED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _admin_user_global_sign_out(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ user["_tokens"] = []+ return json_response({})+++def _admin_list_groups_for_user(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ groups = [+ pool["_groups"][g] for g in user.get("_groups", [])+ if g in pool["_groups"]+ ]+ return json_response({"Groups": [_group_out(g) for g in groups]})+++def _admin_list_user_auth_events(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ _, err = _resolve_user(pool, username)+ if err:+ return err+ return json_response({"AuthEvents": []})+++def _admin_add_user_to_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ group_name = data.get("GroupName")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ if group_name not in pool["_groups"]:+ return error_response_json("ResourceNotFoundException", f"Group {group_name} not found.", 400)+ if group_name not in user.get("_groups", []):+ user.setdefault("_groups", []).append(group_name)+ pool["_groups"][group_name].setdefault("_members", []).append(username)+ return json_response({})+++def _admin_remove_user_from_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ username = data.get("Username")+ group_name = data.get("GroupName")+ user, err = _resolve_user(pool, username)+ if err:+ return err+ if group_name in user.get("_groups", []):+ user["_groups"].remove(group_name)+ if group_name in pool["_groups"]:+ members = pool["_groups"][group_name].get("_members", [])+ if username in members:+ members.remove(username)+ return json_response({})+++# ===========================================================================+# AUTH FLOWS+# ===========================================================================++def _build_auth_result(pool_id: str, client_id: str, user: dict) -> dict:+ sub = _attr_list_to_dict(user.get("Attributes", [])).get("sub", user["Username"])+ return {+ "AccessToken": _fake_token(sub, pool_id, client_id, "access"),+ "IdToken": _fake_token(sub, pool_id, client_id, "id"),+ "RefreshToken": _fake_token(sub, pool_id, client_id, "refresh"),+ "TokenType": "Bearer",+ "ExpiresIn": 3600,+ }+++def _admin_initiate_auth(data):+ pid = data.get("UserPoolId")+ cid = data.get("ClientId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ if cid not in pool["_clients"]:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ auth_flow = data.get("AuthFlow", "")+ auth_params = data.get("AuthParameters", {})++ if auth_flow in ("ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"):+ username = auth_params.get("USERNAME")+ password = auth_params.get("PASSWORD")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ if not user.get("Enabled", True):+ return error_response_json("NotAuthorizedException", "User is disabled.", 400)+ if user.get("_password") and user["_password"] != password:+ return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)+ if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":+ session = base64.b64encode(secrets.token_bytes(32)).decode()+ return json_response({+ "ChallengeName": "NEW_PASSWORD_REQUIRED",+ "Session": session,+ "ChallengeParameters": {+ "USER_ID_FOR_SRP": username,+ "requiredAttributes": "[]",+ "userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),+ },+ })+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):+ refresh_token = auth_params.get("REFRESH_TOKEN", "")+ if not refresh_token:+ return error_response_json("NotAuthorizedException", "Refresh token is missing.", 400)+ # Decode stub token to find the correct user by sub+ user = _user_from_token(refresh_token, pool)+ if not user:+ # Fall back to first user if token can't be decoded (e.g. externally issued token)+ users = list(pool["_users"].values())+ if not users:+ return error_response_json("NotAuthorizedException", "No users in pool.", 400)+ user = users[0]+ result = _build_auth_result(pid, cid, user)+ result.pop("RefreshToken", None) # AWS doesn't return a new refresh token here+ return json_response({"AuthenticationResult": result})++ return error_response_json("InvalidParameterException", f"Unsupported AuthFlow: {auth_flow}", 400)+++def _admin_respond_to_auth_challenge(data):+ pid = data.get("UserPoolId")+ cid = data.get("ClientId")+ pool, err = _resolve_pool(pid)+ if err:+ return err++ challenge_name = data.get("ChallengeName", "")+ responses = data.get("ChallengeResponses", {})++ if challenge_name == "NEW_PASSWORD_REQUIRED":+ username = responses.get("USERNAME")+ new_password = responses.get("NEW_PASSWORD")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ if new_password:+ user["_password"] = new_password+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ if challenge_name == "SMS_MFA":+ username = responses.get("USERNAME")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ if challenge_name == "SOFTWARE_TOKEN_MFA":+ username = responses.get("USERNAME")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)+++def _initiate_auth(data):+ """Public InitiateAuth — same logic as AdminInitiateAuth but no UserPoolId required."""+ cid = data.get("ClientId")+ auth_flow = data.get("AuthFlow", "")+ auth_params = data.get("AuthParameters", {})++ # Find pool by client id+ pool = None+ pid = None+ for p_id, p in _user_pools.items():+ if cid in p["_clients"]:+ pool = p+ pid = p_id+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ if auth_flow in ("USER_PASSWORD_AUTH",):+ username = auth_params.get("USERNAME")+ password = auth_params.get("PASSWORD")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ if not user.get("Enabled", True):+ return error_response_json("NotAuthorizedException", "User is disabled.", 400)+ if user.get("_password") and user["_password"] != password:+ return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)+ if user.get("UserStatus") == "FORCE_CHANGE_PASSWORD":+ session = base64.b64encode(secrets.token_bytes(32)).decode()+ return json_response({+ "ChallengeName": "NEW_PASSWORD_REQUIRED",+ "Session": session,+ "ChallengeParameters": {+ "USER_ID_FOR_SRP": username,+ "requiredAttributes": "[]",+ "userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),+ },+ })+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):+ refresh_token = auth_params.get("REFRESH_TOKEN", "")+ if not refresh_token:+ return error_response_json("NotAuthorizedException", "Refresh token is missing.", 400)+ # Decode stub token to find the correct user by sub+ user = _user_from_token(refresh_token, pool)+ if not user:+ users = list(pool["_users"].values())+ if not users:+ return error_response_json("NotAuthorizedException", "No users in pool.", 400)+ user = users[0]+ result = _build_auth_result(pid, cid, user)+ result.pop("RefreshToken", None) # AWS doesn't return a new refresh token here+ return json_response({"AuthenticationResult": result})++ # USER_SRP_AUTH — return SRP challenge stub+ if auth_flow == "USER_SRP_AUTH":+ username = auth_params.get("USERNAME", "")+ return json_response({+ "ChallengeName": "PASSWORD_VERIFIER",+ "Session": base64.b64encode(secrets.token_bytes(32)).decode(),+ "ChallengeParameters": {+ "USER_ID_FOR_SRP": username,+ "SRP_B": base64.b64encode(secrets.token_bytes(128)).hex(),+ "SALT": base64.b64encode(secrets.token_bytes(16)).hex(),+ "SECRET_BLOCK": base64.b64encode(secrets.token_bytes(32)).decode(),+ },+ })++ return error_response_json("InvalidParameterException", f"Unsupported AuthFlow: {auth_flow}", 400)+++def _respond_to_auth_challenge(data):+ cid = data.get("ClientId")+ challenge_name = data.get("ChallengeName", "")+ responses = data.get("ChallengeResponses", {})++ pool = None+ pid = None+ for p_id, p in _user_pools.items():+ if cid in p["_clients"]:+ pool = p+ pid = p_id+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ if challenge_name in ("NEW_PASSWORD_REQUIRED", "PASSWORD_VERIFIER"):+ username = responses.get("USERNAME")+ new_password = responses.get("NEW_PASSWORD") or responses.get("PASSWORD")+ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)+ if new_password:+ user["_password"] = new_password+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})++ return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)+++def _global_sign_out(data):+ # Access token is opaque to us — accept and succeed+ return json_response({})+++def _revoke_token(data):+ return json_response({})+++# ===========================================================================+# SELF-SERVICE (public-facing)+# ===========================================================================++def _sign_up(data):+ cid = data.get("ClientId")+ username = data.get("Username")+ password = data.get("Password", "")++ pool = None+ pid = None+ for p_id, p in _user_pools.items():+ if cid in p["_clients"]:+ pool = p+ pid = p_id+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)+ if username in pool["_users"]:+ return error_response_json("UsernameExistsException", "User already exists.", 400)++ now = _now_epoch()+ attrs = data.get("UserAttributes", [])+ attr_dict = _attr_list_to_dict(attrs)+ if "sub" not in attr_dict:+ attr_dict["sub"] = new_uuid()+ attrs = _dict_to_attr_list(attr_dict)++ # SignUp always creates UNCONFIRMED — ConfirmSignUp (or AdminConfirmSignUp) confirms the account.+ # AutoVerifiedAttributes only auto-verifies those attributes (e.g. email), not the account itself.+ # Auto-confirming accounts requires a pre-signup Lambda trigger, which we don't emulate.+ status = "UNCONFIRMED"++ user = {+ "Username": username,+ "Attributes": attrs,+ "UserCreateDate": now,+ "UserLastModifiedDate": now,+ "Enabled": True,+ "UserStatus": status,+ "MFAOptions": [],+ "_password": password,+ "_groups": [],+ "_tokens": [],+ "_confirmation_code": "123456",+ }+ pool["_users"][username] = user+ pool["EstimatedNumberOfUsers"] = len(pool["_users"])++ resp = {+ "UserConfirmed": status == "CONFIRMED",+ "UserSub": attr_dict["sub"],+ }+ if "email" in attr_dict:+ resp["CodeDeliveryDetails"] = {+ "Destination": attr_dict["email"],+ "DeliveryMedium": "EMAIL",+ "AttributeName": "email",+ }+ return json_response(resp)+++def _confirm_sign_up(data):+ cid = data.get("ClientId")+ username = data.get("Username")+ code = data.get("ConfirmationCode", "")++ pool = None+ for p in _user_pools.values():+ if cid in p["_clients"]:+ pool = p+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)++ # Accept any code in emulation+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _forgot_password(data):+ cid = data.get("ClientId")+ username = data.get("Username")++ pool = None+ for p in _user_pools.values():+ if cid in p["_clients"]:+ pool = p+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)++ user["_reset_code"] = "654321"+ attrs = _attr_list_to_dict(user.get("Attributes", []))+ return json_response({+ "CodeDeliveryDetails": {+ "Destination": attrs.get("email", ""),+ "DeliveryMedium": "EMAIL",+ "AttributeName": "email",+ }+ })+++def _confirm_forgot_password(data):+ cid = data.get("ClientId")+ username = data.get("Username")+ new_password = data.get("Password", "")++ pool = None+ for p in _user_pools.values():+ if cid in p["_clients"]:+ pool = p+ break+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Client {cid} not found.", 400)++ user = pool["_users"].get(username)+ if not user:+ return error_response_json("UserNotFoundException", "User does not exist.", 400)++ # Accept any confirmation code in emulation (real AWS validates against issued code)+ user["_password"] = new_password+ user["UserStatus"] = "CONFIRMED"+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+++def _change_password(data):+ access_token = data.get("AccessToken", "")+ if not access_token:+ return error_response_json("NotAuthorizedException", "Access token is missing.", 400)+ proposed = data.get("ProposedPassword", "")+ # Decode token to find user and update password+ for pool in _user_pools.values():+ user = _user_from_token(access_token, pool)+ if user:+ user["_password"] = proposed+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({})+ return error_response_json("NotAuthorizedException", "Invalid access token.", 400)+++def _get_user(data):+ access_token = data.get("AccessToken", "")+ if not access_token:+ return error_response_json("NotAuthorizedException", "Access token is missing.", 400)+ for pool in _user_pools.values():+ user = _user_from_token(access_token, pool)+ if user:+ out = _user_out(user)+ # GetUser uses UserAttributes, not Attributes (per AWS API shape)+ out["UserAttributes"] = out.pop("Attributes", [])+ out["UserMFASettingList"] = []+ out["PreferredMfaSetting"] = ""+ return json_response(out)+ return error_response_json("NotAuthorizedException", "Invalid access token.", 400)+++def _update_user_attributes(data):+ access_token = data.get("AccessToken", "")+ if not access_token:+ return error_response_json("NotAuthorizedException", "Access token is missing.", 400)+ for pool in _user_pools.values():+ user = _user_from_token(access_token, pool)+ if user:+ user["Attributes"] = _merge_attributes(+ user.get("Attributes", []),+ data.get("UserAttributes", []),+ )+ user["UserLastModifiedDate"] = _now_epoch()+ return json_response({"CodeDeliveryDetailsList": []})+ return error_response_json("NotAuthorizedException", "Invalid access token.", 400)+++def _delete_user(data):+ access_token = data.get("AccessToken", "")+ if not access_token:+ return error_response_json("NotAuthorizedException", "Access token is missing.", 400)+ for pool in _user_pools.values():+ user = _user_from_token(access_token, pool)+ if user:+ username = user["Username"]+ del pool["_users"][username]+ pool["EstimatedNumberOfUsers"] = len(pool["_users"])+ return json_response({})+ return error_response_json("NotAuthorizedException", "Invalid access token.", 400)+++# ===========================================================================+# GROUPS+# ===========================================================================++def _create_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ name = data.get("GroupName")+ if not name:+ return error_response_json("InvalidParameterException", "GroupName is required.", 400)+ if name in pool["_groups"]:+ return error_response_json("GroupExistsException", f"Group {name} already exists.", 400)+ now = _now_epoch()+ group = {+ "GroupName": name,+ "UserPoolId": pid,+ "Description": data.get("Description", ""),+ "RoleArn": data.get("RoleArn", ""),+ "Precedence": data.get("Precedence", 0),+ "CreationDate": now,+ "LastModifiedDate": now,+ "_members": [],+ }+ pool["_groups"][name] = group+ return json_response({"Group": _group_out(group)})+++def _delete_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ name = data.get("GroupName")+ if name not in pool["_groups"]:+ return error_response_json("ResourceNotFoundException", f"Group {name} not found.", 400)+ # Remove group from all member users+ for username in pool["_groups"][name].get("_members", []):+ user = pool["_users"].get(username)+ if user and name in user.get("_groups", []):+ user["_groups"].remove(name)+ del pool["_groups"][name]+ return json_response({})+++def _get_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ name = data.get("GroupName")+ group = pool["_groups"].get(name)+ if not group:+ return error_response_json("ResourceNotFoundException", f"Group {name} not found.", 400)+ return json_response({"Group": _group_out(group)})+++def _list_groups(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ limit = min(data.get("Limit", 60), 60)+ next_token = data.get("NextToken")+ groups = sorted(pool["_groups"].values(), key=lambda g: g["GroupName"])+ start = int(next_token) if next_token else 0+ page = groups[start:start + limit]+ resp = {"Groups": [_group_out(g) for g in page]}+ if start + limit < len(groups):+ resp["NextToken"] = str(start + limit)+ return json_response(resp)+++def _group_out(group: dict) -> dict:+ return {k: v for k, v in group.items() if not k.startswith("_")}+++def _list_users_in_group(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ name = data.get("GroupName")+ group = pool["_groups"].get(name)+ if not group:+ return error_response_json("ResourceNotFoundException", f"Group {name} not found.", 400)+ limit = min(data.get("Limit", 60), 60)+ next_token = data.get("NextToken")+ members = group.get("_members", [])+ start = int(next_token) if next_token else 0+ page = members[start:start + limit]+ users = [_user_out(pool["_users"][u]) for u in page if u in pool["_users"]]+ resp = {"Users": users}+ if start + limit < len(members):+ resp["NextToken"] = str(start + limit)+ return json_response(resp)+++# ===========================================================================+# DOMAIN+# ===========================================================================++def _create_user_pool_domain(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ domain = data.get("Domain")+ if not domain:+ return error_response_json("InvalidParameterException", "Domain is required.", 400)+ if domain in _pool_domain_map:+ return error_response_json("InvalidParameterException", f"Domain {domain} already exists.", 400)+ pool["Domain"] = domain+ _pool_domain_map[domain] = pid+ return json_response({"CloudFrontDomain": f"{domain}.auth.{REGION}.amazoncognito.com"})+++def _delete_user_pool_domain(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ domain = data.get("Domain")+ _pool_domain_map.pop(domain, None)+ pool["Domain"] = None+ return json_response({})+++def _describe_user_pool_domain(data):+ domain = data.get("Domain")+ pid = _pool_domain_map.get(domain)+ if not pid:+ return json_response({"DomainDescription": {}})+ pool = _user_pools.get(pid, {})+ return json_response({+ "DomainDescription": {+ "UserPoolId": pid,+ "AWSAccountId": ACCOUNT_ID,+ "Domain": domain,+ "S3Bucket": "",+ "CloudFrontDistribution": f"{domain}.auth.{REGION}.amazoncognito.com",+ "Version": "1",+ "Status": "ACTIVE",+ "CustomDomainConfig": {},+ }+ })+++# ===========================================================================+# MFA CONFIG+# ===========================================================================++def _get_user_pool_mfa_config(data):+ 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"),+ })+++def _set_user_pool_mfa_config(data):+ pid = data.get("UserPoolId")+ pool, err = _resolve_pool(pid)+ if err:+ return err+ if "SmsMfaConfiguration" in data:+ pool["SmsMfaConfiguration"] = data["SmsMfaConfiguration"]+ if "SoftwareTokenMfaConfiguration" in data:+ pool["SoftwareTokenMfaConfiguration"] = data["SoftwareTokenMfaConfiguration"]+ 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"),+ })+++def _associate_software_token(data):+ # Return a stub TOTP secret+ secret = base64.b32encode(secrets.token_bytes(20)).decode()+ return json_response({"SecretCode": secret})+++def _verify_software_token(data):+ # Accept any code in emulation+ return json_response({"Status": "SUCCESS"})+++# ===========================================================================+# IDP TAGS+# ===========================================================================++def _idp_tag_resource(data):+ arn = data.get("ResourceArn", "")+ tags = data.get("Tags", {})+ # Find pool by ARN+ for pool in _user_pools.values():+ if pool["Arn"] == arn:+ pool["UserPoolTags"].update(tags)+ return json_response({})+ return error_response_json("ResourceNotFoundException", f"Resource {arn} not found.", 400)+++def _idp_untag_resource(data):+ arn = data.get("ResourceArn", "")+ tag_keys = data.get("TagKeys", [])+ for pool in _user_pools.values():+ if pool["Arn"] == arn:+ for k in tag_keys:+ pool["UserPoolTags"].pop(k, None)+ return json_response({})+ return error_response_json("ResourceNotFoundException", f"Resource {arn} not found.", 400)+++def _idp_list_tags_for_resource(data):+ arn = data.get("ResourceArn", "")+ for pool in _user_pools.values():+ if pool["Arn"] == arn:+ return json_response({"Tags": pool.get("UserPoolTags", {})})+ return error_response_json("ResourceNotFoundException", f"Resource {arn} not found.", 400)+++# ===========================================================================+# OAUTH2 TOKEN ENDPOINT (data plane)+# ===========================================================================++def _oauth2_token(data, query_params, raw_body: bytes = b""):+ """Stub /oauth2/token endpoint — returns fake tokens for client_credentials flow.+ Body is application/x-www-form-urlencoded, not JSON.+ """+ # Parse form-encoded body first, fall back to query_params+ form: dict = {}+ if raw_body:+ try:+ parsed = parse_qs(raw_body.decode("utf-8", errors="replace"), keep_blank_values=True)+ form = {k: v[0] for k, v in parsed.items()}+ except Exception:+ pass++ def _get(key):+ if key in form:+ return form[key]+ v = query_params.get(key, "")+ return v[0] if isinstance(v, list) else v++ client_id = _get("client_id")+ now = int(time.time())+ pool_id = ""+ for pid, pool in _user_pools.items():+ if client_id in pool["_clients"]:+ pool_id = pid+ break+ access_token = _fake_token(client_id or new_uuid(), pool_id, client_id or "", "access")+ return json_response({+ "access_token": access_token,+ "token_type": "Bearer",+ "expires_in": 3600,+ })+++# ===========================================================================+# IDENTITY POOLS (cognito-identity)+# ===========================================================================++def _create_identity_pool(data):+ name = data.get("IdentityPoolName")+ if not name:+ return error_response_json("InvalidParameterException", "IdentityPoolName is required.", 400)+ iid = _identity_pool_id()+ pool = {+ "IdentityPoolId": iid,+ "IdentityPoolName": name,+ "AllowUnauthenticatedIdentities": data.get("AllowUnauthenticatedIdentities", False),+ "AllowClassicFlow": data.get("AllowClassicFlow", False),+ "SupportedLoginProviders": data.get("SupportedLoginProviders", {}),+ "DeveloperProviderName": data.get("DeveloperProviderName", ""),+ "OpenIdConnectProviderARNs": data.get("OpenIdConnectProviderARNs", []),+ "CognitoIdentityProviders": data.get("CognitoIdentityProviders", []),+ "SamlProviderARNs": data.get("SamlProviderARNs", []),+ "IdentityPoolTags": data.get("IdentityPoolTags", {}),+ "_roles": {},+ "_identities": {},+ }+ _identity_pools[iid] = pool+ return json_response(_identity_pool_out(pool))+++def _delete_identity_pool(data):+ iid = data.get("IdentityPoolId")+ if iid not in _identity_pools:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ del _identity_pools[iid]+ _identity_tags.pop(iid, None)+ return json_response({})+++def _describe_identity_pool(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ return json_response(_identity_pool_out(pool))+++def _list_identity_pools(data):+ max_results = min(data.get("MaxResults", 60), 60)+ next_token = data.get("NextToken")+ pools = sorted(_identity_pools.values(), key=lambda p: p["IdentityPoolId"])+ start = int(next_token) if next_token else 0+ page = pools[start:start + max_results]+ resp = {+ "IdentityPools": [+ {"IdentityPoolId": p["IdentityPoolId"], "IdentityPoolName": p["IdentityPoolName"]}+ for p in page+ ]+ }+ if start + max_results < len(pools):+ resp["NextToken"] = str(start + max_results)+ return json_response(resp)+++def _update_identity_pool(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ updatable = {+ "IdentityPoolName", "AllowUnauthenticatedIdentities", "AllowClassicFlow",+ "SupportedLoginProviders", "DeveloperProviderName", "OpenIdConnectProviderARNs",+ "CognitoIdentityProviders", "SamlProviderARNs", "IdentityPoolTags",+ }+ for k in updatable:+ if k in data:+ pool[k] = data[k]+ return json_response(_identity_pool_out(pool))+++def _get_id(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ identity_id = _identity_id(iid)+ pool["_identities"][identity_id] = {+ "IdentityId": identity_id,+ "Logins": data.get("Logins", {}),+ "CreationDate": _now_epoch(),+ "LastModifiedDate": _now_epoch(),+ }+ return json_response({"IdentityId": identity_id})+++def _get_credentials_for_identity(data):+ identity_id = data.get("IdentityId", new_uuid())+ now = int(time.time())+ return json_response({+ "IdentityId": identity_id,+ "Credentials": {+ "AccessKeyId": f"ASIA{''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16))}",+ "SecretKey": base64.b64encode(secrets.token_bytes(30)).decode(),+ "SessionToken": base64.b64encode(secrets.token_bytes(64)).decode(),+ "Expiration": now + 3600,+ },+ })+++def _get_open_id_token(data):+ identity_id = data.get("IdentityId", new_uuid())+ # Find pool containing this identity+ pool_id = ""+ for iid, pool in _identity_pools.items():+ if identity_id in pool["_identities"]:+ pool_id = iid+ break+ token = _fake_token(identity_id, pool_id, "", "id")+ return json_response({"IdentityId": identity_id, "Token": token})+++def _set_identity_pool_roles(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ pool["_roles"] = data.get("Roles", {})+ return json_response({})+++def _get_identity_pool_roles(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ return json_response({+ "IdentityPoolId": iid,+ "Roles": pool.get("_roles", {}),+ "RoleMappings": {},+ })+++def _list_identities(data):+ iid = data.get("IdentityPoolId")+ pool = _identity_pools.get(iid)+ if not pool:+ return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)+ max_results = min(data.get("MaxResults", 60), 60)+ identities = list(pool["_identities"].values())[:max_results]+ return json_response({+ "IdentityPoolId": iid,+ "Identities": [+ {"IdentityId": i["IdentityId"], "Logins": list(i.get("Logins", {}).keys()),+ "CreationDate": i["CreationDate"], "LastModifiedDate": i["LastModifiedDate"]}+ for i in identities+ ],+ })+++def _describe_identity(data):+ identity_id = data.get("IdentityId")+ for pool in _identity_pools.values():+ identity = pool["_identities"].get(identity_id)+ if identity:+ return json_response({+ "IdentityId": identity_id,+ "Logins": list(identity.get("Logins", {}).keys()),+ "CreationDate": identity["CreationDate"],+ "LastModifiedDate": identity["LastModifiedDate"],+ })+ return error_response_json("ResourceNotFoundException", f"Identity {identity_id} not found.", 400)+++def _merge_developer_identities(data):+ # Stub — return a new identity id+ return json_response({"IdentityId": _identity_id(data.get("IdentityPoolId", ""))})+++def _unlink_developer_identity(data):+ return json_response({})+++def _unlink_identity(data):+ return json_response({})+++def _identity_tag_resource(data):+ arn = data.get("ResourceArn", "")+ tags = data.get("Tags", {})+ # ARN format: arn:aws:cognito-identity:region:account:identitypool/id+ iid = arn.split("/")[-1] if "/" in arn else arn+ _identity_tags.setdefault(iid, {}).update(tags)+ return json_response({})+++def _identity_untag_resource(data):+ arn = data.get("ResourceArn", "")+ tag_keys = data.get("TagKeys", [])+ iid = arn.split("/")[-1] if "/" in arn else arn+ for k in tag_keys:+ _identity_tags.get(iid, {}).pop(k, None)+ return json_response({})+++def _identity_list_tags_for_resource(data):+ arn = data.get("ResourceArn", "")+ iid = arn.split("/")[-1] if "/" in arn else arn+ return json_response({"Tags": _identity_tags.get(iid, {})})+++def _identity_pool_out(pool: dict) -> dict:+ return {k: v for k, v in pool.items() if not k.startswith("_")}+++# ===========================================================================+# MISC HELPERS+# ===========================================================================++def _generate_temp_password() -> str:+ chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + "!@#$%"+ return "".join(secrets.choice(chars) for _ in range(12))+++def _apply_user_filter(users: list, filter_str: str) -> list:+ """+ Supports simple Cognito filter syntax:+ attribute_name = "value"+ attribute_name ^= "value" (starts with)+ attribute_name != "value"+ """+ import re+ m = re.match(r'(\w+)\s*(=|\^=|!=)\s*"([^"]*)"', filter_str.strip())+ if not m:+ return users+ attr_name, op, value = m.group(1), m.group(2), m.group(3)+ result = []+ for user in users:+ attr_dict = _attr_list_to_dict(user.get("Attributes", []))+ # Also check top-level fields like username, status+ field_val = attr_dict.get(attr_name, "")+ if attr_name == "username":+ field_val = user.get("Username", "")+ elif attr_name == "status":+ field_val = user.get("UserStatus", "")+ elif attr_name == "email_verified":+ field_val = attr_dict.get("email_verified", "")+ if op == "=" and field_val == value:+ result.append(user)+ elif op == "^=" and field_val.startswith(value):+ result.append(user)+ elif op == "!=" and field_val != value:+ result.append(user)+ return result+++# ===========================================================================+# RESET+# ===========================================================================++def reset():+ _user_pools.clear()+ _pool_domain_map.clear()+ _identity_pools.clear()+ _identity_tags.clear()diff --git a/services/dynamodb.py b/ministack/services/dynamodb.pysimilarity index 99%rename from services/dynamodb.pyrename to ministack/services/dynamodb.pyindex 1969e9e4..c01931b2 100644--- a/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -18,7 +18,7 @@ import threadingfrom collections import defaultdictfrom decimal import Decimal, InvalidOperation-from core.responses import json_response, error_response_json, new_uuid, now_iso+from ministack.core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("dynamodb")diff --git a/services/ecs.py b/ministack/services/ecs.pysimilarity index 98%rename from services/ecs.pyrename to ministack/services/ecs.pyindex c377e2d1..6d9a02c6 100644--- a/services/ecs.py+++ b/ministack/services/ecs.py@@ -19,7 +19,7 @@ import jsonimport timeimport logging-from core.responses import json_response, error_response_json, new_uuid, now_iso+from ministack.core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("ecs")@@ -751,7 +751,7 @@ def _stop_task(data):try:c = docker_client.containers.get(docker_id)c.stop(timeout=5)- c.remove()+ c.remove(v=True)except Exception as e:logger.warning(f"ECS: failed to stop container {docker_id}: {e}")@@ -1212,6 +1212,16 @@ _ACTION_MAP = {def reset():+ docker_client = _get_docker()+ if docker_client:+ for task in _tasks.values():+ for cid in task.get("_docker_ids", []):+ try:+ c = docker_client.containers.get(cid)+ c.stop(timeout=2)+ c.remove(v=True)+ except Exception:+ pass_clusters.clear()_task_defs.clear()_task_def_latest.clear()diff --git a/services/elasticache.py b/ministack/services/elasticache.pysimilarity index 98%rename from services/elasticache.pyrename to ministack/services/elasticache.pyindex 72312e41..c4c30fe6 100644--- a/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -25,7 +25,7 @@ import timeimport loggingfrom urllib.parse import parse_qs-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("elasticache")@@ -184,6 +184,7 @@ def _create_cache_cluster(p):ports={f"{container_port}/tcp": host_port},name=f"ministack-elasticache-{cluster_id}",labels={"ministack": "elasticache", "cluster_id": cluster_id},+ volumes={},)docker_container_id = container.idlogger.info(f"ElastiCache: started {engine} container for {cluster_id} on port {host_port}")@@ -658,9 +659,9 @@ def _modify_cache_parameter_group(p):params = _param_group_params.setdefault(name, {})idx = 1- while _p(p, f"ParameterNameValues.member.{idx}.ParameterName"):- pname = _p(p, f"ParameterNameValues.member.{idx}.ParameterName")- pvalue = _p(p, f"ParameterNameValues.member.{idx}.ParameterValue")+ while _p(p, f"ParameterNameValues.ParameterNameValue.{idx}.ParameterName"):+ pname = _p(p, f"ParameterNameValues.ParameterNameValue.{idx}.ParameterName")+ pvalue = _p(p, f"ParameterNameValues.ParameterNameValue.{idx}.ParameterValue")if pname in params:params[pname]["Value"] = pvalueparams[pname]["Source"] = "user"@@ -690,8 +691,8 @@ def _reset_cache_parameter_group(p):defaults = _default_params_for_family(family)params = _param_group_params.get(name, {})idx = 1- while _p(p, f"ParameterNameValues.member.{idx}.ParameterName"):- pname = _p(p, f"ParameterNameValues.member.{idx}.ParameterName")+ while _p(p, f"ParameterNameValues.ParameterNameValue.{idx}.ParameterName"):+ pname = _p(p, f"ParameterNameValues.ParameterNameValue.{idx}.ParameterName")if pname in defaults:params[pname] = dict(defaults[pname])idx += 1@@ -1266,6 +1267,17 @@ def _error(code, message, status):def reset():+ docker_client = _get_docker()+ if docker_client:+ for cluster in _clusters.values():+ cid = cluster.get("_docker_container_id")+ if cid:+ try:+ c = docker_client.containers.get(cid)+ c.stop(timeout=2)+ c.remove(v=True)+ except Exception:+ pass_clusters.clear()_replication_groups.clear()_subnet_groups.clear()diff --git a/services/eventbridge.py b/ministack/services/eventbridge.pysimilarity index 99%rename from services/eventbridge.pyrename to ministack/services/eventbridge.pyindex 8d537f5a..80459b1f 100644--- a/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -21,7 +21,7 @@ import loggingimport refrom datetime import datetime, timezone-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("events")@@ -593,7 +593,7 @@ def _apply_input_transformer(transformer, event):def _dispatch_to_lambda(arn, payload):- from services import lambda_svc+ from ministack.services import lambda_svcparts = arn.split(":")func_name = parts[-1].split("/")[-1] if "/" in parts[-1] else parts[-1]@@ -611,7 +611,7 @@ def _dispatch_to_lambda(arn, payload):def _dispatch_to_sqs(arn, payload):- from services import sqs as _sqs+ from ministack.services import sqs as _sqsqueue_name = arn.split(":")[-1]queue_url = _sqs._queue_url(queue_name)@@ -636,7 +636,7 @@ def _dispatch_to_sqs(arn, payload):def _dispatch_to_sns(arn, payload):- from services import sns as _sns+ from ministack.services import sns as _snstopic = _sns._topics.get(arn)if not topic:diff --git a/services/firehose.py b/ministack/services/firehose.pysimilarity index 99%rename from services/firehose.pyrename to ministack/services/firehose.pyindex 87c5c09b..accb18a9 100644--- a/services/firehose.py+++ b/ministack/services/firehose.py@@ -21,7 +21,7 @@ import loggingimport threadingimport time-from core.responses import json_response, error_response_json, new_uuid, now_epoch+from ministack.core.responses import json_response, error_response_json, new_uuid, now_epochlogger = logging.getLogger("firehose")@@ -174,7 +174,7 @@ def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes):Schedules a coroutine on the running loop (fire-and-forget)."""try:- from services import s3 as s3_svc+ from ministack.services import s3 as s3_svccfg = dest["config"]bucket_arn = cfg.get("BucketARN", "")diff --git a/services/glue.py b/ministack/services/glue.pysimilarity index 99%rename from services/glue.pyrename to ministack/services/glue.pyindex 963025a3..37e3a39f 100644--- a/services/glue.py+++ b/ministack/services/glue.py@@ -16,7 +16,7 @@ import tempfileimport threadingimport logging-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("glue")diff --git a/services/iam_sts.py b/ministack/services/iam_sts.pysimilarity index 99%rename from services/iam_sts.pyrename to ministack/services/iam_sts.pyindex 91240a2d..98d45fd7 100644--- a/services/iam_sts.py+++ b/ministack/services/iam_sts.py@@ -33,7 +33,7 @@ import loggingimport timefrom urllib.parse import parse_qs, quote as _url_quote-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("iam")diff --git a/services/kinesis.py b/ministack/services/kinesis.pysimilarity index 99%rename from services/kinesis.pyrename to ministack/services/kinesis.pyindex 5ee3cde9..dc460c82 100644--- a/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -19,7 +19,7 @@ import hashlibimport loggingimport threading-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("kinesis")diff --git a/services/lambda_svc.py b/ministack/services/lambda_svc.pysimilarity index 99%rename from services/lambda_svc.pyrename to ministack/services/lambda_svc.pyindex 255645eb..33c7df00 100644--- a/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -39,7 +39,7 @@ import loggingimport refrom urllib.parse import unquote-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("lambda")@@ -1368,11 +1368,6 @@ def _get_policy(func_name: str, query_params: dict | None = None):f"Function not found: {_func_arn(func_name)}", 404,)func = _functions[func_name]- if not func["policy"]["Statement"]:- return error_response_json(- "ResourceNotFoundException",- "The resource you requested does not exist.", 404,- )return json_response({"Policy": json.dumps(func["policy"]),"RevisionId": func["config"]["RevisionId"],@@ -1575,7 +1570,7 @@ def _get_function_concurrency(func_name: str):)conc = _functions[func_name].get("concurrency")if conc is None:- return json_response({"ReservedConcurrentExecutions": 0})+ return json_response({})return json_response({"ReservedConcurrentExecutions": conc})@@ -1776,7 +1771,7 @@ def _poll_loop():def _poll_once():- from services import sqs as _sqs+ from ministack.services import sqs as _sqsfor esm in list(_esms.values()):if not esm.get("Enabled", True):@@ -1925,7 +1920,7 @@ def _list_function_url_configs(func_name: str, query_params: dict):def reset():- from core import lambda_runtime+ from ministack.core import lambda_runtime_functions.clear()_layers.clear()_esms.clear()diff --git a/services/rds.py b/ministack/services/rds.pysimilarity index 99%rename from services/rds.pyrename to ministack/services/rds.pyindex 25f2b619..0c5b1274 100644--- a/services/rds.py+++ b/ministack/services/rds.py@@ -26,7 +26,7 @@ import timeimport loggingfrom urllib.parse import parse_qs-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("rds")@@ -132,6 +132,8 @@ def _create_db_instance(p):ports={f"{container_port}/tcp": host_port},name=f"ministack-rds-{db_id}",labels={"ministack": "rds", "db_id": db_id},+ tmpfs={"/var/lib/postgresql/data": "rw,noexec,nosuid,size=256m",+ "/var/lib/mysql": "rw,noexec,nosuid,size=256m"},)docker_container_id = container.idlogger.info(f"RDS: started {engine} container for {db_id} on port {host_port}")@@ -263,7 +265,7 @@ def _delete_db_instance(p):try:c = docker_client.containers.get(instance["_docker_container_id"])c.stop(timeout=5)- c.remove()+ c.remove(v=True)logger.info(f"RDS: removed container for {db_id}")except Exception as e:logger.warning(f"RDS: failed to remove container for {db_id}: {e}")@@ -1971,6 +1973,17 @@ _ACTION_MAP = {def reset():+ docker_client = _get_docker()+ if docker_client:+ for instance in _instances.values():+ cid = instance.get("_docker_container_id")+ if cid:+ try:+ c = docker_client.containers.get(cid)+ c.stop(timeout=2)+ c.remove(v=True)+ except Exception:+ pass_instances.clear()_clusters.clear()_subnet_groups.clear()diff --git a/services/route53.py b/ministack/services/route53.pysimilarity index 99%rename from services/route53.pyrename to ministack/services/route53.pyindex 07e81dd4..5323212d 100644--- a/services/route53.py+++ b/ministack/services/route53.py@@ -26,7 +26,7 @@ import randomfrom datetime import datetime, timezonefrom xml.etree.ElementTree import Element, SubElement, tostring, fromstring-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("route53")diff --git a/services/s3.py b/ministack/services/s3.pysimilarity index 99%rename from services/s3.pyrename to ministack/services/s3.pyindex ec97b830..a20f6e1b 100644--- a/services/s3.py+++ b/ministack/services/s3.py@@ -28,7 +28,7 @@ import timefrom urllib.parse import quote as url_quote, unquote as url_unquotefrom xml.etree.ElementTree import Element, SubElement, tostring, fromstring-from core.responses import md5_hash, sha256_hash, now_iso, new_uuid, iso_to_rfc7231+from ministack.core.responses import md5_hash, sha256_hash, now_iso, new_uuid, iso_to_rfc7231logger = logging.getLogger("s3")@@ -970,7 +970,7 @@ def _fire_s3_event(bucket_name: str, key: str, event_name: str,def _deliver_event_to_sqs(arn: str, event_payload: dict) -> None:- from services import sqs as _sqs+ from ministack.services import sqs as _sqsqueue_name = arn.rsplit(":", 1)[-1]queue_url = _sqs._queue_url(queue_name)@@ -996,7 +996,7 @@ def _deliver_event_to_sqs(arn: str, event_payload: dict) -> None:def _deliver_event_to_sns(arn: str, event_payload: dict) -> None:- from services import sns as _sns+ from ministack.services import sns as _snstopic = _sns._topics.get(arn)if not topic:@@ -1010,7 +1010,7 @@ def _deliver_event_to_sns(arn: str, event_payload: dict) -> None:def _deliver_event_to_lambda(arn: str, event_payload: dict) -> None:- from services import lambda_svc as _lambda+ from ministack.services import lambda_svc as _lambdafunc_name = arn.rsplit(":", 1)[-1]if func_name not in _lambda._functions:diff --git a/services/secretsmanager.py b/ministack/services/secretsmanager.pysimilarity index 99%rename from services/secretsmanager.pyrename to ministack/services/secretsmanager.pyindex 61728a8d..98cfba6f 100644--- a/services/secretsmanager.py+++ b/ministack/services/secretsmanager.py@@ -16,7 +16,7 @@ import secrets as stdlib_secretsimport loggingimport base64-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("secretsmanager")diff --git a/services/ses.py b/ministack/services/ses.pysimilarity index 99%rename from services/ses.pyrename to ministack/services/ses.pyindex 7d60093b..e720d1f3 100644--- a/services/ses.py+++ b/ministack/services/ses.py@@ -33,7 +33,7 @@ from email import message_from_bytesfrom email.policy import default as default_policyfrom urllib.parse import parse_qs, unquote-from core.responses import new_uuid+from ministack.core.responses import new_uuidlogger = logging.getLogger("ses")diff --git a/services/sns.py b/ministack/services/sns.pysimilarity index 99%rename from services/sns.pyrename to ministack/services/sns.pyindex d9cd9722..73ed3a66 100644--- a/services/sns.py+++ b/ministack/services/sns.py@@ -17,9 +17,9 @@ import loggingimport timefrom urllib.parse import parse_qs-from core.responses import new_uuid-from services import sqs as _sqs-import services.lambda_svc as _lambda_svc+from ministack.core.responses import new_uuid+from ministack.services import sqs as _sqs+import ministack.services.lambda_svc as _lambda_svclogger = logging.getLogger("sns")diff --git a/services/sqs.py b/ministack/services/sqs.pysimilarity index 99%rename from services/sqs.pyrename to ministack/services/sqs.pyindex 4e2b5ff4..a507ceee 100644--- a/services/sqs.py+++ b/ministack/services/sqs.py@@ -31,7 +31,7 @@ import structfrom urllib.parse import parse_qsfrom xml.sax.saxutils import escape as _esc-from core.responses import new_uuid, now_iso, md5_hash+from ministack.core.responses import new_uuid, now_iso, md5_hashlogger = logging.getLogger("sqs")diff --git a/services/ssm.py b/ministack/services/ssm.pysimilarity index 99%rename from services/ssm.pyrename to ministack/services/ssm.pyindex 265fdf62..903dbf05 100644--- a/services/ssm.py+++ b/ministack/services/ssm.py@@ -13,7 +13,7 @@ import loggingimport base64from datetime import datetime, timezone-from core.responses import json_response, error_response_json, new_uuid+from ministack.core.responses import json_response, error_response_json, new_uuidlogger = logging.getLogger("ssm")diff --git a/services/stepfunctions.py b/ministack/services/stepfunctions.pysimilarity index 99%rename from services/stepfunctions.pyrename to ministack/services/stepfunctions.pyindex ab91f318..e12e01ac 100644--- a/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -26,7 +26,7 @@ import timefrom concurrent.futures import ThreadPoolExecutor, wait as futures_waitfrom datetime import datetime, timezone-from core.responses import json_response, error_response_json, new_uuid, now_iso+from ministack.core.responses import json_response, error_response_json, new_uuid, now_isologger = logging.getLogger("states")@@ -749,7 +749,7 @@ def _invoke_with_callback(resource, input_data, token, state_def):def _call_lambda(func_name, event):"""Invoke a Lambda via the co-located lambda_svc module."""try:- from services import lambda_svc+ from ministack.services import lambda_svcexcept ImportError:logger.warning("lambda_svc unavailable; returning passthrough for %s", func_name)return event@@ -1235,7 +1235,7 @@ def _parse_ts(v):def _invoke_sqs_send_message(resource, input_data):"""arn:aws:states:::sqs:sendMessage"""try:- from services import sqs+ from ministack.services import sqsexcept ImportError:logger.warning("sqs module unavailable; returning passthrough")return input_data@@ -1250,7 +1250,7 @@ def _invoke_sqs_send_message(resource, input_data):def _invoke_sns_publish(resource, input_data):"""arn:aws:states:::sns:publish"""try:- from services import sns+ from ministack.services import snsexcept ImportError:logger.warning("sns module unavailable; returning passthrough")return input_data@@ -1269,7 +1269,7 @@ def _invoke_sns_publish(resource, input_data):def _invoke_dynamodb(op_name, input_data):"""arn:aws:states:::dynamodb:{putItem,getItem,deleteItem,updateItem}"""try:- from services import dynamodb+ from ministack.services import dynamodbexcept ImportError:logger.warning("dynamodb module unavailable; returning passthrough")return input_data@@ -1295,7 +1295,7 @@ def _invoke_dynamodb(op_name, input_data):def _invoke_ecs_run_task(resource, input_data):"""arn:aws:states:::ecs:runTask[.sync]"""try:- from services import ecs+ from ministack.services import ecsexcept ImportError:logger.warning("ecs module unavailable; returning passthrough")return input_data@@ -1320,7 +1320,7 @@ def _poll_ecs_tasks(cluster, task_arns):Returns the full DescribeTasks result including exit codes — the statemachine definition decides how to handle success/failure via Choice or Catch."""- from services import ecs+ from ministack.services import ecsfor _ in range(600):time.sleep(1)diff --git a/pyproject.toml b/pyproject.tomlindex 4637a2a0..0d6b4279 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.0.8"+version = "1.1.0"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }@@ -45,10 +45,10 @@ Repository = "https://github.com/Nahuel990/ministack"Issues = "https://github.com/Nahuel990/ministack/issues"[project.scripts]-ministack = "app:main"+ministack = "ministack.app:main"[tool.setuptools.packages.find]-include = ["core*", "services*"]+include = ["ministack*"][tool.pytest.ini_options]testpaths = ["tests"]@@ -56,5 +56,5 @@ python_files = ["test_*.py"]python_functions = ["test_*"][tool.coverage.run]-source = ["core", "services"]+source = ["ministack"]omit = ["tests/*"]diff --git a/tests/conftest.py b/tests/conftest.pyindex 53a2e45a..728994d3 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -133,6 +133,14 @@ def apigw_v1():def r53():return make_client("route53")[email protected](scope="session")+def cognito_idp():+ return make_client("cognito-idp")+[email protected](scope="session")+def cognito_identity():+ return make_client("cognito-identity")+@pytest.fixture(scope="session")def sfn_sync():"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""diff --git a/tests/test_services.py b/tests/test_services.pyindex f80bc64d..23aa24ff 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -8055,7 +8055,13 @@ def test_lambda_reset_terminates_workers(lam):# Reset — must terminate worker without errorendpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")req = urllib.request.Request(f"{endpoint}/_ministack/reset", data=b"", method="POST")- urllib.request.urlopen(req, timeout=5)+ for _attempt in range(3):+ try:+ urllib.request.urlopen(req, timeout=15)+ break+ except Exception:+ if _attempt == 2:+ raise# Re-create and invoke — new worker means new boot timelam.create_function(@@ -8116,3 +8122,2512 @@ def test_sfn_integration_lambda_invoke(sfn, lam):assert desc["status"] == "SUCCEEDED"output = json.loads(desc["output"])assert output["result"]["doubled"] == 42+++# ========== Package structure ==========++_ministack_installed = True+try:+ import ministack # noqa: F401+except ModuleNotFoundError:+ _ministack_installed = False++_requires_package = pytest.mark.skipif(+ not _ministack_installed,+ reason="ministack not installed locally (runs in CI via pip install -e .)",+)+++@_requires_package+def test_package_core_importable():+ """ministack.core modules must all be importable."""+ from ministack.core.responses import json_response, error_response_json, new_uuid+ from ministack.core.router import detect_service+ from ministack.core.lambda_runtime import get_or_create_worker, reset as lr_reset+ from ministack.core.persistence import save_all, load_state+ assert callable(json_response)+ assert callable(detect_service)+ assert callable(get_or_create_worker)+ assert callable(save_all)+++@_requires_package+def test_package_services_importable():+ """All 25 ministack.services modules must be importable and expose handle_request."""+ from ministack.services import (+ s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logs,+ ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions,+ ecs, rds, elasticache, glue, athena, apigateway, apigateway_v1,+ firehose, route53, cognito,+ )+ from ministack.services.iam_sts import handle_iam_request, handle_sts_request+ for mod in [s3, sqs, sns, dynamodb, lambda_svc, secretsmanager,+ cloudwatch_logs, ssm, eventbridge, kinesis, cloudwatch,+ ses, stepfunctions, ecs, rds, elasticache, glue, athena,+ apigateway, firehose, route53, cognito]:+ assert callable(getattr(mod, "handle_request", None)), \+ f"{mod.__name__} missing handle_request"+ assert callable(handle_iam_request)+ assert callable(handle_sts_request)+++@_requires_package+def test_app_asgi_callable():+ """ministack.app:app must be an async callable (ASGI entry point)."""+ import inspect+ from ministack import app as app_module+ assert callable(app_module.app)+ assert inspect.iscoroutinefunction(app_module.app)+ assert callable(app_module.main)+++# ========== Cognito ==========+++def test_cognito_create_and_describe_user_pool(cognito_idp):+ resp = cognito_idp.create_user_pool(PoolName="TestPool")+ pool = resp["UserPool"]+ pid = pool["Id"]+ assert pool["Name"] == "TestPool"+ assert pid.startswith("us-east-1_")++ desc = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]+ assert desc["Id"] == pid+ assert desc["Name"] == "TestPool"+++def test_cognito_list_user_pools(cognito_idp):+ cognito_idp.create_user_pool(PoolName="ListPoolA")+ cognito_idp.create_user_pool(PoolName="ListPoolB")+ resp = cognito_idp.list_user_pools(MaxResults=60)+ names = [p["Name"] for p in resp["UserPools"]]+ assert "ListPoolA" in names+ assert "ListPoolB" in names+++def test_cognito_update_user_pool(cognito_idp):+ resp = cognito_idp.create_user_pool(PoolName="UpdatePool")+ pid = resp["UserPool"]["Id"]+ cognito_idp.update_user_pool(UserPoolId=pid, UserPoolTags={"env": "test"})+ desc = cognito_idp.describe_user_pool(UserPoolId=pid)["UserPool"]+ assert desc["UserPoolTags"].get("env") == "test"+++def test_cognito_delete_user_pool(cognito_idp):+ resp = cognito_idp.create_user_pool(PoolName="DeletePool")+ pid = resp["UserPool"]["Id"]+ cognito_idp.delete_user_pool(UserPoolId=pid)+ pools = cognito_idp.list_user_pools(MaxResults=60)["UserPools"]+ assert not any(p["Id"] == pid for p in pools)+++def test_cognito_create_and_describe_user_pool_client(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ClientPool")["UserPool"]["Id"]+ client_resp = cognito_idp.create_user_pool_client(+ UserPoolId=pid,+ ClientName="MyApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )+ client = client_resp["UserPoolClient"]+ cid = client["ClientId"]+ assert client["ClientName"] == "MyApp"++ desc = cognito_idp.describe_user_pool_client(UserPoolId=pid, ClientId=cid)["UserPoolClient"]+ assert desc["ClientId"] == cid+ assert desc["ClientName"] == "MyApp"+++def test_cognito_list_user_pool_clients(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="MultiClientPool")["UserPool"]["Id"]+ cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="App1")+ cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="App2")+ clients = cognito_idp.list_user_pool_clients(UserPoolId=pid, MaxResults=60)["UserPoolClients"]+ names = [c["ClientName"] for c in clients]+ assert "App1" in names+ assert "App2" in names+++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(+ UserPoolId=pid,+ Username="alice",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="alice")+ assert user["Username"] == "alice"+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+++def test_cognito_list_users(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ListUsersPool")["UserPool"]["Id"]+ for name in ["user1", "user2", "user3"]:+ cognito_idp.admin_create_user(UserPoolId=pid, Username=name)+ users = cognito_idp.list_users(UserPoolId=pid)["Users"]+ usernames = [u["Username"] for u in users]+ assert "user1" in usernames+ assert "user2" in usernames+ assert "user3" in usernames+++def test_cognito_list_users_filter(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="FilterUsersPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="bob",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="charlie",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ resp = cognito_idp.list_users(UserPoolId=pid, Filter='username = "bob"')+ users = resp["Users"]+ assert len(users) == 1+ assert users[0]["Username"] == "bob"+++def test_cognito_admin_set_user_password(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="PwdPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="PwdApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="dave")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="dave", Password="NewPass123!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid,+ ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "dave", "PASSWORD": "NewPass123!"},+ )+ assert "AuthenticationResult" in auth+++def test_cognito_admin_initiate_auth_wrong_password(cognito_idp):+ import botocore.exceptions+ pid = cognito_idp.create_user_pool(PoolName="AuthFailPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="AuthFailApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="eve")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="eve", Password="Correct1!", Permanent=True+ )+ with pytest.raises(botocore.exceptions.ClientError) as exc_info:+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid,+ ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "eve", "PASSWORD": "Wrong1!"},+ )+ assert exc_info.value.response["Error"]["Code"] == "NotAuthorizedException"+++def test_cognito_initiate_auth_user_password(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="InitiateAuthPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="InitiateApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="frank")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="frank", Password="FrankPass1!", Permanent=True+ )+ auth = cognito_idp.initiate_auth(+ ClientId=cid,+ AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "frank", "PASSWORD": "FrankPass1!"},+ )+ assert "AuthenticationResult" in auth+ result = auth["AuthenticationResult"]+ assert "AccessToken" in result+ assert "IdToken" in result+ assert "RefreshToken" in result+++def test_cognito_signup_and_confirm(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="SignupPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="SignupApp"+ )["UserPoolClient"]["ClientId"]++ resp = cognito_idp.sign_up(+ ClientId=cid,+ Username="grace",+ Password="GracePass1!",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ assert resp["UserSub"]++ cognito_idp.confirm_sign_up(+ ClientId=cid,+ Username="grace",+ ConfirmationCode="123456",+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="grace")+ assert user["UserStatus"] == "CONFIRMED"+++def test_cognito_forgot_password_and_confirm(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ForgotPwdPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="ForgotApp"+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="henry")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="henry", Password="OldPass1!", Permanent=True+ )++ cognito_idp.forgot_password(ClientId=cid, Username="henry")++ cognito_idp.confirm_forgot_password(+ ClientId=cid,+ Username="henry",+ ConfirmationCode="654321",+ Password="NewPass2!",+ )+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="henry", Password="NewPass2!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid,+ ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "henry", "PASSWORD": "NewPass2!"},+ )+ assert "AuthenticationResult" in auth+++def test_cognito_admin_update_user_attributes(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="UpdateAttrPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="irene",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ cognito_idp.admin_update_user_attributes(+ UserPoolId=pid,+ Username="irene",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="irene")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+++def test_cognito_admin_disable_enable_user(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="DisablePool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="jack")++ cognito_idp.admin_disable_user(UserPoolId=pid, Username="jack")+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="jack")+ assert user["Enabled"] is False++ cognito_idp.admin_enable_user(UserPoolId=pid, Username="jack")+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="jack")+ assert user["Enabled"] is True+++def test_cognito_admin_delete_user(cognito_idp):+ import botocore.exceptions+ pid = cognito_idp.create_user_pool(PoolName="DeleteUserPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="kate")+ cognito_idp.admin_delete_user(UserPoolId=pid, Username="kate")+ with pytest.raises(botocore.exceptions.ClientError) as exc_info:+ cognito_idp.admin_get_user(UserPoolId=pid, Username="kate")+ assert exc_info.value.response["Error"]["Code"] == "UserNotFoundException"+++def test_cognito_groups_crud(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="GroupPool")["UserPool"]["Id"]++ resp = cognito_idp.create_group(UserPoolId=pid, GroupName="admins", Description="Admins")+ assert resp["Group"]["GroupName"] == "admins"++ group = cognito_idp.get_group(UserPoolId=pid, GroupName="admins")["Group"]+ assert group["Description"] == "Admins"++ groups = cognito_idp.list_groups(UserPoolId=pid)["Groups"]+ assert any(g["GroupName"] == "admins" for g in groups)++ cognito_idp.delete_group(UserPoolId=pid, GroupName="admins")+ groups = cognito_idp.list_groups(UserPoolId=pid)["Groups"]+ assert not any(g["GroupName"] == "admins" for g in groups)+++def test_cognito_admin_add_remove_user_from_group(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="GroupMemberPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="liam")+ cognito_idp.create_group(UserPoolId=pid, GroupName="editors")++ cognito_idp.admin_add_user_to_group(UserPoolId=pid, Username="liam", GroupName="editors")+ members = cognito_idp.list_users_in_group(UserPoolId=pid, GroupName="editors")["Users"]+ assert any(u["Username"] == "liam" for u in members)++ groups_for_user = cognito_idp.admin_list_groups_for_user(+ UserPoolId=pid, Username="liam"+ )["Groups"]+ assert any(g["GroupName"] == "editors" for g in groups_for_user)++ cognito_idp.admin_remove_user_from_group(+ UserPoolId=pid, Username="liam", GroupName="editors"+ )+ members = cognito_idp.list_users_in_group(UserPoolId=pid, GroupName="editors")["Users"]+ assert not any(u["Username"] == "liam" for u in members)+++def test_cognito_domain_crud(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="DomainPool")["UserPool"]["Id"]+ resp = cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain="my-test-domain")+ assert "CloudFrontDomain" in resp++ desc = cognito_idp.describe_user_pool_domain(Domain="my-test-domain")+ assert desc["DomainDescription"]["UserPoolId"] == pid+ assert desc["DomainDescription"]["Status"] == "ACTIVE"++ cognito_idp.delete_user_pool_domain(UserPoolId=pid, Domain="my-test-domain")+ desc2 = cognito_idp.describe_user_pool_domain(Domain="my-test-domain")+ assert desc2["DomainDescription"] == {}+++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"++ cognito_idp.set_user_pool_mfa_config(+ UserPoolId=pid,+ SoftwareTokenMfaConfiguration={"Enabled": True},+ MfaConfiguration="OPTIONAL",+ )+ resp = cognito_idp.get_user_pool_mfa_config(UserPoolId=pid)+ assert resp["MfaConfiguration"] == "OPTIONAL"+ assert resp["SoftwareTokenMfaConfiguration"]["Enabled"] is True+++def test_cognito_tags(cognito_idp):+ resp = cognito_idp.create_user_pool(PoolName="TagPool")+ pid = resp["UserPool"]["Id"]+ arn = resp["UserPool"]["Arn"]++ cognito_idp.tag_resource(ResourceArn=arn, Tags={"project": "ministack"})+ tags = cognito_idp.list_tags_for_resource(ResourceArn=arn)["Tags"]+ assert tags["project"] == "ministack"++ cognito_idp.untag_resource(ResourceArn=arn, TagKeys=["project"])+ tags = cognito_idp.list_tags_for_resource(ResourceArn=arn)["Tags"]+ assert "project" not in tags+++def test_cognito_get_user_from_token(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="GetUserPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="GetUserApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(+ UserPoolId=pid,+ Username="maya",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="maya", Password="MayaPass1!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid,+ ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "maya", "PASSWORD": "MayaPass1!"},+ )+ access_token = auth["AuthenticationResult"]["AccessToken"]+ user = cognito_idp.get_user(AccessToken=access_token)+ assert user["Username"] == "maya"+++def test_cognito_global_sign_out(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="SignOutPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="SignOutApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="noah")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="noah", Password="NoahPass1!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid,+ ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "noah", "PASSWORD": "NoahPass1!"},+ )+ access_token = auth["AuthenticationResult"]["AccessToken"]+ cognito_idp.global_sign_out(AccessToken=access_token) # must not raise+++def test_cognito_admin_confirm_signup(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="AdminConfirmPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="AdminConfirmApp"+ )["UserPoolClient"]["ClientId"]+ cognito_idp.sign_up(+ ClientId=cid,+ Username="olivia",+ Password="OliviaPass1!",+ )+ cognito_idp.admin_confirm_sign_up(UserPoolId=pid, Username="olivia")+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="olivia")+ assert user["UserStatus"] == "CONFIRMED"+++# Identity Pools (cognito-identity)++def test_cognito_identity_pool_crud(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="TestIdPool",+ AllowUnauthenticatedIdentities=False,+ )+ iid = resp["IdentityPoolId"]+ assert resp["IdentityPoolName"] == "TestIdPool"+ assert iid.startswith("us-east-1:")++ desc = cognito_identity.describe_identity_pool(IdentityPoolId=iid)+ assert desc["IdentityPoolId"] == iid+ assert desc["IdentityPoolName"] == "TestIdPool"++ pools = cognito_identity.list_identity_pools(MaxResults=60)["IdentityPools"]+ assert any(p["IdentityPoolId"] == iid for p in pools)++ cognito_identity.update_identity_pool(+ IdentityPoolId=iid,+ IdentityPoolName="TestIdPool",+ AllowUnauthenticatedIdentities=True,+ )+ desc2 = cognito_identity.describe_identity_pool(IdentityPoolId=iid)+ assert desc2["AllowUnauthenticatedIdentities"] is True++ cognito_identity.delete_identity_pool(IdentityPoolId=iid)+ pools2 = cognito_identity.list_identity_pools(MaxResults=60)["IdentityPools"]+ assert not any(p["IdentityPoolId"] == iid for p in pools2)+++def test_cognito_get_id_and_credentials(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="CredsPool",+ AllowUnauthenticatedIdentities=True,+ )+ iid = resp["IdentityPoolId"]++ id_resp = cognito_identity.get_id(IdentityPoolId=iid, AccountId="000000000000")+ identity_id = id_resp["IdentityId"]+ assert identity_id++ creds = cognito_identity.get_credentials_for_identity(IdentityId=identity_id)+ assert creds["IdentityId"] == identity_id+ assert "AccessKeyId" in creds["Credentials"]+ assert creds["Credentials"]["AccessKeyId"].startswith("ASIA")+ assert "SecretKey" in creds["Credentials"]+ assert "SessionToken" in creds["Credentials"]+++def test_cognito_identity_pool_roles(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="RolesPool",+ AllowUnauthenticatedIdentities=True,+ )+ iid = resp["IdentityPoolId"]++ cognito_identity.set_identity_pool_roles(+ IdentityPoolId=iid,+ Roles={+ "authenticated": "arn:aws:iam::000000000000:role/AuthRole",+ "unauthenticated": "arn:aws:iam::000000000000:role/UnauthRole",+ },+ )+ roles = cognito_identity.get_identity_pool_roles(IdentityPoolId=iid)+ assert roles["Roles"]["authenticated"] == "arn:aws:iam::000000000000:role/AuthRole"+ assert roles["Roles"]["unauthenticated"] == "arn:aws:iam::000000000000:role/UnauthRole"+++def test_cognito_list_identities(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="ListIdPool",+ AllowUnauthenticatedIdentities=True,+ )+ iid = resp["IdentityPoolId"]++ id1 = cognito_identity.get_id(IdentityPoolId=iid, AccountId="000000000000")["IdentityId"]+ id2 = cognito_identity.get_id(IdentityPoolId=iid, AccountId="000000000000")["IdentityId"]++ identities = cognito_identity.list_identities(IdentityPoolId=iid, MaxResults=60)["Identities"]+ ids = [i["IdentityId"] for i in identities]+ assert id1 in ids+ assert id2 in ids+++def test_cognito_get_open_id_token(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="OidcPool",+ AllowUnauthenticatedIdentities=True,+ )+ iid = resp["IdentityPoolId"]+ identity_id = cognito_identity.get_id(+ IdentityPoolId=iid, AccountId="000000000000"+ )["IdentityId"]++ token_resp = cognito_identity.get_open_id_token(IdentityId=identity_id)+ assert token_resp["IdentityId"] == identity_id+ token = token_resp["Token"]+ # Verify stub JWT structure: header.payload.sig+ parts = token.split(".")+ assert len(parts) == 3+++def test_cognito_signup_always_unconfirmed(cognito_idp):+ """SignUp always returns UNCONFIRMED regardless of AutoVerifiedAttributes."""+ # Pool with AutoVerifiedAttributes — user still starts UNCONFIRMED+ pid = cognito_idp.create_user_pool(+ PoolName="AutoVerifyPool",+ AutoVerifiedAttributes=["email"],+ )["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="AutoVerifyApp"+ )["UserPoolClient"]["ClientId"]+ resp = cognito_idp.sign_up(+ ClientId=cid,+ Username="testuser",+ Password="TestPass1!",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ assert resp["UserConfirmed"] is False+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="testuser")+ assert user["UserStatus"] == "UNCONFIRMED"++ # Pool with NO AutoVerifiedAttributes — user also starts UNCONFIRMED+ pid2 = cognito_idp.create_user_pool(PoolName="NoAutoVerifyPool")["UserPool"]["Id"]+ cid2 = cognito_idp.create_user_pool_client(+ UserPoolId=pid2, ClientName="NoAutoVerifyApp"+ )["UserPoolClient"]["ClientId"]+ resp2 = cognito_idp.sign_up(+ ClientId=cid2, Username="testuser2", Password="TestPass1!"+ )+ assert resp2["UserConfirmed"] is False+ user2 = cognito_idp.admin_get_user(UserPoolId=pid2, Username="testuser2")+ assert user2["UserStatus"] == "UNCONFIRMED"+++def test_cognito_change_password(cognito_idp):+ """ChangePassword decodes the access token and updates the stored password."""+ pid = cognito_idp.create_user_pool(PoolName="ChangePwdPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="ChangePwdApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="pwduser")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="pwduser", Password="OldPass1!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "pwduser", "PASSWORD": "OldPass1!"},+ )+ access_token = auth["AuthenticationResult"]["AccessToken"]++ cognito_idp.change_password(+ AccessToken=access_token,+ PreviousPassword="OldPass1!",+ ProposedPassword="NewPass2!",+ )++ # New password must work+ auth2 = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "pwduser", "PASSWORD": "NewPass2!"},+ )+ assert "AuthenticationResult" in auth2++ # Old password must fail+ import botocore.exceptions+ with pytest.raises(botocore.exceptions.ClientError) as exc_info:+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "pwduser", "PASSWORD": "OldPass1!"},+ )+ assert exc_info.value.response["Error"]["Code"] == "NotAuthorizedException"+++def test_cognito_refresh_token_auth_correct_user(cognito_idp):+ """REFRESH_TOKEN_AUTH returns tokens for the correct user, not the first user in the pool."""+ pid = cognito_idp.create_user_pool(PoolName="RefreshPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="RefreshApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]++ for name, pw in [("first", "First1!"), ("second", "Second1!")]:+ cognito_idp.admin_create_user(UserPoolId=pid, Username=name)+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username=name, Password=pw, Permanent=True+ )++ # Auth as "second" user and refresh+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "second", "PASSWORD": "Second1!"},+ )+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]++ refresh = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )+ assert "AuthenticationResult" in refresh+ # New access token should resolve back to "second" via GetUser+ new_access = refresh["AuthenticationResult"]["AccessToken"]+ user = cognito_idp.get_user(AccessToken=new_access)+ assert user["Username"] == "second"+++def test_cognito_refresh_token_alias(cognito_idp):+ """REFRESH_TOKEN (without _AUTH suffix) is accepted as an alias."""+ pid = cognito_idp.create_user_pool(PoolName="RefreshAliasPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="RefreshAliasApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="aliasuser")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="aliasuser", Password="AliasPass1!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "aliasuser", "PASSWORD": "AliasPass1!"},+ )+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ refresh = cognito_idp.initiate_auth(+ ClientId=cid,+ AuthFlow="REFRESH_TOKEN",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )+ assert "AuthenticationResult" in refresh+ assert "AccessToken" in refresh["AuthenticationResult"]+ assert "RefreshToken" not in refresh["AuthenticationResult"]+++def test_cognito_respond_to_auth_challenge_new_password(cognito_idp):+ """RespondToAuthChallenge with NEW_PASSWORD_REQUIRED confirms the user."""+ pid = cognito_idp.create_user_pool(PoolName="ChallengePool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="ChallengeApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="newpwduser")+ # Set a temp password — Permanent=False keeps FORCE_CHANGE_PASSWORD status+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="newpwduser", Password="TempPass1!", Permanent=False+ )+ # Initiate auth — FORCE_CHANGE_PASSWORD triggers NEW_PASSWORD_REQUIRED challenge+ auth = cognito_idp.initiate_auth(+ ClientId=cid,+ AuthFlow="USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "newpwduser", "PASSWORD": "TempPass1!"},+ )+ assert auth.get("ChallengeName") == "NEW_PASSWORD_REQUIRED"+ session = auth["Session"]+ result = cognito_idp.respond_to_auth_challenge(+ ClientId=cid,+ ChallengeName="NEW_PASSWORD_REQUIRED",+ Session=session,+ ChallengeResponses={"USERNAME": "newpwduser", "NEW_PASSWORD": "FinalPass1!"},+ )+ assert "AuthenticationResult" in result+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="newpwduser")+ assert user["UserStatus"] == "CONFIRMED"+++def test_cognito_update_user_attributes_via_token(cognito_idp):+ """UpdateUserAttributes (self-service) updates attributes using access token."""+ pid = cognito_idp.create_user_pool(PoolName="UpdateAttrTokenPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="UpdateAttrApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(+ UserPoolId=pid, Username="attrupdate",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="attrupdate", Password="AttrPass1!", Permanent=True+ )+ access_token = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "attrupdate", "PASSWORD": "AttrPass1!"},+ )["AuthenticationResult"]["AccessToken"]++ cognito_idp.update_user_attributes(+ AccessToken=access_token,+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="attrupdate")+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+++def test_cognito_delete_user_via_token(cognito_idp):+ """DeleteUser (self-service) removes the user using access token."""+ import botocore.exceptions+ pid = cognito_idp.create_user_pool(PoolName="DeleteSelfPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="DeleteSelfApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="selfdelete")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="selfdelete", Password="DelPass1!", Permanent=True+ )+ access_token = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "selfdelete", "PASSWORD": "DelPass1!"},+ )["AuthenticationResult"]["AccessToken"]++ cognito_idp.delete_user(AccessToken=access_token)++ with pytest.raises(botocore.exceptions.ClientError) as exc_info:+ cognito_idp.admin_get_user(UserPoolId=pid, Username="selfdelete")+ assert exc_info.value.response["Error"]["Code"] == "UserNotFoundException"+++def test_cognito_update_user_pool_client(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="UpdateClientPool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="OriginalName"+ )["UserPoolClient"]["ClientId"]+ updated = cognito_idp.update_user_pool_client(+ UserPoolId=pid, ClientId=cid, ClientName="UpdatedName",+ RefreshTokenValidity=14,+ )["UserPoolClient"]+ assert updated["ClientName"] == "UpdatedName"+ assert updated["RefreshTokenValidity"] == 14+ # Verify persisted+ desc = cognito_idp.describe_user_pool_client(UserPoolId=pid, ClientId=cid)["UserPoolClient"]+ assert desc["ClientName"] == "UpdatedName"+++def test_cognito_admin_reset_user_password(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="ResetPwdPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="resetuser")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="resetuser", Password="Pass1!", Permanent=True+ )+ cognito_idp.admin_reset_user_password(UserPoolId=pid, Username="resetuser")+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="resetuser")+ assert user["UserStatus"] == "RESET_REQUIRED"+++def test_cognito_admin_user_global_sign_out(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="GlobalSignOutAdminPool")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="signoutuser")+ cognito_idp.admin_user_global_sign_out(UserPoolId=pid, Username="signoutuser")+++def test_cognito_revoke_token(cognito_idp):+ pid = cognito_idp.create_user_pool(PoolName="RevokePool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="RevokeApp",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="revokeuser")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="revokeuser", Password="RevokePass1!", Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "revokeuser", "PASSWORD": "RevokePass1!"},+ )+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ cognito_idp.revoke_token(Token=refresh_token, ClientId=cid)+++def test_cognito_describe_identity(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="DescribeIdPool",+ AllowUnauthenticatedIdentities=True,+ )+ iid = resp["IdentityPoolId"]+ identity_id = cognito_identity.get_id(+ IdentityPoolId=iid, AccountId="000000000000"+ )["IdentityId"]+ desc = cognito_identity.describe_identity(IdentityId=identity_id)+ assert desc["IdentityId"] == identity_id+++def test_cognito_merge_developer_identities(cognito_identity):+ resp = cognito_identity.create_identity_pool(+ IdentityPoolName="MergePool",+ AllowUnauthenticatedIdentities=True,+ DeveloperProviderName="login.myapp",+ )+ iid = resp["IdentityPoolId"]+ result = cognito_identity.merge_developer_identities(+ SourceUserIdentifier="user-a",+ DestinationUserIdentifier="user-b",+ DeveloperProviderName="login.myapp",+ IdentityPoolId=iid,+ )+ assert "IdentityId" in result+++# ===========================================================================+# QA — Edge cases and regression tests (merged from test_qa_comprehensive.py)+# ===========================================================================++def _zip_lambda(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++# ---------------------------------------------------------------------------+# COGNITO — fix regressions + edge cases+# ---------------------------------------------------------------------------++def test_cognito_credentials_secret_access_key(cognito_identity):+ """GetCredentialsForIdentity must return SecretKey (boto3 wire name)."""+ iid = cognito_identity.create_identity_pool(+ IdentityPoolName="qa-creds-pool",+ AllowUnauthenticatedIdentities=True,+ )["IdentityPoolId"]+ identity_id = cognito_identity.get_id(+ IdentityPoolId=iid, AccountId="000000000000"+ )["IdentityId"]+ creds = cognito_identity.get_credentials_for_identity(IdentityId=identity_id)+ c = creds["Credentials"]+ assert "SecretKey" in c+ assert c["AccessKeyId"].startswith("ASIA")+ assert "SessionToken" in c+ assert c["Expiration"] is not None+++def test_cognito_change_password_actually_changes(cognito_idp):+ """ChangePassword must update the stored password so old one stops working."""+ pid = cognito_idp.create_user_pool(PoolName="qa-changepwd")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-changepwd-app",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="qa-cpwd-user")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="qa-cpwd-user", Password="OldPwd1!", Permanent=True+ )+ token = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-cpwd-user", "PASSWORD": "OldPwd1!"},+ )["AuthenticationResult"]["AccessToken"]+ cognito_idp.change_password(+ AccessToken=token, PreviousPassword="OldPwd1!", ProposedPassword="NewPwd2!"+ )+ auth2 = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-cpwd-user", "PASSWORD": "NewPwd2!"},+ )+ assert "AuthenticationResult" in auth2+ with pytest.raises(ClientError) as exc:+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-cpwd-user", "PASSWORD": "OldPwd1!"},+ )+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+++def test_cognito_refresh_token_returns_correct_user(cognito_idp):+ """REFRESH_TOKEN_AUTH must return tokens for the refreshing user, not users[0]."""+ pid = cognito_idp.create_user_pool(PoolName="qa-refresh-pool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-refresh-app",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ for name, pw in [("qa-first", "First1!"), ("qa-second", "Second1!")]:+ cognito_idp.admin_create_user(UserPoolId=pid, Username=name)+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username=name, Password=pw, Permanent=True+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-second", "PASSWORD": "Second1!"},+ )+ refresh_token = auth["AuthenticationResult"]["RefreshToken"]+ refresh = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="REFRESH_TOKEN_AUTH",+ AuthParameters={"REFRESH_TOKEN": refresh_token},+ )+ new_token = refresh["AuthenticationResult"]["AccessToken"]+ user = cognito_idp.get_user(AccessToken=new_token)+ assert user["Username"] == "qa-second", "Refresh must return tokens for qa-second not qa-first"+++def test_cognito_signup_unconfirmed_with_auto_verify(cognito_idp):+ """SignUp with AutoVerifiedAttributes must return UserConfirmed=False."""+ pid = cognito_idp.create_user_pool(+ PoolName="qa-autoverify", AutoVerifiedAttributes=["email"]+ )["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-autoverify-app"+ )["UserPoolClient"]["ClientId"]+ resp = cognito_idp.sign_up(+ ClientId=cid, Username="qa-signup-user", Password="SignUp1!",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}],+ )+ assert resp["UserConfirmed"] is False+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="qa-signup-user")+ assert user["UserStatus"] == "UNCONFIRMED"+++def test_cognito_disabled_user_auth_fails(cognito_idp):+ """Disabled user must get NotAuthorizedException."""+ pid = cognito_idp.create_user_pool(PoolName="qa-disabled-pool")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-disabled-app",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="qa-disabled")+ cognito_idp.admin_set_user_password(+ UserPoolId=pid, Username="qa-disabled", Password="Dis1!", Permanent=True+ )+ cognito_idp.admin_disable_user(UserPoolId=pid, Username="qa-disabled")+ with pytest.raises(ClientError) as exc:+ cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-disabled", "PASSWORD": "Dis1!"},+ )+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"+++def test_cognito_list_users_in_group(cognito_idp):+ """ListUsersInGroup must return members added via AdminAddUserToGroup."""+ pid = cognito_idp.create_user_pool(PoolName="qa-group-members")["UserPool"]["Id"]+ cognito_idp.create_group(UserPoolId=pid, GroupName="qa-grp")+ for u in ["qa-u1", "qa-u2", "qa-u3"]:+ cognito_idp.admin_create_user(UserPoolId=pid, Username=u)+ cognito_idp.admin_add_user_to_group(UserPoolId=pid, Username=u, GroupName="qa-grp")+ members = cognito_idp.list_users_in_group(UserPoolId=pid, GroupName="qa-grp")["Users"]+ names = {u["Username"] for u in members}+ assert {"qa-u1", "qa-u2", "qa-u3"} == names+++def test_cognito_duplicate_username_error(cognito_idp):+ """AdminCreateUser with duplicate username must raise UsernameExistsException."""+ pid = cognito_idp.create_user_pool(PoolName="qa-dup-user")["UserPool"]["Id"]+ cognito_idp.admin_create_user(UserPoolId=pid, Username="qa-dup")+ with pytest.raises(ClientError) as exc:+ cognito_idp.admin_create_user(UserPoolId=pid, Username="qa-dup")+ assert exc.value.response["Error"]["Code"] == "UsernameExistsException"+++def test_cognito_client_secret_generated(cognito_idp):+ """CreateUserPoolClient with GenerateSecret=True must return a ClientSecret."""+ pid = cognito_idp.create_user_pool(PoolName="qa-secret-client")["UserPool"]["Id"]+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-secret-app", GenerateSecret=True+ )["UserPoolClient"]+ assert "ClientSecret" in client+ assert len(client["ClientSecret"]) > 20+++def test_cognito_force_change_password_challenge(cognito_idp):+ """AdminCreateUser with TemporaryPassword triggers NEW_PASSWORD_REQUIRED challenge."""+ pid = cognito_idp.create_user_pool(PoolName="qa-force-change")["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="qa-force-app",+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ )["UserPoolClient"]["ClientId"]+ cognito_idp.admin_create_user(+ UserPoolId=pid, Username="qa-force-user",+ TemporaryPassword="TempPwd1!",+ )+ auth = cognito_idp.admin_initiate_auth(+ UserPoolId=pid, ClientId=cid,+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": "qa-force-user", "PASSWORD": "TempPwd1!"},+ )+ assert auth.get("ChallengeName") == "NEW_PASSWORD_REQUIRED"+ assert "Session" in auth+++# ---------------------------------------------------------------------------+# DYNAMODB — edge cases+# ---------------------------------------------------------------------------++def test_ddb_update_item_updated_new(ddb):+ """UpdateItem ReturnValues=UPDATED_NEW returns only changed attributes."""+ ddb.create_table(+ TableName="qa-ddb-updated-new",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="qa-ddb-updated-new", Item={+ "pk": {"S": "k1"}, "a": {"S": "old"}, "b": {"N": "1"}+ })+ resp = ddb.update_item(+ TableName="qa-ddb-updated-new",+ Key={"pk": {"S": "k1"}},+ UpdateExpression="SET a = :new",+ ExpressionAttributeValues={":new": {"S": "new"}},+ ReturnValues="UPDATED_NEW",+ )+ assert "Attributes" in resp+ assert resp["Attributes"]["a"]["S"] == "new"+ assert "b" not in resp["Attributes"]+++def test_ddb_update_item_updated_old(ddb):+ """UpdateItem ReturnValues=UPDATED_OLD returns old values of changed attributes."""+ ddb.create_table(+ TableName="qa-ddb-updated-old",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="qa-ddb-updated-old", Item={+ "pk": {"S": "k1"}, "score": {"N": "10"}+ })+ resp = ddb.update_item(+ TableName="qa-ddb-updated-old",+ Key={"pk": {"S": "k1"}},+ UpdateExpression="SET score = :new",+ ExpressionAttributeValues={":new": {"N": "20"}},+ ReturnValues="UPDATED_OLD",+ )+ assert resp["Attributes"]["score"]["N"] == "10"+++def test_ddb_conditional_put_fails(ddb):+ """PutItem with attribute_not_exists condition fails if item already exists."""+ ddb.create_table(+ TableName="qa-ddb-cond-put",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="qa-ddb-cond-put", Item={"pk": {"S": "exists"}})+ with pytest.raises(ClientError) as exc:+ ddb.put_item(+ TableName="qa-ddb-cond-put",+ Item={"pk": {"S": "exists"}, "data": {"S": "new"}},+ ConditionExpression="attribute_not_exists(pk)",+ )+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"+++def test_ddb_query_with_filter_expression(ddb):+ """Query with FilterExpression reduces Count but not ScannedCount."""+ ddb.create_table(+ TableName="qa-ddb-filter",+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "N"},+ ],+ BillingMode="PAY_PER_REQUEST",+ )+ for i in range(5):+ ddb.put_item(TableName="qa-ddb-filter", Item={+ "pk": {"S": "user1"}, "sk": {"N": str(i)}, "active": {"BOOL": i % 2 == 0}+ })+ resp = ddb.query(+ TableName="qa-ddb-filter",+ KeyConditionExpression="pk = :pk",+ FilterExpression="active = :t",+ ExpressionAttributeValues={":pk": {"S": "user1"}, ":t": {"BOOL": True}},+ )+ assert resp["Count"] == 3+ assert resp["ScannedCount"] == 5+++def test_ddb_scan_with_limit_and_pagination(ddb):+ """Scan with Limit returns LastEvaluatedKey and pagination works."""+ ddb.create_table(+ TableName="qa-ddb-scan-page",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ for i in range(10):+ ddb.put_item(TableName="qa-ddb-scan-page", Item={"pk": {"S": f"item{i:02d}"}})+ all_items = []+ lek = None+ while True:+ kwargs = {"TableName": "qa-ddb-scan-page", "Limit": 3}+ if lek:+ kwargs["ExclusiveStartKey"] = lek+ resp = ddb.scan(**kwargs)+ all_items.extend(resp["Items"])+ lek = resp.get("LastEvaluatedKey")+ if not lek:+ break+ assert len(all_items) == 10+++def test_ddb_transact_write_condition_cancel(ddb):+ """TransactWriteItems cancels entire transaction if one condition fails."""+ ddb.create_table(+ TableName="qa-ddb-transact",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="qa-ddb-transact", Item={"pk": {"S": "existing"}})+ with pytest.raises(ClientError) as exc:+ ddb.transact_write_items(TransactItems=[+ {"Put": {+ "TableName": "qa-ddb-transact",+ "Item": {"pk": {"S": "new-item"}},+ }},+ {"Put": {+ "TableName": "qa-ddb-transact",+ "Item": {"pk": {"S": "existing"}, "data": {"S": "x"}},+ "ConditionExpression": "attribute_not_exists(pk)",+ }},+ ])+ assert exc.value.response["Error"]["Code"] == "TransactionCanceledException"+ resp = ddb.get_item(TableName="qa-ddb-transact", Key={"pk": {"S": "new-item"}})+ assert "Item" not in resp+++def test_ddb_batch_get_missing_table(ddb):+ """BatchGetItem with non-existent table returns it in UnprocessedKeys."""+ resp = ddb.batch_get_item(RequestItems={+ "qa-ddb-nonexistent-xyz": {"Keys": [{"pk": {"S": "k1"}}]}+ })+ assert "qa-ddb-nonexistent-xyz" in resp["UnprocessedKeys"]+++# ---------------------------------------------------------------------------+# S3 — edge cases+# ---------------------------------------------------------------------------++def test_s3_range_suffix(s3):+ """Range: bytes=-N returns last N bytes."""+ s3.create_bucket(Bucket="qa-s3-range-suffix")+ s3.put_object(Bucket="qa-s3-range-suffix", Key="data.txt", Body=b"0123456789")+ resp = s3.get_object(Bucket="qa-s3-range-suffix", Key="data.txt", Range="bytes=-3")+ assert resp["Body"].read() == b"789"+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 206+++def test_s3_range_beyond_end(s3):+ """Range start beyond file size returns 416."""+ s3.create_bucket(Bucket="qa-s3-range-beyond")+ s3.put_object(Bucket="qa-s3-range-beyond", Key="small.txt", Body=b"hello")+ with pytest.raises(ClientError) as exc:+ s3.get_object(Bucket="qa-s3-range-beyond", Key="small.txt", Range="bytes=100-200")+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 416+++def test_s3_list_v1_marker_pagination(s3):+ """ListObjects v1 Marker pagination returns correct pages."""+ s3.create_bucket(Bucket="qa-s3-marker")+ keys = [f"file{i:03d}.txt" for i in range(10)]+ for k in keys:+ s3.put_object(Bucket="qa-s3-marker", Key=k, Body=b"x")+ # NextMarker only returned when Delimiter is set (AWS spec)+ resp1 = s3.list_objects(Bucket="qa-s3-marker", MaxKeys=4, Delimiter="/")+ assert resp1["IsTruncated"] is True+ assert len(resp1["Contents"]) == 4+ marker = resp1["NextMarker"]+ resp2 = s3.list_objects(Bucket="qa-s3-marker", MaxKeys=4, Marker=marker, Delimiter="/")+ page2_keys = [o["Key"] for o in resp2["Contents"]]+ page1_keys = [o["Key"] for o in resp1["Contents"]]+ assert not any(k in page1_keys for k in page2_keys)+++def test_s3_delete_objects_returns_deleted(s3):+ """DeleteObjects returns each deleted key in Deleted list."""+ s3.create_bucket(Bucket="qa-s3-batch-del")+ for i in range(3):+ s3.put_object(Bucket="qa-s3-batch-del", Key=f"obj{i}.txt", Body=b"x")+ resp = s3.delete_objects(+ Bucket="qa-s3-batch-del",+ Delete={"Objects": [{"Key": f"obj{i}.txt"} for i in range(3)]},+ )+ assert len(resp["Deleted"]) == 3+ assert not resp.get("Errors")+++def test_s3_put_object_content_type_preserved(s3):+ """Content-Type set on PutObject is returned on GetObject."""+ s3.create_bucket(Bucket="qa-s3-ct")+ s3.put_object(+ Bucket="qa-s3-ct", Key="page.html",+ Body=b"<html/>", ContentType="text/html; charset=utf-8"+ )+ resp = s3.get_object(Bucket="qa-s3-ct", Key="page.html")+ assert "text/html" in resp["ContentType"]+++def test_s3_head_object_returns_content_length(s3):+ """HeadObject must return correct ContentLength."""+ s3.create_bucket(Bucket="qa-s3-head-len")+ body = b"exactly twenty bytes"+ s3.put_object(Bucket="qa-s3-head-len", Key="f.bin", Body=body)+ resp = s3.head_object(Bucket="qa-s3-head-len", Key="f.bin")+ assert resp["ContentLength"] == len(body)+++def test_s3_copy_preserves_metadata(s3):+ """CopyObject with MetadataDirective=COPY preserves source metadata."""+ s3.create_bucket(Bucket="qa-s3-copy-meta")+ s3.put_object(+ Bucket="qa-s3-copy-meta", Key="src.txt", Body=b"data",+ Metadata={"x-custom": "value123"},+ )+ s3.copy_object(+ CopySource={"Bucket": "qa-s3-copy-meta", "Key": "src.txt"},+ Bucket="qa-s3-copy-meta", Key="dst.txt",+ MetadataDirective="COPY",+ )+ resp = s3.head_object(Bucket="qa-s3-copy-meta", Key="dst.txt")+ assert resp["Metadata"].get("x-custom") == "value123"+++def test_s3_multipart_list_parts(s3):+ """ListParts returns uploaded parts before completion."""+ s3.create_bucket(Bucket="qa-s3-listparts")+ mpu = s3.create_multipart_upload(Bucket="qa-s3-listparts", Key="big.bin")+ uid = mpu["UploadId"]+ p1 = s3.upload_part(Bucket="qa-s3-listparts", Key="big.bin",+ UploadId=uid, PartNumber=1, Body=b"A" * 50)+ p2 = s3.upload_part(Bucket="qa-s3-listparts", Key="big.bin",+ UploadId=uid, PartNumber=2, Body=b"B" * 50)+ parts = s3.list_parts(Bucket="qa-s3-listparts", Key="big.bin", UploadId=uid)["Parts"]+ assert len(parts) == 2+ assert parts[0]["PartNumber"] == 1+ assert parts[1]["PartNumber"] == 2+ s3.complete_multipart_upload(+ Bucket="qa-s3-listparts", Key="big.bin", UploadId=uid,+ MultipartUpload={"Parts": [+ {"PartNumber": 1, "ETag": p1["ETag"]},+ {"PartNumber": 2, "ETag": p2["ETag"]},+ ]},+ )+++def test_s3_list_multipart_uploads(s3):+ """ListMultipartUploads returns in-progress uploads."""+ s3.create_bucket(Bucket="qa-s3-list-mpu")+ uid1 = s3.create_multipart_upload(Bucket="qa-s3-list-mpu", Key="a.bin")["UploadId"]+ uid2 = s3.create_multipart_upload(Bucket="qa-s3-list-mpu", Key="b.bin")["UploadId"]+ resp = s3.list_multipart_uploads(Bucket="qa-s3-list-mpu")+ upload_ids = {u["UploadId"] for u in resp.get("Uploads", [])}+ assert uid1 in upload_ids+ assert uid2 in upload_ids+ s3.abort_multipart_upload(Bucket="qa-s3-list-mpu", Key="a.bin", UploadId=uid1)+ s3.abort_multipart_upload(Bucket="qa-s3-list-mpu", Key="b.bin", UploadId=uid2)+++# ---------------------------------------------------------------------------+# SQS — edge cases+# ---------------------------------------------------------------------------++def test_sqs_receive_max_10(sqs):+ """ReceiveMessage with MaxNumberOfMessages > 10 is capped at 10."""+ url = sqs.create_queue(QueueName="qa-sqs-max10")["QueueUrl"]+ for i in range(15):+ sqs.send_message(QueueUrl=url, MessageBody=f"msg{i}")+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=15)+ assert len(msgs.get("Messages", [])) <= 10+++def test_sqs_visibility_timeout_zero_makes_visible(sqs):+ """ChangeMessageVisibility to 0 makes message immediately visible again."""+ url = sqs.create_queue(QueueName="qa-sqs-vis0")["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="vis-test")+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1, VisibilityTimeout=30)+ rh = msgs["Messages"][0]["ReceiptHandle"]+ sqs.change_message_visibility(QueueUrl=url, ReceiptHandle=rh, VisibilityTimeout=0)+ msgs2 = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ assert len(msgs2.get("Messages", [])) == 1+++def test_sqs_batch_delete_invalid_receipt_handle_in_failed(sqs):+ """DeleteMessageBatch with invalid receipt handle puts entry in Failed."""+ url = sqs.create_queue(QueueName="qa-sqs-batchdel-fail")["QueueUrl"]+ resp = sqs.delete_message_batch(+ QueueUrl=url,+ Entries=[{"Id": "bad1", "ReceiptHandle": "totally-invalid-handle"}],+ )+ assert len(resp.get("Failed", [])) == 1+ assert resp["Failed"][0]["Id"] == "bad1"+ assert len(resp.get("Successful", [])) == 0+++def test_sqs_fifo_group_ordering(sqs):+ """FIFO queue delivers messages in send order within a group."""+ url = sqs.create_queue(+ QueueName="qa-sqs-fifo-order.fifo",+ Attributes={"FifoQueue": "true", "ContentBasedDeduplication": "true"},+ )["QueueUrl"]+ for i in range(3):+ sqs.send_message(QueueUrl=url, MessageBody=f"msg{i}", MessageGroupId="g1")+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ assert msgs["Messages"][0]["Body"] == "msg0"+++def test_sqs_approximate_message_count(sqs):+ """ApproximateNumberOfMessages reflects messages in queue."""+ url = sqs.create_queue(QueueName="qa-sqs-count")["QueueUrl"]+ for i in range(5):+ sqs.send_message(QueueUrl=url, MessageBody=f"m{i}")+ attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["ApproximateNumberOfMessages"])+ count = int(attrs["Attributes"]["ApproximateNumberOfMessages"])+ assert count == 5+++def test_sqs_purge_empties_queue(sqs):+ """PurgeQueue removes all messages."""+ url = sqs.create_queue(QueueName="qa-sqs-purge2")["QueueUrl"]+ for i in range(5):+ sqs.send_message(QueueUrl=url, MessageBody=f"m{i}")+ sqs.purge_queue(QueueUrl=url)+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=0)+ assert len(msgs.get("Messages", [])) == 0+++# ---------------------------------------------------------------------------+# SNS — edge cases+# ---------------------------------------------------------------------------++def test_sns_filter_policy_blocks_non_matching(sns, sqs):+ """SNS filter policy prevents delivery when message attributes don't match."""+ topic_arn = sns.create_topic(Name="qa-sns-filter")["TopicArn"]+ q_url = sqs.create_queue(QueueName="qa-sns-filter-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"]+ )["Attributes"]["QueueArn"]+ sub_arn = sns.subscribe(+ TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn+ )["SubscriptionArn"]+ sns.set_subscription_attributes(+ SubscriptionArn=sub_arn,+ AttributeName="FilterPolicy",+ AttributeValue=json.dumps({"color": ["blue"]}),+ )+ sns.publish(+ TopicArn=topic_arn, Message="red message",+ MessageAttributes={"color": {"DataType": "String", "StringValue": "red"}},+ )+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)+ assert len(msgs.get("Messages", [])) == 0, "Filtered message must not be delivered"+ sns.publish(+ TopicArn=topic_arn, Message="blue message",+ MessageAttributes={"color": {"DataType": "String", "StringValue": "blue"}},+ )+ msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)+ assert len(msgs2.get("Messages", [])) == 1+ body = json.loads(msgs2["Messages"][0]["Body"])+ assert body["Message"] == "blue message"+++def test_sns_raw_message_delivery(sns, sqs):+ """RawMessageDelivery=true delivers raw message body, not SNS envelope."""+ topic_arn = sns.create_topic(Name="qa-sns-raw")["TopicArn"]+ q_url = sqs.create_queue(QueueName="qa-sns-raw-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"]+ )["Attributes"]["QueueArn"]+ sub_arn = sns.subscribe(+ TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn+ )["SubscriptionArn"]+ sns.set_subscription_attributes(+ SubscriptionArn=sub_arn,+ AttributeName="RawMessageDelivery",+ AttributeValue="true",+ )+ sns.publish(TopicArn=topic_arn, Message="raw-body")+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)+ assert len(msgs["Messages"]) == 1+ assert msgs["Messages"][0]["Body"] == "raw-body"+++def test_sns_publish_batch_distinct_ids(sns):+ """PublishBatch with duplicate IDs must fail with BatchEntryIdsNotDistinct."""+ arn = sns.create_topic(Name="qa-sns-batch-dup")["TopicArn"]+ with pytest.raises(ClientError) as exc:+ sns.publish_batch(+ TopicArn=arn,+ PublishBatchRequestEntries=[+ {"Id": "same", "Message": "msg1"},+ {"Id": "same", "Message": "msg2"},+ ],+ )+ assert exc.value.response["Error"]["Code"] == "BatchEntryIdsNotDistinct"+++# ---------------------------------------------------------------------------+# LAMBDA — edge cases+# ---------------------------------------------------------------------------++def test_lambda_alias_crud(lam):+ """CreateAlias, GetAlias, UpdateAlias, DeleteAlias."""+ code = _zip_lambda("def handler(e,c): return {'v': 1}")+ lam.create_function(+ FunctionName="qa-lam-alias",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ lam.publish_version(FunctionName="qa-lam-alias")+ lam.create_alias(+ FunctionName="qa-lam-alias",+ Name="prod",+ FunctionVersion="1",+ Description="production alias",+ )+ alias = lam.get_alias(FunctionName="qa-lam-alias", Name="prod")+ assert alias["Name"] == "prod"+ assert alias["FunctionVersion"] == "1"+ lam.update_alias(FunctionName="qa-lam-alias", Name="prod", Description="updated")+ alias2 = lam.get_alias(FunctionName="qa-lam-alias", Name="prod")+ assert alias2["Description"] == "updated"+ aliases = lam.list_aliases(FunctionName="qa-lam-alias")["Aliases"]+ assert any(a["Name"] == "prod" for a in aliases)+ lam.delete_alias(FunctionName="qa-lam-alias", Name="prod")+ aliases2 = lam.list_aliases(FunctionName="qa-lam-alias")["Aliases"]+ assert not any(a["Name"] == "prod" for a in aliases2)+++def test_lambda_publish_version(lam):+ """PublishVersion creates a numbered version snapshot."""+ code = _zip_lambda("def handler(e,c): return 'v1'")+ lam.create_function(+ FunctionName="qa-lam-version",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ ver = lam.publish_version(FunctionName="qa-lam-version")+ assert ver["Version"] == "1"+ versions = lam.list_versions_by_function(FunctionName="qa-lam-version")["Versions"]+ version_nums = [v["Version"] for v in versions]+ assert "1" in version_nums+ assert "$LATEST" in version_nums+++def test_lambda_function_concurrency(lam):+ """PutFunctionConcurrency / GetFunctionConcurrency / DeleteFunctionConcurrency."""+ code = _zip_lambda("def handler(e,c): return {}")+ lam.create_function(+ FunctionName="qa-lam-concurrency",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ lam.put_function_concurrency(+ FunctionName="qa-lam-concurrency",+ ReservedConcurrentExecutions=5,+ )+ resp = lam.get_function_concurrency(FunctionName="qa-lam-concurrency")+ assert resp["ReservedConcurrentExecutions"] == 5+ lam.delete_function_concurrency(FunctionName="qa-lam-concurrency")+ resp2 = lam.get_function_concurrency(FunctionName="qa-lam-concurrency")+ assert resp2.get("ReservedConcurrentExecutions") is None+++def test_lambda_add_remove_permission(lam):+ """AddPermission / RemovePermission / GetPolicy."""+ code = _zip_lambda("def handler(e,c): return {}")+ lam.create_function(+ FunctionName="qa-lam-policy",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ lam.add_permission(+ FunctionName="qa-lam-policy",+ StatementId="allow-s3",+ Action="lambda:InvokeFunction",+ Principal="s3.amazonaws.com",+ )+ policy = json.loads(lam.get_policy(FunctionName="qa-lam-policy")["Policy"])+ assert any(s["Sid"] == "allow-s3" for s in policy["Statement"])+ lam.remove_permission(FunctionName="qa-lam-policy", StatementId="allow-s3")+ policy2 = json.loads(lam.get_policy(FunctionName="qa-lam-policy")["Policy"])+ assert not any(s["Sid"] == "allow-s3" for s in policy2["Statement"])+++def test_lambda_list_functions_pagination(lam):+ """ListFunctions pagination with Marker works correctly."""+ for i in range(5):+ code = _zip_lambda("def handler(e,c): return {}")+ try:+ lam.create_function(+ FunctionName=f"qa-lam-page-{i}",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ except ClientError:+ pass+ resp1 = lam.list_functions(MaxItems=2)+ assert len(resp1["Functions"]) <= 2+ if "NextMarker" in resp1:+ resp2 = lam.list_functions(MaxItems=2, Marker=resp1["NextMarker"])+ names1 = {f["FunctionName"] for f in resp1["Functions"]}+ names2 = {f["FunctionName"] for f in resp2["Functions"]}+ assert not names1 & names2+++def test_lambda_invoke_event_type_returns_202(lam):+ """Invoke with InvocationType=Event returns 202 immediately."""+ code = _zip_lambda("def handler(e,c): return {}")+ try:+ lam.create_function(+ FunctionName="qa-lam-event-invoke",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ except ClientError:+ pass+ resp = lam.invoke(+ FunctionName="qa-lam-event-invoke",+ InvocationType="Event",+ Payload=json.dumps({}),+ )+ assert resp["StatusCode"] == 202+++def test_lambda_invoke_dry_run_returns_204(lam):+ """Invoke with InvocationType=DryRun returns 204."""+ code = _zip_lambda("def handler(e,c): return {}")+ try:+ lam.create_function(+ FunctionName="qa-lam-dryrun",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler",+ Code={"ZipFile": code},+ )+ except ClientError:+ pass+ resp = lam.invoke(+ FunctionName="qa-lam-dryrun",+ InvocationType="DryRun",+ Payload=json.dumps({}),+ )+ assert resp["StatusCode"] == 204+++# ---------------------------------------------------------------------------+# IAM — edge cases+# ---------------------------------------------------------------------------++def test_iam_policy_version_crud(iam):+ """CreatePolicyVersion, GetPolicyVersion, ListPolicyVersions, DeletePolicyVersion."""+ doc1 = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})+ doc2 = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "sqs:*", "Resource": "*"}]})+ arn = iam.create_policy(PolicyName="qa-iam-versions", PolicyDocument=doc1)["Policy"]["Arn"]+ iam.create_policy_version(PolicyArn=arn, PolicyDocument=doc2, SetAsDefault=True)+ versions = iam.list_policy_versions(PolicyArn=arn)["Versions"]+ assert len(versions) == 2+ default = next(v for v in versions if v["IsDefaultVersion"])+ assert default["VersionId"] == "v2"+ v1 = iam.get_policy_version(PolicyArn=arn, VersionId="v1")["PolicyVersion"]+ assert v1["IsDefaultVersion"] is False+ iam.delete_policy_version(PolicyArn=arn, VersionId="v1")+ versions2 = iam.list_policy_versions(PolicyArn=arn)["Versions"]+ assert len(versions2) == 1+++def test_iam_inline_user_policy(iam):+ """PutUserPolicy / GetUserPolicy / ListUserPolicies / DeleteUserPolicy."""+ iam.create_user(UserName="qa-iam-inline-user")+ doc = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]})+ iam.put_user_policy(UserName="qa-iam-inline-user", PolicyName="qa-inline", PolicyDocument=doc)+ policies = iam.list_user_policies(UserName="qa-iam-inline-user")["PolicyNames"]+ assert "qa-inline" in policies+ got = iam.get_user_policy(UserName="qa-iam-inline-user", PolicyName="qa-inline")+ # boto3 deserialises PolicyDocument as a dict+ assert "s3:GetObject" in json.dumps(got["PolicyDocument"])+ iam.delete_user_policy(UserName="qa-iam-inline-user", PolicyName="qa-inline")+ policies2 = iam.list_user_policies(UserName="qa-iam-inline-user")["PolicyNames"]+ assert "qa-inline" not in policies2+++def test_iam_instance_profile_crud(iam):+ """CreateInstanceProfile, AddRoleToInstanceProfile, GetInstanceProfile, ListInstanceProfiles."""+ iam.create_role(+ RoleName="qa-iam-ip-role",+ AssumeRolePolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": []}),+ )+ iam.create_instance_profile(InstanceProfileName="qa-iam-ip")+ iam.add_role_to_instance_profile(InstanceProfileName="qa-iam-ip", RoleName="qa-iam-ip-role")+ ip = iam.get_instance_profile(InstanceProfileName="qa-iam-ip")["InstanceProfile"]+ assert ip["InstanceProfileName"] == "qa-iam-ip"+ assert any(r["RoleName"] == "qa-iam-ip-role" for r in ip["Roles"])+ profiles = iam.list_instance_profiles()["InstanceProfiles"]+ assert any(p["InstanceProfileName"] == "qa-iam-ip" for p in profiles)+ iam.remove_role_from_instance_profile(InstanceProfileName="qa-iam-ip", RoleName="qa-iam-ip-role")+ iam.delete_instance_profile(InstanceProfileName="qa-iam-ip")+++def test_iam_attach_detach_user_policy(iam):+ """AttachUserPolicy / DetachUserPolicy / ListAttachedUserPolicies."""+ iam.create_user(UserName="qa-iam-attach-user")+ doc = json.dumps({"Version": "2012-10-17", "Statement": []})+ policy_arn = iam.create_policy(PolicyName="qa-iam-attach-pol", PolicyDocument=doc)["Policy"]["Arn"]+ iam.attach_user_policy(UserName="qa-iam-attach-user", PolicyArn=policy_arn)+ attached = iam.list_attached_user_policies(UserName="qa-iam-attach-user")["AttachedPolicies"]+ assert any(p["PolicyArn"] == policy_arn for p in attached)+ iam.detach_user_policy(UserName="qa-iam-attach-user", PolicyArn=policy_arn)+ attached2 = iam.list_attached_user_policies(UserName="qa-iam-attach-user")["AttachedPolicies"]+ assert not any(p["PolicyArn"] == policy_arn for p in attached2)+++# ---------------------------------------------------------------------------+# SECRETS MANAGER — edge cases+# ---------------------------------------------------------------------------++def test_sm_put_secret_value_stages(sm):+ """PutSecretValue stages manage AWSCURRENT/AWSPREVIOUS correctly."""+ sm.create_secret(Name="qa-sm-stages", SecretString="v1")+ sm.put_secret_value(SecretId="qa-sm-stages", SecretString="v2")+ sm.put_secret_value(SecretId="qa-sm-stages", SecretString="v3")+ current = sm.get_secret_value(SecretId="qa-sm-stages", VersionStage="AWSCURRENT")+ assert current["SecretString"] == "v3"+ previous = sm.get_secret_value(SecretId="qa-sm-stages", VersionStage="AWSPREVIOUS")+ assert previous["SecretString"] == "v2"+++def test_sm_list_secret_version_ids(sm):+ """ListSecretVersionIds returns all versions."""+ sm.create_secret(Name="qa-sm-versions", SecretString="initial")+ sm.put_secret_value(SecretId="qa-sm-versions", SecretString="second")+ resp = sm.list_secret_version_ids(SecretId="qa-sm-versions")+ assert len(resp["Versions"]) >= 2+++def test_sm_delete_and_restore(sm):+ """DeleteSecret schedules deletion; RestoreSecret cancels it."""+ sm.create_secret(Name="qa-sm-restore", SecretString="data")+ sm.delete_secret(SecretId="qa-sm-restore", RecoveryWindowInDays=7)+ with pytest.raises(ClientError) as exc:+ sm.get_secret_value(SecretId="qa-sm-restore")+ assert exc.value.response["Error"]["Code"] == "InvalidRequestException"+ sm.restore_secret(SecretId="qa-sm-restore")+ val = sm.get_secret_value(SecretId="qa-sm-restore")+ assert val["SecretString"] == "data"+++def test_sm_get_random_password(sm):+ """GetRandomPassword returns a password of the requested length."""+ resp = sm.get_random_password(PasswordLength=24, ExcludeNumbers=True)+ pwd = resp["RandomPassword"]+ assert len(pwd) == 24+ assert not any(c.isdigit() for c in pwd)+++# ---------------------------------------------------------------------------+# SSM — edge cases+# ---------------------------------------------------------------------------++def test_ssm_get_parameter_history(ssm):+ """GetParameterHistory returns all versions of a parameter."""+ ssm.put_parameter(Name="/qa/ssm/hist", Value="v1", Type="String")+ ssm.put_parameter(Name="/qa/ssm/hist", Value="v2", Type="String", Overwrite=True)+ ssm.put_parameter(Name="/qa/ssm/hist", Value="v3", Type="String", Overwrite=True)+ history = ssm.get_parameter_history(Name="/qa/ssm/hist")["Parameters"]+ assert len(history) == 3+ values = [h["Value"] for h in history]+ assert "v1" in values and "v2" in values and "v3" in values+++def test_ssm_describe_parameters_filter(ssm):+ """DescribeParameters with ParameterFilters filters by path prefix."""+ ssm.put_parameter(Name="/qa/ssm/filter/a", Value="1", Type="String")+ ssm.put_parameter(Name="/qa/ssm/filter/b", Value="2", Type="String")+ ssm.put_parameter(Name="/qa/ssm/other/c", Value="3", Type="String")+ resp = ssm.describe_parameters(+ ParameterFilters=[{"Key": "Path", "Values": ["/qa/ssm/filter"]}]+ )+ names = [p["Name"] for p in resp["Parameters"]]+ assert "/qa/ssm/filter/a" in names+ assert "/qa/ssm/filter/b" in names+ assert "/qa/ssm/other/c" not in names+++def test_ssm_secure_string_not_decrypted_by_default(ssm):+ """SecureString value is not returned in plaintext without WithDecryption=True."""+ ssm.put_parameter(Name="/qa/ssm/secure", Value="mysecret", Type="SecureString")+ resp = ssm.get_parameter(Name="/qa/ssm/secure", WithDecryption=False)+ assert resp["Parameter"]["Value"] != "mysecret"+ resp2 = ssm.get_parameter(Name="/qa/ssm/secure", WithDecryption=True)+ assert resp2["Parameter"]["Value"] == "mysecret"+++# ---------------------------------------------------------------------------+# EVENTBRIDGE — edge cases+# ---------------------------------------------------------------------------++def test_eb_content_filter_prefix(eb, sqs):+ """EventBridge prefix content filter matches events correctly."""+ bus_name = "qa-eb-prefix-bus"+ eb.create_event_bus(Name=bus_name)+ q_url = sqs.create_queue(QueueName="qa-eb-prefix-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ eb.put_rule(+ Name="qa-eb-prefix-rule", EventBusName=bus_name,+ EventPattern=json.dumps({"source": ["myapp"], "detail": {"env": [{"prefix": "prod"}]}}),+ State="ENABLED",+ )+ eb.put_targets(Rule="qa-eb-prefix-rule", EventBusName=bus_name,+ Targets=[{"Id": "t1", "Arn": q_arn}])+ eb.put_events(Entries=[{+ "Source": "myapp", "DetailType": "test",+ "Detail": json.dumps({"env": "production"}), "EventBusName": bus_name,+ }])+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)+ assert len(msgs.get("Messages", [])) == 1+ eb.put_events(Entries=[{+ "Source": "myapp", "DetailType": "test",+ "Detail": json.dumps({"env": "staging"}), "EventBusName": bus_name,+ }])+ msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)+ assert len(msgs2.get("Messages", [])) == 0+++def test_eb_anything_but_filter(eb, sqs):+ """EventBridge anything-but filter excludes specified values."""+ bus_name = "qa-eb-anybut-bus"+ eb.create_event_bus(Name=bus_name)+ q_url = sqs.create_queue(QueueName="qa-eb-anybut-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ eb.put_rule(+ Name="qa-eb-anybut-rule", EventBusName=bus_name,+ EventPattern=json.dumps({"source": ["myapp"], "detail": {"status": [{"anything-but": ["error", "failed"]}]}}),+ State="ENABLED",+ )+ eb.put_targets(Rule="qa-eb-anybut-rule", EventBusName=bus_name,+ Targets=[{"Id": "t1", "Arn": q_arn}])+ eb.put_events(Entries=[{+ "Source": "myapp", "DetailType": "t",+ "Detail": json.dumps({"status": "success"}), "EventBusName": bus_name,+ }])+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)+ assert len(msgs.get("Messages", [])) == 1+ eb.put_events(Entries=[{+ "Source": "myapp", "DetailType": "t",+ "Detail": json.dumps({"status": "error"}), "EventBusName": bus_name,+ }])+ msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)+ assert len(msgs2.get("Messages", [])) == 0+++def test_eb_input_transformer(eb, sqs):+ """InputTransformer rewrites event payload before delivery."""+ bus_name = "qa-eb-transform-bus"+ eb.create_event_bus(Name=bus_name)+ q_url = sqs.create_queue(QueueName="qa-eb-transform-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ eb.put_rule(+ Name="qa-eb-transform-rule", EventBusName=bus_name,+ EventPattern=json.dumps({"source": ["myapp"]}), State="ENABLED",+ )+ eb.put_targets(+ Rule="qa-eb-transform-rule", EventBusName=bus_name,+ Targets=[{"Id": "t1", "Arn": q_arn, "InputTransformer": {+ "InputPathsMap": {"src": "$.source"},+ "InputTemplate": '{"transformed": "<src>"}',+ }}],+ )+ eb.put_events(Entries=[{+ "Source": "myapp", "DetailType": "t", "Detail": "{}", "EventBusName": bus_name,+ }])+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)+ assert len(msgs.get("Messages", [])) == 1+ body = json.loads(msgs["Messages"][0]["Body"])+ assert body.get("transformed") == "myapp"+++# ---------------------------------------------------------------------------+# KINESIS — edge cases+# ---------------------------------------------------------------------------++def test_kinesis_at_timestamp_iterator(kin):+ """AT_TIMESTAMP shard iterator returns records after the given timestamp."""+ kin.create_stream(StreamName="qa-kin-ts", ShardCount=1)+ time.sleep(0.1)+ before = time.time()+ kin.put_record(StreamName="qa-kin-ts", Data=b"after-ts", PartitionKey="pk")+ shards = kin.describe_stream(StreamName="qa-kin-ts")["StreamDescription"]["Shards"]+ shard_id = shards[0]["ShardId"]+ it = kin.get_shard_iterator(+ StreamName="qa-kin-ts", ShardId=shard_id,+ ShardIteratorType="AT_TIMESTAMP", Timestamp=before,+ )["ShardIterator"]+ records = kin.get_records(ShardIterator=it, Limit=10)["Records"]+ assert len(records) >= 1+ assert any(r["Data"] == b"after-ts" for r in records)+++def test_kinesis_retention_period(kin):+ """IncreaseStreamRetentionPeriod / DecreaseStreamRetentionPeriod."""+ kin.create_stream(StreamName="qa-kin-retention", ShardCount=1)+ kin.increase_stream_retention_period(StreamName="qa-kin-retention", RetentionPeriodHours=48)+ desc = kin.describe_stream(StreamName="qa-kin-retention")["StreamDescription"]+ assert desc["RetentionPeriodHours"] == 48+ kin.decrease_stream_retention_period(StreamName="qa-kin-retention", RetentionPeriodHours=24)+ desc2 = kin.describe_stream(StreamName="qa-kin-retention")["StreamDescription"]+ assert desc2["RetentionPeriodHours"] == 24+++def test_kinesis_stream_encryption(kin):+ """StartStreamEncryption / StopStreamEncryption."""+ kin.create_stream(StreamName="qa-kin-enc", ShardCount=1)+ kin.start_stream_encryption(+ StreamName="qa-kin-enc", EncryptionType="KMS", KeyId="alias/aws/kinesis",+ )+ desc = kin.describe_stream(StreamName="qa-kin-enc")["StreamDescription"]+ assert desc["EncryptionType"] == "KMS"+ kin.stop_stream_encryption(+ StreamName="qa-kin-enc", EncryptionType="KMS", KeyId="alias/aws/kinesis",+ )+ desc2 = kin.describe_stream(StreamName="qa-kin-enc")["StreamDescription"]+ assert desc2["EncryptionType"] == "NONE"+++# ---------------------------------------------------------------------------+# STEP FUNCTIONS — edge cases+# ---------------------------------------------------------------------------++def test_sfn_choice_state(sfn):+ """Choice state routes to correct branch based on input."""+ definition = json.dumps({+ "StartAt": "Check",+ "States": {+ "Check": {+ "Type": "Choice",+ "Choices": [+ {"Variable": "$.value", "NumericGreaterThan": 10, "Next": "High"},+ {"Variable": "$.value", "NumericLessThanEquals": 10, "Next": "Low"},+ ],+ },+ "High": {"Type": "Pass", "Result": {"result": "high"}, "End": True},+ "Low": {"Type": "Pass", "Result": {"result": "low"}, "End": True},+ },+ })+ arn = sfn.create_state_machine(+ name="qa-sfn-choice", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]+ exec_arn = sfn.start_execution(stateMachineArn=arn, input=json.dumps({"value": 15}))["executionArn"]+ time.sleep(0.5)+ desc = sfn.describe_execution(executionArn=exec_arn)+ assert desc["status"] == "SUCCEEDED"+ assert json.loads(desc["output"])["result"] == "high"+ exec_arn2 = sfn.start_execution(stateMachineArn=arn, input=json.dumps({"value": 5}))["executionArn"]+ time.sleep(0.5)+ desc2 = sfn.describe_execution(executionArn=exec_arn2)+ assert desc2["status"] == "SUCCEEDED"+ assert json.loads(desc2["output"])["result"] == "low"+++def test_sfn_pass_state_result(sfn):+ """Pass state with Result injects static data into output."""+ definition = json.dumps({+ "StartAt": "Inject",+ "States": {"Inject": {"Type": "Pass", "Result": {"injected": True, "count": 42}, "End": True}},+ })+ arn = sfn.create_state_machine(+ name="qa-sfn-pass-result", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]+ exec_arn = sfn.start_execution(stateMachineArn=arn, input="{}")["executionArn"]+ time.sleep(0.5)+ desc = sfn.describe_execution(executionArn=exec_arn)+ assert desc["status"] == "SUCCEEDED"+ output = json.loads(desc["output"])+ assert output["injected"] is True+ assert output["count"] == 42+++def test_sfn_fail_state(sfn):+ """Fail state transitions execution to FAILED."""+ definition = json.dumps({+ "StartAt": "Boom",+ "States": {"Boom": {"Type": "Fail", "Error": "CustomError", "Cause": "Something went wrong"}},+ })+ arn = sfn.create_state_machine(+ name="qa-sfn-fail", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]+ exec_arn = sfn.start_execution(stateMachineArn=arn, input="{}")["executionArn"]+ time.sleep(0.5)+ desc = sfn.describe_execution(executionArn=exec_arn)+ assert desc["status"] == "FAILED"+++def test_sfn_stop_execution(sfn):+ """StopExecution transitions a RUNNING execution to ABORTED."""+ definition = json.dumps({+ "StartAt": "Wait",+ "States": {"Wait": {"Type": "Wait", "Seconds": 60, "End": True}},+ })+ arn = sfn.create_state_machine(+ name="qa-sfn-stop", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]+ exec_arn = sfn.start_execution(stateMachineArn=arn, input="{}")["executionArn"]+ time.sleep(0.2)+ sfn.stop_execution(executionArn=exec_arn, cause="test stop")+ desc = sfn.describe_execution(executionArn=exec_arn)+ assert desc["status"] == "ABORTED"+++def test_sfn_list_executions_filter(sfn):+ """ListExecutions with statusFilter returns only matching executions."""+ definition = json.dumps({+ "StartAt": "Done",+ "States": {"Done": {"Type": "Succeed"}},+ })+ arn = sfn.create_state_machine(+ name="qa-sfn-list-filter", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/r",+ )["stateMachineArn"]+ sfn.start_execution(stateMachineArn=arn, input="{}")+ time.sleep(0.5)+ succeeded = sfn.list_executions(stateMachineArn=arn, statusFilter="SUCCEEDED")["executions"]+ assert all(e["status"] == "SUCCEEDED" for e in succeeded)+++# ---------------------------------------------------------------------------+# CLOUDWATCH — edge cases+# ---------------------------------------------------------------------------++def test_cw_get_metric_data_time_range(cw):+ """GetMetricData respects StartTime/EndTime filtering."""+ import datetime+ now = datetime.datetime.utcnow()+ past = now - datetime.timedelta(hours=2)+ cw.put_metric_data(+ Namespace="qa/cw",+ MetricData=[{"MetricName": "Requests", "Value": 100.0, "Unit": "Count"}],+ )+ resp = cw.get_metric_data(+ MetricDataQueries=[{"Id": "m1", "MetricStat": {+ "Metric": {"Namespace": "qa/cw", "MetricName": "Requests"},+ "Period": 60, "Stat": "Sum",+ }}],+ StartTime=past,+ EndTime=now + datetime.timedelta(minutes=5),+ )+ result = next((r for r in resp["MetricDataResults"] if r["Id"] == "m1"), None)+ assert result is not None+ assert result["StatusCode"] == "Complete"+ assert len(result["Values"]) >= 1+ assert sum(result["Values"]) >= 100.0+++def test_cw_alarm_state_transitions(cw):+ """SetAlarmState changes alarm state correctly."""+ cw.put_metric_alarm(+ AlarmName="qa-cw-state-alarm", MetricName="Errors", Namespace="qa/cw",+ Statistic="Sum", Period=60, EvaluationPeriods=1, Threshold=10.0,+ ComparisonOperator="GreaterThanThreshold",+ )+ cw.set_alarm_state(AlarmName="qa-cw-state-alarm", StateValue="ALARM", StateReason="Testing")+ alarms = cw.describe_alarms(AlarmNames=["qa-cw-state-alarm"])["MetricAlarms"]+ assert alarms[0]["StateValue"] == "ALARM"+ cw.set_alarm_state(AlarmName="qa-cw-state-alarm", StateValue="OK", StateReason="Resolved")+ alarms2 = cw.describe_alarms(AlarmNames=["qa-cw-state-alarm"])["MetricAlarms"]+ assert alarms2[0]["StateValue"] == "OK"+++def test_cw_list_metrics_namespace_filter(cw):+ """ListMetrics with Namespace filter returns only matching metrics."""+ cw.put_metric_data(Namespace="qa/ns-a", MetricData=[{"MetricName": "MetA", "Value": 1.0}])+ cw.put_metric_data(Namespace="qa/ns-b", MetricData=[{"MetricName": "MetB", "Value": 1.0}])+ resp = cw.list_metrics(Namespace="qa/ns-a")+ names = [m["MetricName"] for m in resp["Metrics"]]+ assert "MetA" in names+ assert "MetB" not in names+++def test_cw_put_metric_data_statistics_values(cw):+ """PutMetricData with Values/Counts array stores multiple data points."""+ cw.put_metric_data(+ Namespace="qa/cw-multi",+ MetricData=[{"MetricName": "Latency", "Values": [10.0, 20.0, 30.0],+ "Counts": [1.0, 2.0, 1.0], "Unit": "Milliseconds"}],+ )+ resp = cw.list_metrics(Namespace="qa/cw-multi")+ assert any(m["MetricName"] == "Latency" for m in resp["Metrics"])+++# ---------------------------------------------------------------------------+# CLOUDWATCH LOGS — edge cases+# ---------------------------------------------------------------------------++def test_logs_filter_with_wildcard(logs):+ """FilterLogEvents with wildcard pattern matches correctly."""+ logs.create_log_group(logGroupName="/qa/logs/wildcard")+ logs.create_log_stream(logGroupName="/qa/logs/wildcard", logStreamName="stream1")+ logs.put_log_events(+ logGroupName="/qa/logs/wildcard", logStreamName="stream1",+ logEvents=[+ {"timestamp": int(time.time() * 1000), "message": "ERROR: disk full"},+ {"timestamp": int(time.time() * 1000), "message": "INFO: all good"},+ {"timestamp": int(time.time() * 1000), "message": "ERROR: timeout"},+ ],+ )+ resp = logs.filter_log_events(logGroupName="/qa/logs/wildcard", filterPattern="ERROR*")+ messages = [e["message"] for e in resp["events"]]+ assert all("ERROR" in m for m in messages)+ assert len(messages) == 2+++def test_logs_describe_log_groups_prefix(logs):+ """DescribeLogGroups with logGroupNamePrefix filters correctly."""+ logs.create_log_group(logGroupName="/qa/logs/prefix/alpha")+ logs.create_log_group(logGroupName="/qa/logs/prefix/beta")+ logs.create_log_group(logGroupName="/qa/logs/other/gamma")+ resp = logs.describe_log_groups(logGroupNamePrefix="/qa/logs/prefix")+ names = [g["logGroupName"] for g in resp["logGroups"]]+ assert "/qa/logs/prefix/alpha" in names+ assert "/qa/logs/prefix/beta" in names+ assert "/qa/logs/other/gamma" not in names+++def test_logs_retention_policy_invalid_value(logs):+ """PutRetentionPolicy with invalid days raises InvalidParameterException."""+ logs.create_log_group(logGroupName="/qa/logs/retention-invalid")+ with pytest.raises(ClientError) as exc:+ logs.put_retention_policy(logGroupName="/qa/logs/retention-invalid", retentionInDays=999)+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+++# ---------------------------------------------------------------------------+# FIREHOSE — edge cases+# ---------------------------------------------------------------------------++def test_firehose_put_record_batch_failure_count(fh):+ """PutRecordBatch with valid records returns FailedPutCount=0."""+ fh.create_delivery_stream(+ DeliveryStreamName="qa-fh-batch-fail",+ ExtendedS3DestinationConfiguration={+ "BucketARN": "arn:aws:s3:::qa-fh-bucket",+ "RoleARN": "arn:aws:iam::000000000000:role/r",+ },+ )+ resp = fh.put_record_batch(+ DeliveryStreamName="qa-fh-batch-fail",+ Records=[{"Data": "aGVsbG8="}, {"Data": "d29ybGQ="}],+ )+ assert resp["FailedPutCount"] == 0+ assert len(resp["RequestResponses"]) == 2+++def test_firehose_update_destination_version_mismatch(fh):+ """UpdateDestination with wrong version raises ConcurrentModificationException."""+ fh.create_delivery_stream(+ DeliveryStreamName="qa-fh-version-check",+ ExtendedS3DestinationConfiguration={+ "BucketARN": "arn:aws:s3:::qa-fh-bucket2",+ "RoleARN": "arn:aws:iam::000000000000:role/r",+ },+ )+ desc = fh.describe_delivery_stream(DeliveryStreamName="qa-fh-version-check")+ dest_id = desc["DeliveryStreamDescription"]["Destinations"][0]["DestinationId"]+ with pytest.raises(ClientError) as exc:+ fh.update_destination(+ DeliveryStreamName="qa-fh-version-check",+ CurrentDeliveryStreamVersionId="999",+ DestinationId=dest_id,+ ExtendedS3DestinationUpdate={+ "BucketARN": "arn:aws:s3:::qa-fh-bucket2-updated",+ "RoleARN": "arn:aws:iam::000000000000:role/r",+ },+ )+ assert exc.value.response["Error"]["Code"] == "ConcurrentModificationException"+++# ---------------------------------------------------------------------------+# ROUTE53 — edge cases+# ---------------------------------------------------------------------------++def test_r53_delete_zone_with_records_fails(r53):+ """DeleteHostedZone fails if non-default records exist."""+ zone_id = r53.create_hosted_zone(+ Name="qa-r53-nonempty.com.",+ CallerReference=f"qa-nonempty-{int(time.time())}",+ )["HostedZone"]["Id"].split("/")[-1]+ r53.change_resource_record_sets(+ HostedZoneId=zone_id,+ ChangeBatch={"Changes": [{"Action": "CREATE", "ResourceRecordSet": {+ "Name": "www.qa-r53-nonempty.com.", "Type": "A", "TTL": 300,+ "ResourceRecords": [{"Value": "1.2.3.4"}],+ }}]},+ )+ with pytest.raises(ClientError) as exc:+ r53.delete_hosted_zone(Id=zone_id)+ assert exc.value.response["Error"]["Code"] == "HostedZoneNotEmpty"+++def test_r53_upsert_is_idempotent(r53):+ """UPSERT on existing record updates it without error."""+ zone_id = r53.create_hosted_zone(+ Name="qa-r53-upsert.com.",+ CallerReference=f"qa-upsert-{int(time.time())}",+ )["HostedZone"]["Id"].split("/")[-1]+ for ip in ["1.1.1.1", "2.2.2.2"]:+ r53.change_resource_record_sets(+ HostedZoneId=zone_id,+ ChangeBatch={"Changes": [{"Action": "UPSERT", "ResourceRecordSet": {+ "Name": "api.qa-r53-upsert.com.", "Type": "A", "TTL": 60,+ "ResourceRecords": [{"Value": ip}],+ }}]},+ )+ records = r53.list_resource_record_sets(HostedZoneId=zone_id)["ResourceRecordSets"]+ a_records = [r for r in records if r["Name"] == "api.qa-r53-upsert.com." and r["Type"] == "A"]+ assert len(a_records) == 1+ assert a_records[0]["ResourceRecords"][0]["Value"] == "2.2.2.2"+++def test_r53_create_record_duplicate_fails(r53):+ """CREATE on existing record raises InvalidChangeBatch."""+ zone_id = r53.create_hosted_zone(+ Name="qa-r53-dup.com.",+ CallerReference=f"qa-dup-{int(time.time())}",+ )["HostedZone"]["Id"].split("/")[-1]+ r53.change_resource_record_sets(+ HostedZoneId=zone_id,+ ChangeBatch={"Changes": [{"Action": "CREATE", "ResourceRecordSet": {+ "Name": "dup.qa-r53-dup.com.", "Type": "A", "TTL": 60,+ "ResourceRecords": [{"Value": "1.1.1.1"}],+ }}]},+ )+ with pytest.raises(ClientError) as exc:+ r53.change_resource_record_sets(+ HostedZoneId=zone_id,+ ChangeBatch={"Changes": [{"Action": "CREATE", "ResourceRecordSet": {+ "Name": "dup.qa-r53-dup.com.", "Type": "A", "TTL": 60,+ "ResourceRecords": [{"Value": "2.2.2.2"}],+ }}]},+ )+ assert exc.value.response["Error"]["Code"] == "InvalidChangeBatch"+++# ---------------------------------------------------------------------------+# API GATEWAY v2 — edge cases+# ---------------------------------------------------------------------------++def test_apigw_update_integration(apigw):+ """UpdateIntegration changes integrationUri."""+ api_id = apigw.create_api(Name="qa-apigw-update-integ", ProtocolType="HTTP")["ApiId"]+ integ_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:old-fn",+ )["IntegrationId"]+ apigw.update_integration(+ ApiId=api_id, IntegrationId=integ_id,+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:new-fn",+ )+ integ = apigw.get_integration(ApiId=api_id, IntegrationId=integ_id)+ assert "new-fn" in integ["IntegrationUri"]+++def test_apigw_delete_route(apigw):+ """DeleteRoute removes the route from GetRoutes."""+ api_id = apigw.create_api(Name="qa-apigw-del-route", ProtocolType="HTTP")["ApiId"]+ route_id = apigw.create_route(ApiId=api_id, RouteKey="GET /qa")["RouteId"]+ apigw.delete_route(ApiId=api_id, RouteId=route_id)+ routes = apigw.get_routes(ApiId=api_id)["Items"]+ assert not any(r["RouteId"] == route_id for r in routes)+++def test_apigw_stage_variables(apigw):+ """CreateStage with stageVariables stores and returns them."""+ api_id = apigw.create_api(Name="qa-apigw-stage-vars", ProtocolType="HTTP")["ApiId"]+ apigw.create_stage(+ ApiId=api_id, StageName="dev",+ StageVariables={"env": "development", "version": "1"},+ )+ stage = apigw.get_stage(ApiId=api_id, StageName="dev")+ assert stage["StageVariables"]["env"] == "development"+ assert stage["StageVariables"]["version"] == "1"+++# ---------------------------------------------------------------------------+# API GATEWAY v1 — edge cases+# ---------------------------------------------------------------------------++def test_apigwv1_usage_plan_key_crud(apigw_v1):+ """CreateUsagePlanKey / GetUsagePlanKeys / DeleteUsagePlanKey."""+ api_key = apigw_v1.create_api_key(name="qa-v1-key", enabled=True)+ key_id = api_key["id"]+ plan = apigw_v1.create_usage_plan(+ name="qa-v1-plan", throttle={"rateLimit": 100, "burstLimit": 200},+ )+ plan_id = plan["id"]+ apigw_v1.create_usage_plan_key(usagePlanId=plan_id, keyId=key_id, keyType="API_KEY")+ keys = apigw_v1.get_usage_plan_keys(usagePlanId=plan_id)["items"]+ assert any(k["id"] == key_id for k in keys)+ apigw_v1.delete_usage_plan_key(usagePlanId=plan_id, keyId=key_id)+ keys2 = apigw_v1.get_usage_plan_keys(usagePlanId=plan_id)["items"]+ assert not any(k["id"] == key_id for k in keys2)+++# ---------------------------------------------------------------------------+# GLUE — edge cases+# ---------------------------------------------------------------------------++def test_glue_partition_crud(glue):+ """CreatePartition / GetPartition / GetPartitions / DeletePartition."""+ glue.create_database(DatabaseInput={"Name": "qa-glue-partdb"})+ glue.create_table(+ DatabaseName="qa-glue-partdb",+ TableInput={+ "Name": "qa-glue-parttbl",+ "StorageDescriptor": {"Columns": [], "Location": "s3://bucket/key",+ "InputFormat": "", "OutputFormat": "", "SerdeInfo": {}},+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ },+ )+ glue.create_partition(+ DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl",+ PartitionInput={+ "Values": ["2024-01-01"],+ "StorageDescriptor": {"Columns": [], "Location": "s3://bucket/key/dt=2024-01-01",+ "InputFormat": "", "OutputFormat": "", "SerdeInfo": {}},+ },+ )+ part = glue.get_partition(+ DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl",+ PartitionValues=["2024-01-01"],+ )["Partition"]+ assert part["Values"] == ["2024-01-01"]+ parts = glue.get_partitions(DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl")["Partitions"]+ assert len(parts) == 1+ glue.delete_partition(+ DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl",+ PartitionValues=["2024-01-01"],+ )+ parts2 = glue.get_partitions(DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl")["Partitions"]+ assert len(parts2) == 0+++def test_glue_duplicate_partition_error(glue):+ """CreatePartition with duplicate values raises AlreadyExistsException."""+ glue.create_database(DatabaseInput={"Name": "qa-glue-duppartdb"})+ glue.create_table(+ DatabaseName="qa-glue-duppartdb",+ TableInput={+ "Name": "qa-glue-dupparttbl",+ "StorageDescriptor": {"Columns": [], "Location": "s3://b/k",+ "InputFormat": "", "OutputFormat": "", "SerdeInfo": {}},+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ },+ )+ part_input = {+ "Values": ["2024-01-01"],+ "StorageDescriptor": {"Columns": [], "Location": "s3://b/k/dt=2024-01-01",+ "InputFormat": "", "OutputFormat": "", "SerdeInfo": {}},+ }+ glue.create_partition(DatabaseName="qa-glue-duppartdb", TableName="qa-glue-dupparttbl",+ PartitionInput=part_input)+ with pytest.raises(ClientError) as exc:+ glue.create_partition(DatabaseName="qa-glue-duppartdb", TableName="qa-glue-dupparttbl",+ PartitionInput=part_input)+ assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"+++# ---------------------------------------------------------------------------+# ATHENA — edge cases+# ---------------------------------------------------------------------------++def test_athena_stop_query(athena):+ """StopQueryExecution cancels a running query."""+ resp = athena.start_query_execution(+ QueryString="SELECT 1",+ ResultConfiguration={"OutputLocation": "s3://qa-athena-results/"},+ )+ qid = resp["QueryExecutionId"]+ athena.stop_query_execution(QueryExecutionId=qid)+ desc = athena.get_query_execution(QueryExecutionId=qid)["QueryExecution"]+ assert desc["Status"]["State"] in ("CANCELLED", "SUCCEEDED")+++def test_athena_prepared_statement_crud(athena):+ """CreatePreparedStatement / GetPreparedStatement / DeletePreparedStatement."""+ athena.create_prepared_statement(+ StatementName="qa-athena-stmt", WorkGroup="primary",+ QueryStatement="SELECT * FROM tbl WHERE id = ?",+ Description="test stmt",+ )+ stmt = athena.get_prepared_statement(StatementName="qa-athena-stmt", WorkGroup="primary")["PreparedStatement"]+ assert stmt["StatementName"] == "qa-athena-stmt"+ assert "SELECT" in stmt["QueryStatement"]+ stmts = athena.list_prepared_statements(WorkGroup="primary")["PreparedStatements"]+ assert any(s["StatementName"] == "qa-athena-stmt" for s in stmts)+ athena.delete_prepared_statement(StatementName="qa-athena-stmt", WorkGroup="primary")+ stmts2 = athena.list_prepared_statements(WorkGroup="primary")["PreparedStatements"]+ assert not any(s["StatementName"] == "qa-athena-stmt" for s in stmts2)+++def test_athena_data_catalog_crud(athena):+ """CreateDataCatalog / GetDataCatalog / ListDataCatalogs / DeleteDataCatalog."""+ athena.create_data_catalog(Name="qa-athena-catalog", Type="HIVE", Description="test catalog")+ catalog = athena.get_data_catalog(Name="qa-athena-catalog")["DataCatalog"]+ assert catalog["Name"] == "qa-athena-catalog"+ assert catalog["Type"] == "HIVE"+ catalogs = athena.list_data_catalogs()["DataCatalogsSummary"]+ assert any(c["CatalogName"] == "qa-athena-catalog" for c in catalogs)+ athena.delete_data_catalog(Name="qa-athena-catalog")+ catalogs2 = athena.list_data_catalogs()["DataCatalogsSummary"]+ assert not any(c["CatalogName"] == "qa-athena-catalog" for c in catalogs2)+++# ---------------------------------------------------------------------------+# RDS — edge cases+# ---------------------------------------------------------------------------++def test_rds_snapshot_crud(rds):+ """CreateDBSnapshot / DescribeDBSnapshots / DeleteDBSnapshot."""+ rds.create_db_instance(+ DBInstanceIdentifier="qa-rds-snap-db", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="password",+ AllocatedStorage=20,+ )+ try:+ rds.create_db_snapshot(DBSnapshotIdentifier="qa-rds-snap-1", DBInstanceIdentifier="qa-rds-snap-db")+ snaps = rds.describe_db_snapshots(DBSnapshotIdentifier="qa-rds-snap-1")["DBSnapshots"]+ assert len(snaps) == 1+ assert snaps[0]["DBSnapshotIdentifier"] == "qa-rds-snap-1"+ assert snaps[0]["Status"] == "available"+ rds.delete_db_snapshot(DBSnapshotIdentifier="qa-rds-snap-1")+ snaps2 = rds.describe_db_snapshots()["DBSnapshots"]+ assert not any(s["DBSnapshotIdentifier"] == "qa-rds-snap-1" for s in snaps2)+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="qa-rds-snap-db", SkipFinalSnapshot=True)+++def test_rds_deletion_protection(rds):+ """DeleteDBInstance fails when DeletionProtection=True."""+ rds.create_db_instance(+ DBInstanceIdentifier="qa-rds-protected", DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin", MasterUserPassword="password",+ AllocatedStorage=20, DeletionProtection=True,+ )+ try:+ with pytest.raises(ClientError) as exc:+ rds.delete_db_instance(DBInstanceIdentifier="qa-rds-protected")+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"+ finally:+ rds.modify_db_instance(DBInstanceIdentifier="qa-rds-protected", DeletionProtection=False, ApplyImmediately=True)+ rds.delete_db_instance(DBInstanceIdentifier="qa-rds-protected", SkipFinalSnapshot=True)+++# ---------------------------------------------------------------------------+# ELASTICACHE — edge cases+# ---------------------------------------------------------------------------++def test_ec_describe_cache_parameters(ec):+ """DescribeCacheParameters returns parameters for a parameter group."""+ ec.create_cache_parameter_group(+ CacheParameterGroupName="qa-ec-params",+ CacheParameterGroupFamily="redis7.0",+ Description="test",+ )+ resp = ec.describe_cache_parameters(CacheParameterGroupName="qa-ec-params")+ assert "Parameters" in resp+ assert len(resp["Parameters"]) > 0+++def test_ec_modify_cache_parameter_group(ec):+ """ModifyCacheParameterGroup updates parameter values."""+ ec.create_cache_parameter_group(+ CacheParameterGroupName="qa-ec-modify-params",+ CacheParameterGroupFamily="redis7.0",+ Description="test",+ )+ ec.modify_cache_parameter_group(+ CacheParameterGroupName="qa-ec-modify-params",+ ParameterNameValues=[{"ParameterName": "maxmemory-policy", "ParameterValue": "allkeys-lru"}],+ )+ params = ec.describe_cache_parameters(CacheParameterGroupName="qa-ec-modify-params")["Parameters"]+ maxmem = next((p for p in params if p["ParameterName"] == "maxmemory-policy"), None)+ assert maxmem is not None+ assert maxmem["ParameterValue"] == "allkeys-lru"+++# ---------------------------------------------------------------------------+# SES — edge cases+# ---------------------------------------------------------------------------++def test_ses_send_templated_email(ses):+ """SendTemplatedEmail renders template and stores email."""+ ses.verify_email_identity(EmailAddress="[email protected]")+ ses.create_template(Template={+ "TemplateName": "qa-ses-tmpl",+ "SubjectPart": "Hello {{name}}",+ "TextPart": "Hi {{name}}, welcome!",+ "HtmlPart": "<p>Hi {{name}}</p>",+ })+ resp = ses.send_templated_email(+ Source="[email protected]",+ Destination={"ToAddresses": ["[email protected]"]},+ Template="qa-ses-tmpl",+ TemplateData=json.dumps({"name": "Alice"}),+ )+ assert "MessageId" in resp+++def test_ses_verify_domain(ses):+ """VerifyDomainIdentity returns a verification token."""+ resp = ses.verify_domain_identity(Domain="example.com")+ assert "VerificationToken" in resp+ assert len(resp["VerificationToken"]) > 0+ identities = ses.list_identities(IdentityType="Domain")["Identities"]+ assert "example.com" in identities+++def test_ses_configuration_set_crud(ses):+ """CreateConfigurationSet / DescribeConfigurationSet / DeleteConfigurationSet."""+ ses.create_configuration_set(ConfigurationSet={"Name": "qa-ses-config"})+ desc = ses.describe_configuration_set(ConfigurationSetName="qa-ses-config")+ assert desc["ConfigurationSet"]["Name"] == "qa-ses-config"+ sets = ses.list_configuration_sets()["ConfigurationSets"]+ assert any(s["Name"] == "qa-ses-config" for s in sets)+ ses.delete_configuration_set(ConfigurationSetName="qa-ses-config")+ sets2 = ses.list_configuration_sets()["ConfigurationSets"]+ assert not any(s["Name"] == "qa-ses-config" for s in sets2)