Skip to content

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

Feat/cognito totp mfa v1.1.8 (#39)

Nahuel Nucera35a0cc86ee87
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b358c4a..55c156ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.8] — 2026-03-30
+
+### Added
+- **Cognito TOTP MFA** — full end-to-end Software Token MFA flow now works with CDK and boto3
+ - `AssociateSoftwareToken` returns a stub TOTP secret + session (accepts `AccessToken` or `Session`)
+ - `VerifySoftwareToken` accepts any code and marks the user as TOTP-enrolled (`_mfa_enabled`, `_preferred_mfa`)
+ - `AdminSetUserMFAPreference` — new: enables/disables TOTP or SMS MFA per user and sets preferred method
+ - `SetUserMFAPreference` — new: public (AccessToken-based) equivalent of the above
+ - `AdminInitiateAuth` / `InitiateAuth` now issue `SOFTWARE_TOKEN_MFA` challenge after password auth when pool `MfaConfiguration` is `ON` or `OPTIONAL` and user has TOTP enrolled
+ - `AdminRespondToAuthChallenge` / `RespondToAuthChallenge` accept any TOTP code for `SOFTWARE_TOKEN_MFA` and return tokens (emulator — no real TOTP validation)
+ - `AdminGetUser` / `GetUser` now return real `UserMFASettingList` and `PreferredMfaSetting` fields
+ - `MFA_SETUP` challenge handled in both respond endpoints (for pool `ON` + unenrolled users)
+
+### Tests
+- 4 new integration tests: full TOTP flow, OPTIONAL MFA, AdminGetUser MFA fields, SetUserMFAPreference via token — 714 tests total, all passing
+
+---
+
## [1.1.7] — 2026-03-30
### Added
diff --git a/README.md b/README.md
index fe04e736..6dde5dc6 100644
--- a/README.md
+++ b/README.md
@@ -237,7 +237,7 @@ subnet = ec2.create_subnet(
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
-| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, 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 |
+| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
---
@@ -467,20 +467,20 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (708 tests across all 30 services)
+# Run the full test suite (714 tests across all 30 services)
pytest tests/ -v
```
Expected output:
```
-collected 694 items
+collected 714 items
tests/test_services.py::test_s3_create_bucket PASSED
...
tests/test_services.py::test_app_asgi_callable PASSED
-694 passed in ~60s
+714 passed in ~60s
```
---
diff --git a/ministack/app.py b/ministack/app.py
index ee19ec25..5a63e576 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -5,13 +5,13 @@ Routes requests to service handlers based on AWS headers, paths, and query param
Compatible with AWS CLI, boto3, and any AWS SDK via --endpoint-url.
"""
-import os
-import re
-import json
-import uuid
import asyncio
+import json
import logging
+import os
+import re
import subprocess
+import uuid
from urllib.parse import parse_qs, urlparse
# Matches host headers like "{apiId}.execute-api.localhost" or "{apiId}.execute-api.localhost:4566"
@@ -23,20 +23,37 @@ _EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\.localhost(?::\d+)?$"
_S3_VHOST_RE = re.compile(r"^([^.]+)(?:\.s3)?\.localhost(?::\d+)?$")
_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache)\.")
-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 alb
-from ministack.services import ec2
-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 import emr
-from ministack.services import efs
+from ministack.core.persistence import PERSIST_STATE, load_state, save_all
+from ministack.core.router import detect_service, extract_account_id, extract_region
+from ministack.services import (
+ alb,
+ apigateway,
+ apigateway_v1,
+ athena,
+ cloudwatch,
+ cloudwatch_logs,
+ cognito,
+ dynamodb,
+ ec2,
+ ecs,
+ efs,
+ elasticache,
+ emr,
+ eventbridge,
+ firehose,
+ glue,
+ kinesis,
+ lambda_svc,
+ rds,
+ route53,
+ s3,
+ secretsmanager,
+ ses,
+ sns,
+ sqs,
+ ssm,
+ stepfunctions,
+)
from ministack.services.iam_sts import handle_iam_request, handle_sts_request
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
@@ -422,9 +439,11 @@ 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 ministack.core.persistence import PERSIST_STATE, STATE_DIR
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_PERSIST
+ from ministack.services.s3 import DATA_DIR as S3_DATA_DIR
+ from ministack.services.s3 import PERSIST as S3_PERSIST
for mod, fn in [
(s3, s3.reset), (sqs, sqs.reset), (sns, sns.reset),
@@ -480,8 +499,9 @@ def _reset_all_state():
def main():
- import uvicorn
import socket
+
+ import uvicorn
port = int(_resolve_port())
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(("127.0.0.1", port)) == 0:
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index b7a444d1..f20d7e52 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -4,16 +4,16 @@ Each function gets a persistent Python worker process that imports the handler
once (cold start) and then handles subsequent invocations without re-importing (warm).
"""
+import base64
+import json
+import logging
import os
+import subprocess
import sys
-import json
-import time
-import base64
-import zipfile
import tempfile
import threading
-import subprocess
-import logging
+import time
+import zipfile
logger = logging.getLogger("lambda_runtime")
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index d55b8dea..66ebcb67 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -4,9 +4,9 @@ When PERSIST_STATE=1, service state is saved to STATE_DIR on shutdown
and reloaded on startup.
"""
-import os
import json
import logging
+import os
import tempfile
logger = logging.getLogger("persistence")
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index f775c733..0d08057b 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -4,9 +4,9 @@ Handles XML responses (S3, SQS, SNS, IAM, STS, CloudWatch) and
JSON responses (DynamoDB, Lambda, SecretsManager, CloudWatch Logs).
"""
+import hashlib
import json
import uuid
-import hashlib
from datetime import datetime, timezone
from xml.etree.ElementTree import Element, SubElement, tostring
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 5cf3b1c9..a1b8ba8b 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -7,8 +7,8 @@ Routes incoming requests to the correct service handler based on:
- URL path patterns (e.g., /2015-03-31/functions for Lambda)
"""
-import re
import logging
+import re
logger = logging.getLogger("localstack-clone")
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 2d4e108a..b5a68074 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -18,11 +18,11 @@ Supports:
import base64
import fnmatch
import json
+import logging
import os
import random
import string
import time
-import logging
from urllib.parse import parse_qs
from ministack.core.responses import new_uuid
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index bc672e55..d78bdcbb 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -41,11 +41,11 @@ Data plane:
"""
import json
-import time
import logging
import re
+import time
-from ministack.core.responses import new_uuid, error_response_json
+from ministack.core.responses import error_response_json, new_uuid
logger = logging.getLogger("apigateway")
@@ -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 ministack.services import lambda_svc
from ministack.core.lambda_runtime import get_or_create_worker
+ from ministack.services import lambda_svc
uri = integration.get("integrationUri", "")
# integrationUri is a Lambda ARN; the function name is the last segment
@@ -382,8 +382,8 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
async def _invoke_http_proxy(integration, path, method, headers, body, query_params):
"""Forward a request to an HTTP backend."""
- import urllib.request
import urllib.error
+ import urllib.request
uri = integration.get("integrationUri", "")
url = uri.rstrip("/") + path
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index eed768ca..49d528f7 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -67,10 +67,10 @@ Data plane:
when api_id is found in _rest_apis.
"""
-import json
-import time
import datetime
+import json
import logging
+import time
from ministack.core.responses import new_uuid
@@ -222,8 +222,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 ministack.services import lambda_svc
from ministack.core.lambda_runtime import get_or_create_worker
+ from ministack.services import lambda_svc
if func_name not in lambda_svc._functions:
return None, f"Lambda function '{func_name}' not found"
@@ -673,8 +673,8 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_params):
"""Forward a request to an HTTP backend."""
- import urllib.request
import urllib.error
+ import urllib.request
uri = integration.get("uri", "")
url = uri.rstrip("/") + path
@@ -784,7 +784,7 @@ def _create_rest_api(data):
def _get_rest_api(api_id):
api = _rest_apis.get(api_id)
if not api:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response(api)
@@ -795,7 +795,7 @@ def _get_rest_apis():
def _update_rest_api(api_id, data):
api = _rest_apis.get(api_id)
if not api:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(api, patch_ops)
return _v1_response(api)
@@ -803,7 +803,7 @@ def _update_rest_api(api_id, data):
def _delete_rest_api(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
_rest_apis.pop(api_id, None)
_resources.pop(api_id, None)
_stages_v1.pop(api_id, None)
@@ -818,22 +818,22 @@ def _delete_rest_api(api_id):
def _get_resources(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response({"item": list(_resources.get(api_id, {}).values())})
def _get_resource(api_id, resource_id):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
return _v1_response(resource)
def _create_resource(api_id, parent_id, data):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
if parent_id not in _resources.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
path_part = data.get("pathPart", "")
resource_id = _new_id()[:8]
resource = {
@@ -852,7 +852,7 @@ def _create_resource(api_id, parent_id, data):
def _update_resource(api_id, resource_id, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(resource, patch_ops)
# Recompute path if pathPart changed
@@ -862,7 +862,7 @@ def _update_resource(api_id, resource_id, data):
def _delete_resource(api_id, resource_id):
if resource_id not in _resources.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
_resources[api_id].pop(resource_id, None)
return 202, {}, b""
@@ -872,7 +872,7 @@ def _delete_resource(api_id, resource_id):
def _put_method(api_id, resource_id, http_method, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = {
"httpMethod": http_method,
"authorizationType": data.get("authorizationType", "NONE"),
@@ -891,17 +891,17 @@ def _put_method(api_id, resource_id, http_method, data):
def _get_method(api_id, resource_id, http_method):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
return _v1_response(method_obj)
def _delete_method(api_id, resource_id, http_method):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
resource["resourceMethods"].pop(http_method, None)
return 204, {}, b""
@@ -909,10 +909,10 @@ def _delete_method(api_id, resource_id, http_method):
def _update_method(api_id, resource_id, http_method, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(method_obj, patch_ops)
return _v1_response(method_obj)
@@ -923,10 +923,10 @@ def _update_method(api_id, resource_id, http_method, data):
def _put_method_response(api_id, resource_id, http_method, status_code, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
method_response = {
"statusCode": status_code,
"responseParameters": data.get("responseParameters", {}),
@@ -939,20 +939,20 @@ def _put_method_response(api_id, resource_id, http_method, status_code, data):
def _get_method_response(api_id, resource_id, http_method, status_code):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
resp = method_obj["methodResponses"].get(status_code)
if not resp:
- return _v1_error("NotFoundException", f"Invalid Response status code specified", 404)
+ return _v1_error("NotFoundException", "Invalid Response status code specified", 404)
return _v1_response(resp)
def _delete_method_response(api_id, resource_id, http_method, status_code):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if method_obj:
method_obj["methodResponses"].pop(status_code, None)
@@ -964,10 +964,10 @@ def _delete_method_response(api_id, resource_id, http_method, status_code):
def _put_integration(api_id, resource_id, http_method, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
integration = {
"type": data.get("type", "AWS_PROXY"),
"httpMethod": data.get("httpMethod", "POST"),
@@ -989,20 +989,20 @@ def _put_integration(api_id, resource_id, http_method, data):
def _get_integration(api_id, resource_id, http_method):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
integration = method_obj.get("methodIntegration")
if not integration:
- return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Integration identifier specified", 404)
return _v1_response(integration)
def _delete_integration(api_id, resource_id, http_method):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if method_obj:
method_obj["methodIntegration"] = None
@@ -1012,13 +1012,13 @@ def _delete_integration(api_id, resource_id, http_method):
def _update_integration(api_id, resource_id, http_method, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
integration = method_obj.get("methodIntegration")
if not integration:
- return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Integration identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(integration, patch_ops)
return _v1_response(integration)
@@ -1029,13 +1029,13 @@ def _update_integration(api_id, resource_id, http_method, data):
def _put_integration_response(api_id, resource_id, http_method, status_code, data):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
integration = method_obj.get("methodIntegration")
if not integration:
- return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Integration identifier specified", 404)
int_response = {
"statusCode": status_code,
"selectionPattern": data.get("selectionPattern", ""),
@@ -1050,23 +1050,23 @@ def _put_integration_response(api_id, resource_id, http_method, status_code, dat
def _get_integration_response(api_id, resource_id, http_method, status_code):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if not method_obj:
- return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Method identifier specified", 404)
integration = method_obj.get("methodIntegration")
if not integration:
- return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Integration identifier specified", 404)
resp = integration["integrationResponses"].get(status_code)
if not resp:
- return _v1_error("NotFoundException", f"Invalid Response status code specified", 404)
+ return _v1_error("NotFoundException", "Invalid Response status code specified", 404)
return _v1_response(resp)
def _delete_integration_response(api_id, resource_id, http_method, status_code):
resource = _resources.get(api_id, {}).get(resource_id)
if not resource:
- return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Resource identifier specified", 404)
method_obj = resource["resourceMethods"].get(http_method)
if method_obj and method_obj.get("methodIntegration"):
method_obj["methodIntegration"]["integrationResponses"].pop(status_code, None)
@@ -1094,7 +1094,7 @@ def _build_api_summary(api_id):
def _create_deployment(api_id, data):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
deployment_id = _new_id()[:8]
deployment = {
"id": deployment_id,
@@ -1134,21 +1134,21 @@ def _create_deployment(api_id, data):
def _get_deployments(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response({"item": list(_deployments_v1.get(api_id, {}).values())})
def _get_deployment(api_id, deployment_id):
deployment = _deployments_v1.get(api_id, {}).get(deployment_id)
if not deployment:
- return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Deployment identifier specified", 404)
return _v1_response(deployment)
def _update_deployment(api_id, deployment_id, data):
deployment = _deployments_v1.get(api_id, {}).get(deployment_id)
if not deployment:
- return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Deployment identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(deployment, patch_ops)
return _v1_response(deployment)
@@ -1156,7 +1156,7 @@ def _update_deployment(api_id, deployment_id, data):
def _delete_deployment(api_id, deployment_id):
if deployment_id not in _deployments_v1.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Deployment identifier specified", 404)
_deployments_v1[api_id].pop(deployment_id, None)
return 202, {}, b""
@@ -1165,7 +1165,7 @@ def _delete_deployment(api_id, deployment_id):
def _create_stage(api_id, data):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
stage_name = data.get("stageName", "")
if not stage_name:
return _v1_error("BadRequestException", "Stage name is required", 400)
@@ -1190,21 +1190,21 @@ def _create_stage(api_id, data):
def _get_stages(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response({"item": list(_stages_v1.get(api_id, {}).values())})
def _get_stage(api_id, stage_name):
stage = _stages_v1.get(api_id, {}).get(stage_name)
if not stage:
- return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Stage identifier specified", 404)
return _v1_response(stage)
def _update_stage(api_id, stage_name, data):
stage = _stages_v1.get(api_id, {}).get(stage_name)
if not stage:
- return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Stage identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(stage, patch_ops)
stage["lastUpdatedDate"] = _now_unix()
@@ -1213,7 +1213,7 @@ def _update_stage(api_id, stage_name, data):
def _delete_stage(api_id, stage_name):
if stage_name not in _stages_v1.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Stage identifier specified", 404)
_stages_v1[api_id].pop(stage_name, None)
return 202, {}, b""
@@ -1222,7 +1222,7 @@ def _delete_stage(api_id, stage_name):
def _create_authorizer(api_id, data):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
auth_id = _new_id()[:8]
authorizer = {
"id": auth_id,
@@ -1241,21 +1241,21 @@ def _create_authorizer(api_id, data):
def _get_authorizers(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response({"item": list(_authorizers_v1.get(api_id, {}).values())})
def _get_authorizer(api_id, auth_id):
authorizer = _authorizers_v1.get(api_id, {}).get(auth_id)
if not authorizer:
- return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Authorizer identifier specified", 404)
return _v1_response(authorizer)
def _update_authorizer(api_id, auth_id, data):
authorizer = _authorizers_v1.get(api_id, {}).get(auth_id)
if not authorizer:
- return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Authorizer identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(authorizer, patch_ops)
return _v1_response(authorizer)
@@ -1263,7 +1263,7 @@ def _update_authorizer(api_id, auth_id, data):
def _delete_authorizer(api_id, auth_id):
if auth_id not in _authorizers_v1.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Authorizer identifier specified", 404)
_authorizers_v1[api_id].pop(auth_id, None)
return 202, {}, b""
@@ -1272,7 +1272,7 @@ def _delete_authorizer(api_id, auth_id):
def _create_model(api_id, data):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
model_name = data.get("name", "")
if not model_name:
return _v1_error("BadRequestException", "Model name is required", 400)
@@ -1289,20 +1289,20 @@ def _create_model(api_id, data):
def _get_models(api_id):
if api_id not in _rest_apis:
- return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
return _v1_response({"item": list(_models.get(api_id, {}).values())})
def _get_model(api_id, model_name):
model = _models.get(api_id, {}).get(model_name)
if not model:
- return _v1_error("NotFoundException", f"Invalid Model identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Model identifier specified", 404)
return _v1_response(model)
def _delete_model(api_id, model_name):
if model_name not in _models.get(api_id, {}):
- return _v1_error("NotFoundException", f"Invalid Model identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Model identifier specified", 404)
_models[api_id].pop(model_name, None)
return 202, {}, b""
@@ -1334,14 +1334,14 @@ def _get_api_keys():
def _get_api_key(key_id):
key = _api_keys.get(key_id)
if not key:
- return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API Key identifier specified", 404)
return _v1_response(key)
def _update_api_key(key_id, data):
key = _api_keys.get(key_id)
if not key:
- return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API Key identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(key, patch_ops)
key["lastUpdatedDate"] = _now_unix()
@@ -1350,7 +1350,7 @@ def _update_api_key(key_id, data):
def _delete_api_key(key_id):
if key_id not in _api_keys:
- return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid API Key identifier specified", 404)
_api_keys.pop(key_id, None)
return 202, {}, b""
@@ -1380,14 +1380,14 @@ def _get_usage_plans():
def _get_usage_plan(plan_id):
plan = _usage_plans.get(plan_id)
if not plan:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
return _v1_response(plan)
def _update_usage_plan(plan_id, data):
plan = _usage_plans.get(plan_id)
if not plan:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(plan, patch_ops)
return _v1_response(plan)
@@ -1395,7 +1395,7 @@ def _update_usage_plan(plan_id, data):
def _delete_usage_plan(plan_id):
if plan_id not in _usage_plans:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
_usage_plans.pop(plan_id, None)
_usage_plan_keys.pop(plan_id, None)
return 202, {}, b""
@@ -1403,7 +1403,7 @@ def _delete_usage_plan(plan_id):
def _create_usage_plan_key(plan_id, data):
if plan_id not in _usage_plans:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
key_id = data.get("keyId", "")
key_type = data.get("keyType", "API_KEY")
plan_key = {
@@ -1418,13 +1418,13 @@ def _create_usage_plan_key(plan_id, data):
def _get_usage_plan_keys(plan_id):
if plan_id not in _usage_plans:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
return _v1_response({"item": list(_usage_plan_keys.get(plan_id, {}).values())})
def _delete_usage_plan_key(plan_id, key_id):
if plan_id not in _usage_plans:
- return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)
_usage_plan_keys.get(plan_id, {}).pop(key_id, None)
return 202, {}, b""
@@ -1457,13 +1457,13 @@ def _get_domain_names():
def _get_domain_name(domain_name):
dn = _domain_names.get(domain_name)
if not dn:
- return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)
return _v1_response(dn)
def _delete_domain_name(domain_name):
if domain_name not in _domain_names:
- return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)
_domain_names.pop(domain_name, None)
_base_path_mappings.pop(domain_name, None)
return 202, {}, b""
@@ -1471,7 +1471,7 @@ def _delete_domain_name(domain_name):
def _create_base_path_mapping(domain_name, data):
if domain_name not in _domain_names:
- return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)
base_path = data.get("basePath", "(none)")
mapping = {
"basePath": base_path,
@@ -1484,14 +1484,14 @@ def _create_base_path_mapping(domain_name, data):
def _get_base_path_mappings(domain_name):
if domain_name not in _domain_names:
- return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)
return _v1_response({"item": list(_base_path_mappings.get(domain_name, {}).values())})
def _get_base_path_mapping(domain_name, base_path):
mapping = _base_path_mappings.get(domain_name, {}).get(base_path)
if not mapping:
- return _v1_error("NotFoundException", f"Invalid base path mapping identifier specified", 404)
+ return _v1_error("NotFoundException", "Invalid base path mapping identifier specified", 404)
return _v1_response(mapping)
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index f4cf60b1..8d13c600 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -13,14 +13,14 @@ Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,
TagResource, UntagResource, ListTagsForResource.
"""
-import os
-import re
import json
-import time
import logging
+import os
+import re
import threading
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("athena")
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 755d3434..850e3003 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -10,13 +10,13 @@ Operations: PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics,
PutDashboard, GetDashboard, DeleteDashboards, ListDashboards.
"""
-import re
import json
-import time
import logging
+import re
+import time
+from collections import defaultdict
from datetime import datetime, timezone
from urllib.parse import parse_qs
-from collections import defaultdict
from ministack.core.responses import new_uuid
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 2dbd22b3..3d4fb117 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -14,12 +14,12 @@ Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,
StartQuery, GetQueryResults, StopQuery.
"""
+import base64
import json
-import time
import logging
-import base64
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("logs")
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 8e37349b..06fecea9 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -42,16 +42,16 @@ Wire protocol:
Routing is handled in app.py via two separate SERVICE_HANDLERS entries.
"""
-import json
-import time
import base64
+import json
import logging
import secrets
import string
+import time
from datetime import datetime, timezone
from urllib.parse import parse_qs
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("cognito")
@@ -301,6 +301,8 @@ def _dispatch_idp(action: str, data: dict):
"SetUserPoolMfaConfig": _set_user_pool_mfa_config,
"AssociateSoftwareToken": _associate_software_token,
"VerifySoftwareToken": _verify_software_token,
+ "AdminSetUserMFAPreference": _admin_set_user_mfa_preference,
+ "SetUserMFAPreference": _set_user_mfa_preference,
# Tags
"TagResource": _idp_tag_resource,
"UntagResource": _idp_untag_resource,
@@ -593,7 +595,7 @@ def _admin_create_user(data):
if username in pool["_users"]:
return error_response_json(
"UsernameExistsException",
- f"User account already exists.", 400,
+ "User account already exists.", 400,
)
now = _now_epoch()
@@ -649,8 +651,8 @@ def _admin_get_user(data):
out = _user_out(user)
# AdminGetUser uses UserAttributes, not Attributes (per AWS API shape)
out["UserAttributes"] = out.pop("Attributes", [])
- out["UserMFASettingList"] = []
- out["PreferredMfaSetting"] = ""
+ out["UserMFASettingList"] = user.get("_mfa_enabled", [])
+ out["PreferredMfaSetting"] = user.get("_preferred_mfa", "")
return json_response(out)
@@ -854,6 +856,30 @@ def _admin_remove_user_from_group(data):
# AUTH FLOWS
# ===========================================================================
+def _mfa_challenge_for_user(pool: dict, user: dict, pid: str, username: str) -> dict | None:
+ """Return a SOFTWARE_TOKEN_MFA challenge dict if the pool+user require it, else None."""
+ mfa_config = pool.get("MfaConfiguration", "OFF")
+ if mfa_config == "OFF":
+ return None
+ preferred = user.get("_preferred_mfa", "")
+ enabled_mfa = user.get("_mfa_enabled", [])
+ # OPTIONAL: only challenge if user has TOTP set up
+ if mfa_config == "OPTIONAL" and "SOFTWARE_TOKEN_MFA" not in enabled_mfa:
+ return None
+ # ON: challenge if TOTP is set up; if not set up yet, skip (let them enroll)
+ if mfa_config == "ON" and "SOFTWARE_TOKEN_MFA" not in enabled_mfa:
+ return None
+ session = base64.b64encode(secrets.token_bytes(32)).decode()
+ return {
+ "ChallengeName": "SOFTWARE_TOKEN_MFA",
+ "Session": session,
+ "ChallengeParameters": {
+ "USER_ID_FOR_SRP": username,
+ "FRIENDLY_DEVICE_NAME": "TOTP device",
+ },
+ }
+
+
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 {
@@ -898,6 +924,9 @@ def _admin_initiate_auth(data):
"userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),
},
})
+ mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
+ if mfa_challenge:
+ return json_response(mfa_challenge)
return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
@@ -949,6 +978,15 @@ def _admin_respond_to_auth_challenge(data):
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)
+ # Accept any TOTP code in emulator — no real TOTP validation
+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
+
+ if challenge_name == "MFA_SETUP":
+ # Triggered when pool MFA=ON but user hasn't enrolled yet
username = responses.get("USERNAME")
user = pool["_users"].get(username)
if not user:
@@ -996,6 +1034,9 @@ def _initiate_auth(data):
"userAttributes": json.dumps(_attr_list_to_dict(user.get("Attributes", []))),
},
})
+ mfa_challenge = _mfa_challenge_for_user(pool, user, pid, username)
+ if mfa_challenge:
+ return json_response(mfa_challenge)
return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
@@ -1057,6 +1098,14 @@ def _respond_to_auth_challenge(data):
user["UserLastModifiedDate"] = _now_epoch()
return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
+ if challenge_name in ("SOFTWARE_TOKEN_MFA", "MFA_SETUP"):
+ username = responses.get("USERNAME")
+ user = pool["_users"].get(username)
+ if not user:
+ return error_response_json("UserNotFoundException", "User does not exist.", 400)
+ # Accept any TOTP code in emulator
+ return json_response({"AuthenticationResult": _build_auth_result(pid, cid, user)})
+
return error_response_json("InvalidParameterException", f"Unsupported challenge: {challenge_name}", 400)
@@ -1230,8 +1279,8 @@ def _get_user(data):
out = _user_out(user)
# GetUser uses UserAttributes, not Attributes (per AWS API shape)
out["UserAttributes"] = out.pop("Attributes", [])
- out["UserMFASettingList"] = []
- out["PreferredMfaSetting"] = ""
+ out["UserMFASettingList"] = user.get("_mfa_enabled", [])
+ out["PreferredMfaSetting"] = user.get("_preferred_mfa", "")
return json_response(out)
return error_response_json("NotAuthorizedException", "Invalid access token.", 400)
@@ -1431,6 +1480,59 @@ def _get_user_pool_mfa_config(data):
})
+def _admin_set_user_mfa_preference(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
+ _apply_mfa_preference(user, data)
+ return json_response({})
+
+
+def _set_user_mfa_preference(data):
+ """Public (user-facing) version — resolves user from AccessToken."""
+ access_token = data.get("AccessToken")
+ if not access_token:
+ return error_response_json("NotAuthorizedException", "Missing access token.", 400)
+ for pool in _user_pools.values():
+ user = _user_from_token(access_token, pool)
+ if user:
+ _apply_mfa_preference(user, data)
+ return json_response({})
+ return error_response_json("NotAuthorizedException", "Invalid access token.", 400)
+
+
+def _apply_mfa_preference(user: dict, data: dict):
+ """Shared logic for Admin and user-facing SetUserMFAPreference."""
+ totp_settings = data.get("SoftwareTokenMfaSettings", {})
+ sms_settings = data.get("SMSMfaSettings", {})
+ enabled_mfa = user.setdefault("_mfa_enabled", [])
+
+ if totp_settings.get("Enabled"):
+ if "SOFTWARE_TOKEN_MFA" not in enabled_mfa:
+ enabled_mfa.append("SOFTWARE_TOKEN_MFA")
+ if totp_settings.get("PreferredMfa"):
+ user["_preferred_mfa"] = "SOFTWARE_TOKEN_MFA"
+ elif "Enabled" in totp_settings and not totp_settings["Enabled"]:
+ enabled_mfa[:] = [m for m in enabled_mfa if m != "SOFTWARE_TOKEN_MFA"]
+ if user.get("_preferred_mfa") == "SOFTWARE_TOKEN_MFA":
+ user["_preferred_mfa"] = ""
+
+ if sms_settings.get("Enabled"):
+ if "SMS_MFA" not in enabled_mfa:
+ enabled_mfa.append("SMS_MFA")
+ if sms_settings.get("PreferredMfa"):
+ user["_preferred_mfa"] = "SMS_MFA"
+ elif "Enabled" in sms_settings and not sms_settings["Enabled"]:
+ enabled_mfa[:] = [m for m in enabled_mfa if m != "SMS_MFA"]
+ if user.get("_preferred_mfa") == "SMS_MFA":
+ user["_preferred_mfa"] = ""
+
+
def _set_user_pool_mfa_config(data):
pid = data.get("UserPoolId")
pool, err = _resolve_pool(pid)
@@ -1451,13 +1553,29 @@ def _set_user_pool_mfa_config(data):
def _associate_software_token(data):
- # Return a stub TOTP secret
+ """Issue a stub TOTP secret. Works with both AccessToken and Session."""
secret = base64.b32encode(secrets.token_bytes(20)).decode()
- return json_response({"SecretCode": secret})
+ session = base64.b64encode(secrets.token_bytes(32)).decode()
+ return json_response({"SecretCode": secret, "Session": session})
def _verify_software_token(data):
- # Accept any code in emulation
+ """Accept any TOTP code. Mark the user as TOTP-enrolled so auth flow issues the challenge."""
+ access_token = data.get("AccessToken")
+ user_code = data.get("UserCode", "") # accepted regardless of value in emulator
+ friendly_name = data.get("FriendlyDeviceName", "TOTP device")
+
+ if access_token:
+ # Find the user by token across all pools
+ for pool in _user_pools.values():
+ user = _user_from_token(access_token, pool)
+ if user:
+ user.setdefault("_mfa_enabled", [])
+ if "SOFTWARE_TOKEN_MFA" not in user["_mfa_enabled"]:
+ user["_mfa_enabled"].append("SOFTWARE_TOKEN_MFA")
+ user["_preferred_mfa"] = "SOFTWARE_TOKEN_MFA"
+ break
+
return json_response({"Status": "SUCCESS"})
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index c4f534ed..f30949a4 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -9,16 +9,21 @@ Supports: CreateTable, DeleteTable, DescribeTable, ListTables, UpdateTable,
Uses X-Amz-Target header for action routing (JSON API).
"""
-import re
-import time
import copy
import json
import logging
+import re
import threading
+import time
from collections import defaultdict
from decimal import Decimal, InvalidOperation
-from ministack.core.responses import json_response, error_response_json, new_uuid, now_iso
+from ministack.core.responses import (
+ error_response_json,
+ json_response,
+ new_uuid,
+ now_iso,
+)
logger = logging.getLogger("dynamodb")
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index e4d9ed18..5819885a 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -42,11 +42,11 @@ Supports:
DeleteEgressOnlyInternetGateway
"""
+import logging
import os
-import time
import random
import string
-import logging
+import time
from urllib.parse import parse_qs
from ministack.core.responses import new_uuid
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 6d9a02c6..ba3fbe2b 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -14,12 +14,17 @@ Supports: CreateCluster, DeleteCluster, DescribeClusters, ListClusters,
Container execution: if Docker socket is available, RunTask actually runs containers.
"""
-import os
import json
-import time
import logging
+import os
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid, now_iso
+from ministack.core.responses import (
+ error_response_json,
+ json_response,
+ new_uuid,
+ now_iso,
+)
logger = logging.getLogger("ecs")
@@ -190,7 +195,7 @@ def _delete_cluster(data):
name = _resolve_cluster_name(data.get("cluster", "default"))
cluster = _clusters.pop(name, None)
if not cluster:
- return error_response_json("ClusterNotFoundException", f"Cluster not found.", 400)
+ return error_response_json("ClusterNotFoundException", "Cluster not found.", 400)
cluster["status"] = "INACTIVE"
_tags.pop(cluster["clusterArn"], None)
return json_response({"cluster": cluster})
@@ -402,7 +407,7 @@ def _create_service(data):
svc_key = f"{cluster_name}/{name}"
if svc_key in _services and _services[svc_key]["status"] == "ACTIVE":
return error_response_json("ServiceAlreadyExists",
- f"Creation of service was not idempotent.", 400)
+ "Creation of service was not idempotent.", 400)
td_ref = data.get("taskDefinition", "")
td_key = _resolve_td_key(td_ref)
@@ -470,7 +475,7 @@ def _delete_service(data):
svc = _services.get(svc_key)
if not svc:
return error_response_json("ServiceNotFoundException",
- f"Service not found.", 400)
+ "Service not found.", 400)
force = data.get("force", False)
if not force and svc.get("desiredCount", 0) > 0:
@@ -740,7 +745,7 @@ def _stop_task(data):
task = _resolve_task(task_ref, cluster_name)
if not task:
return error_response_json("InvalidParameterException",
- f"The referenced task was not found.", 400)
+ "The referenced task was not found.", 400)
if task["lastStatus"] == "STOPPED":
return json_response({"task": _sanitize(task)})
diff --git a/ministack/services/efs.py b/ministack/services/efs.py
index f855d52f..448e4744 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -15,13 +15,13 @@ Supports:
Account: DescribeAccountPreferences, PutAccountPreferences
"""
-import os
import json
+import logging
+import os
import random
+import re
import string
-import logging
import time
-import re
logger = logging.getLogger("efs")
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index c4c30fe6..6382d4dc 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -20,9 +20,9 @@ When Docker is available, CreateCacheCluster spins up a real Redis/Memcached con
Otherwise returns localhost:6379 (assumes Redis sidecar in docker-compose).
"""
+import logging
import os
import time
-import logging
from urllib.parse import parse_qs
from ministack.core.responses import new_uuid
diff --git a/ministack/services/emr.py b/ministack/services/emr.py
index 93c7f978..bed3b03b 100644
--- a/ministack/services/emr.py
+++ b/ministack/services/emr.py
@@ -14,14 +14,14 @@ Supports:
Block Public Access: GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration
"""
-import os
import json
+import logging
+import os
import random
import string
-import logging
import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("emr")
@@ -176,7 +176,7 @@ def _run_job_flow(data):
"Tags": tags,
"ServiceRole": service_role,
"NormalizedInstanceHours": 0,
- "MasterPublicDnsName": f"ec2-0-0-0-0.compute-1.amazonaws.com",
+ "MasterPublicDnsName": "ec2-0-0-0-0.compute-1.amazonaws.com",
"StepConcurrencyLevel": data.get("StepConcurrencyLevel", 1),
"BootstrapActions": bootstrap_actions,
"InstanceFleets": instance_fleets,
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 80459b1f..79e82c89 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -14,14 +14,14 @@ Supports: CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus,
"""
import asyncio
-import json
-import time
import hashlib
+import json
import logging
import re
+import time
from datetime import datetime, timezone
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("events")
@@ -196,7 +196,7 @@ def _put_rule(data):
if schedule and not _validate_schedule_expression(schedule):
return error_response_json(
"ValidationException",
- f"Parameter ScheduleExpression is not valid.",
+ "Parameter ScheduleExpression is not valid.",
400,
)
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index accb18a9..cf609056 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -21,7 +21,12 @@ import logging
import threading
import time
-from ministack.core.responses import json_response, error_response_json, new_uuid, now_epoch
+from ministack.core.responses import (
+ error_response_json,
+ json_response,
+ new_uuid,
+ now_epoch,
+)
logger = logging.getLogger("firehose")
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 37e3a39f..cd65d828 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -8,15 +8,15 @@ Job execution runs Python scripts via subprocess in background threads.
Crawlers transition through RUNNING state with a configurable timer.
"""
-import os
import json
-import time
+import logging
+import os
import subprocess
import tempfile
import threading
-import logging
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("glue")
@@ -353,7 +353,7 @@ def _batch_create_partition(data):
if dupe:
errors.append({"PartitionValues": values, "ErrorDetail": {
"ErrorCode": "AlreadyExistsException",
- "ErrorMessage": f"Partition already exists"}})
+ "ErrorMessage": "Partition already exists"}})
else:
_partitions[key].append({
**pi,
diff --git a/ministack/services/iam_sts.py b/ministack/services/iam_sts.py
index 98d45fd7..f6edda9a 100644
--- a/ministack/services/iam_sts.py
+++ b/ministack/services/iam_sts.py
@@ -31,7 +31,8 @@ STS actions:
import json
import logging
import time
-from urllib.parse import parse_qs, quote as _url_quote
+from urllib.parse import parse_qs
+from urllib.parse import quote as _url_quote
from ministack.core.responses import new_uuid
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index dc460c82..5cff5e0a 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -12,14 +12,14 @@ Supports: CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary,
EnableEnhancedMonitoring, DisableEnhancedMonitoring.
"""
-import json
-import time
import base64
import hashlib
+import json
import logging
import threading
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("kinesis")
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 33c7df00..2650923c 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -22,24 +22,24 @@ with the event piped through stdin (safe from injection).
SQS event source mappings poll the queue in a background thread.
"""
-import os
import asyncio
-import importlib
-from typing import Any
-import copy
-import json
-import time
import base64
+import copy
import hashlib
-import zipfile
-import tempfile
-import subprocess
-import threading
+import importlib
+import json
import logging
+import os
import re
+import subprocess
+import tempfile
+import threading
+import time
+import zipfile
+from typing import Any
from urllib.parse import unquote
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("lambda")
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 0c5b1274..23a28f5e 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -21,9 +21,9 @@ When Docker is available, CreateDBInstance spins up a real Postgres/MySQL contai
and returns the actual host:port as the endpoint.
"""
+import logging
import os
import time
-import logging
from urllib.parse import parse_qs
from ministack.core.responses import new_uuid
diff --git a/ministack/services/route53.py b/ministack/services/route53.py
index 5323212d..80c8111e 100644
--- a/ministack/services/route53.py
+++ b/ministack/services/route53.py
@@ -18,13 +18,13 @@ Wire protocol:
Paths are under /2013-04-01/
"""
+import logging
+import random
import re
import string
-import logging
import threading
-import random
from datetime import datetime, timezone
-from xml.etree.ElementTree import Element, SubElement, tostring, fromstring
+from xml.etree.ElementTree import Element, SubElement, fromstring, tostring
from ministack.core.responses import new_uuid
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index a20f6e1b..ae3484ee 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -17,18 +17,25 @@ Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,
Storage: In-memory (optionally backed by S3_DATA_DIR).
"""
-import os
-import re
import base64
import hashlib
import json
import logging
+import os
+import re
import threading
import time
-from urllib.parse import quote as url_quote, unquote as url_unquote
-from xml.etree.ElementTree import Element, SubElement, tostring, fromstring
-
-from ministack.core.responses import md5_hash, sha256_hash, now_iso, new_uuid, iso_to_rfc7231
+from urllib.parse import quote as url_quote
+from urllib.parse import unquote as url_unquote
+from xml.etree.ElementTree import Element, SubElement, fromstring, tostring
+
+from ministack.core.responses import (
+ iso_to_rfc7231,
+ md5_hash,
+ new_uuid,
+ now_iso,
+ sha256_hash,
+)
logger = logging.getLogger("s3")
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 98cfba6f..76be55d0 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -9,14 +9,14 @@ Supports: CreateSecret, GetSecretValue, ListSecrets, DeleteSecret,
ValidateResourcePolicy.
"""
+import base64
import json
-import time
-import string
-import secrets as stdlib_secrets
import logging
-import base64
+import secrets as stdlib_secrets
+import string
+import time
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("secretsmanager")
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index b24bdc96..98ebb012 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -17,9 +17,9 @@ import logging
import time
from urllib.parse import parse_qs
+import ministack.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_svc
logger = logging.getLogger("sns")
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index a74b7b06..3cee3162 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -22,16 +22,16 @@ Actions:
"""
import asyncio
-import os
-import time
-import json
import hashlib
+import json
import logging
+import os
import struct
+import time
from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
-from ministack.core.responses import new_uuid, now_iso, md5_hash
+from ministack.core.responses import md5_hash, new_uuid, now_iso
logger = logging.getLogger("sqs")
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index 903dbf05..74f8e9ff 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -7,13 +7,13 @@ Supports: PutParameter, GetParameter, GetParameters, GetParametersByPath,
AddTagsToResource, RemoveTagsFromResource, ListTagsForResource.
"""
+import base64
import json
-import time
import logging
-import base64
+import time
from datetime import datetime, timezone
-from ministack.core.responses import json_response, error_response_json, new_uuid
+from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("ssm")
@@ -91,7 +91,7 @@ def _put_parameter(data):
if name in _parameters and not overwrite:
return error_response_json(
"ParameterAlreadyExists",
- f"The parameter already exists. To overwrite this value, set the overwrite option in the request to true.",
+ "The parameter already exists. To overwrite this value, set the overwrite option in the request to true.",
400,
)
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index a0f13d40..17bc7072 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -25,10 +25,16 @@ import logging
import re
import threading
import time
-from concurrent.futures import ThreadPoolExecutor, wait as futures_wait
+from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import wait as futures_wait
from datetime import datetime, timezone
-from ministack.core.responses import json_response, error_response_json, new_uuid, now_iso
+from ministack.core.responses import (
+ error_response_json,
+ json_response,
+ new_uuid,
+ now_iso,
+)
logger = logging.getLogger("states")
@@ -380,7 +386,7 @@ def _send_task_success(data):
info = _task_tokens.get(token)
if not info:
return error_response_json(
- "TaskDoesNotExist", f"Task token not found", 400)
+ "TaskDoesNotExist", "Task token not found", 400)
info["result"] = output
info["event"].set()
return json_response({})
@@ -391,7 +397,7 @@ def _send_task_failure(data):
info = _task_tokens.get(token)
if not info:
return error_response_json(
- "TaskDoesNotExist", f"Task token not found", 400)
+ "TaskDoesNotExist", "Task token not found", 400)
info["error"] = {
"Error": data.get("error", "TaskFailed"),
"Cause": data.get("cause", ""),
@@ -405,7 +411,7 @@ def _send_task_heartbeat(data):
info = _task_tokens.get(token)
if not info:
return error_response_json(
- "TaskDoesNotExist", f"Task token not found", 400)
+ "TaskDoesNotExist", "Task token not found", 400)
info["heartbeat"] = now_iso()
return json_response({})
diff --git a/pyproject.toml b/pyproject.toml
index a6dd9126..6f9faf02 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.7"
+version = "1.1.8"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
@@ -37,6 +37,7 @@ dev = [
"pytest-cov>=5.0",
"duckdb>=0.10.0",
"docker>=7.0.0",
+ "ruff>=0.4",
]
[project.urls]
@@ -55,6 +56,25 @@ testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
+[tool.ruff]
+line-length = 120
+target-version = "py310"
+
+[tool.ruff.lint]
+select = ["E", "F", "I"]
+ignore = [
+ "E501", # line too long — XML templates and service tables make this impractical
+ "E402", # module import not at top — intentional lazy imports in service files
+ "F401", # unused import — needs manual review; some are re-exports
+ "F811", # redefined while unused — needs manual review
+ "F841", # unused variable — needs manual review
+ "E741", # ambiguous variable name — too noisy for emulator code
+ "F601", # multi-value repeated key — needs manual review
+]
+
+[tool.ruff.lint.per-file-ignores]
+"ministack/services/dynamodb.py" = ["E701", "E702"] # compact tokenizer style is intentional
+
[tool.coverage.run]
source = ["ministack"]
omit = ["tests/*"]
diff --git a/tests/conftest.py b/tests/conftest.py
index 0315498b..424dd30e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,8 +3,9 @@ Pytest fixtures for MiniStack integration tests.
"""
import os
import urllib.request
-import pytest
+
import boto3
+import pytest
from botocore.config import Config
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
diff --git a/tests/test_services.py b/tests/test_services.py
index c10e2019..c6af47cf 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -21,7 +21,6 @@ _EXECUTE_PORT = urlparse(_endpoint).port or 4566
import pytest
from botocore.exceptions import ClientError
-
# ========== S3 ==========
@@ -1031,7 +1030,8 @@ def test_lambda_create_invoke(lam):
def test_lambda_esm_sqs(lam, sqs):
"""SQS → Lambda event source mapping: messages sent to SQS trigger Lambda."""
- import io, zipfile as zf
+ import io
+ import zipfile as zf
# Clean up from previous runs
try:
@@ -2578,24 +2578,24 @@ def test_iam_create_policy(iam):
def test_iam_get_policy(iam):
- arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"
+ arn = "arn:aws:iam::000000000000:policy/iam-test-policy"
resp = iam.get_policy(PolicyArn=arn)
assert resp["Policy"]["PolicyName"] == "iam-test-policy"
def test_iam_attach_role_policy(iam):
- policy_arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"
+ policy_arn = "arn:aws:iam::000000000000:policy/iam-test-policy"
iam.attach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)
def test_iam_list_attached_role_policies(iam):
resp = iam.list_attached_role_policies(RoleName="iam-test-role")
arns = [p["PolicyArn"] for p in resp["AttachedPolicies"]]
- assert f"arn:aws:iam::000000000000:policy/iam-test-policy" in arns
+ assert "arn:aws:iam::000000000000:policy/iam-test-policy" in arns
def test_iam_detach_role_policy(iam):
- policy_arn = f"arn:aws:iam::000000000000:policy/iam-test-policy"
+ policy_arn = "arn:aws:iam::000000000000:policy/iam-test-policy"
iam.detach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)
resp = iam.list_attached_role_policies(RoleName="iam-test-role")
arns = [p["PolicyArn"] for p in resp["AttachedPolicies"]]
@@ -4663,7 +4663,7 @@ def test_athena_tags_v2(athena):
arn = athena.get_work_group(WorkGroup="ath-tag-v2wg")["WorkGroup"]["Configuration"][
"ResultConfiguration"
]["OutputLocation"]
- wg_arn = f"arn:aws:athena:us-east-1:000000000000:workgroup/ath-tag-v2wg"
+ wg_arn = "arn:aws:athena:us-east-1:000000000000:workgroup/ath-tag-v2wg"
athena.tag_resource(ResourceARN=wg_arn, Tags=[{"Key": "env", "Value": "dev"}])
resp = athena.list_tags_for_resource(ResourceARN=wg_arn)
@@ -5665,8 +5665,8 @@ def test_ddb_ttl(ddb):
def test_lambda_warm_start(lam, apigw):
"""Warm worker via API Gateway execute-api: module-level state persists across invocations."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-warm-{_uuid.uuid4().hex[:8]}"
code = (
@@ -5718,9 +5718,9 @@ def test_lambda_warm_start(lam, apigw):
def test_apigw_execute_lambda_proxy(apigw, lam):
"""API Gateway execute-api routes a request through Lambda proxy integration."""
- import uuid as _uuid
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-apigw-fn-{_uuid.uuid4().hex[:8]}"
code = (
@@ -5774,8 +5774,8 @@ def test_apigw_execute_lambda_proxy(apigw, lam):
def test_apigw_execute_no_route(apigw):
"""execute-api returns 404 when no matching route exists."""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
api_id = apigw.create_api(Name="no-route-api", ProtocolType="HTTP")["ApiId"]
apigw.create_stage(ApiId=api_id, StageName="$default")
@@ -5792,8 +5792,8 @@ def test_apigw_execute_no_route(apigw):
def test_apigw_execute_default_route(apigw, lam):
"""$default catch-all route matches any path."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-default-fn-{_uuid.uuid4().hex[:8]}"
code = (
@@ -5901,8 +5901,8 @@ def test_eventbridge_lambda_target(eb, lam):
def test_apigw_path_param_route(apigw, lam):
"""Route with {id} path parameter matches requests correctly."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-param-fn-{_uuid.uuid4().hex[:8]}"
code = (
@@ -5946,8 +5946,8 @@ def test_apigw_path_param_route(apigw, lam):
def test_apigw_greedy_path_param(apigw, lam):
"""{proxy+} greedy path parameter matches paths with multiple segments."""
- import uuid as _uuid_mod
import urllib.request as _urlreq
+ import uuid as _uuid_mod
fname = f"intg-greedy-{_uuid_mod.uuid4().hex[:8]}"
code = 'def handler(event, context):\n return {"statusCode": 200, "body": event["rawPath"]}\n'
@@ -6032,8 +6032,8 @@ def test_apigw_authorizer_crud(apigw):
def test_apigw_routekey_in_lambda_event(apigw, lam):
"""routeKey in Lambda event should reflect the matched route, not hardcoded $default."""
- import uuid as _uuid_mod
import urllib.request as _urlreq
+ import uuid as _uuid_mod
fname = f"intg-rk-{_uuid_mod.uuid4().hex[:8]}"
code = 'def handler(event, context):\n return {"statusCode": 200, "body": event["routeKey"]}\n'
@@ -7500,8 +7500,8 @@ def test_apigwv1_usage_plan_crud(apigw_v1):
def test_apigwv1_execute_lambda_proxy(apigw_v1, lam):
"""End-to-end: create API + resource + method + integration + deploy + invoke Lambda."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-v1-proxy-{_uuid.uuid4().hex[:8]}"
code = (
@@ -7560,8 +7560,8 @@ def test_apigwv1_execute_lambda_proxy(apigw_v1, lam):
def test_apigwv1_execute_path_params(apigw_v1, lam):
"""Path parameter {userId} is passed correctly in event['pathParameters']."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"intg-v1-params-{_uuid.uuid4().hex[:8]}"
code = (
@@ -7681,8 +7681,8 @@ def test_apigwv1_execute_mock_integration(apigw_v1):
def test_apigwv1_execute_missing_resource_404(apigw_v1):
"""Request to non-existent path returns 404 with AWS-style message."""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
api_id = apigw_v1.create_rest_api(name="v1-missing-resource")["id"]
dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
@@ -7702,8 +7702,8 @@ def test_apigwv1_execute_missing_resource_404(apigw_v1):
def test_apigwv1_no_conflict_with_v2(apigw_v1, apigw, lam):
"""v1 and v2 APIs can coexist; execute-api routes them independently."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
# Create v1 Lambda
fname_v1 = f"intg-coexist-v1-{_uuid.uuid4().hex[:8]}"
@@ -8048,8 +8048,8 @@ def test_apigwv1_base_path_mapping_crud(apigw_v1):
def test_apigwv1_execute_missing_stage_404(apigw_v1):
"""execute-api returns 404 when stage does not exist."""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
api_id = apigw_v1.create_rest_api(name="v1-no-stage")["id"]
root_id = next(
@@ -8077,8 +8077,8 @@ def test_apigwv1_execute_missing_stage_404(apigw_v1):
def test_apigwv1_execute_missing_method_405(apigw_v1):
"""execute-api returns 405 when resource exists but method is not configured."""
- import urllib.request as _urlreq
import urllib.error as _urlerr
+ import urllib.request as _urlreq
api_id = apigw_v1.create_rest_api(name="v1-no-method")["id"]
root_id = next(
@@ -8113,8 +8113,8 @@ def test_apigwv1_execute_missing_method_405(apigw_v1):
def test_apigwv1_execute_lambda_arn_uri(apigw_v1, lam):
"""execute-api Lambda proxy works with plain arn:aws:lambda ARN as integration URI."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"v1-arn-uri-{_uuid.uuid4().hex[:8]}"
code = (
@@ -8173,8 +8173,8 @@ def test_apigwv1_execute_lambda_arn_uri(apigw_v1, lam):
def test_apigwv1_execute_lambda_requestcontext(apigw_v1, lam):
"""execute-api Lambda event includes required requestContext fields."""
- import uuid as _uuid
import urllib.request as _urlreq
+ import uuid as _uuid
fname = f"v1-reqctx-{_uuid.uuid4().hex[:8]}"
code = (
@@ -9084,7 +9084,10 @@ def test_sns_to_lambda_event_subscription_arn(lam, sns):
sns.publish(TopicArn=topic_arn, Message="test-sub-arn")
# Invoke the function directly and check what event it last received
- import json, base64, zipfile, io
+ import base64
+ import io
+ import json
+ import zipfile
result = lam.invoke(FunctionName=fn, Payload=json.dumps({"ping": True}).encode())
# The subscription ARN should be a real ARN, not "{topic}:subscription"
@@ -9094,7 +9097,8 @@ def test_sns_to_lambda_event_subscription_arn(lam, sns):
def test_lambda_unknown_path_returns_404(lam):
"""Requests to an unrecognised Lambda path must return 404, not 400 InvalidRequest."""
- import urllib.request, urllib.error
+ import urllib.error
+ import urllib.request
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
req = urllib.request.Request(
@@ -9227,10 +9231,11 @@ _requires_package = pytest.mark.skipif(
@_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.lambda_runtime import get_or_create_worker
+ from ministack.core.lambda_runtime import reset as lr_reset
+ from ministack.core.persistence import load_state, save_all
+ from ministack.core.responses import error_response_json, json_response, 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)
@@ -9242,29 +9247,29 @@ def test_package_core_importable():
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,
+ apigateway,
+ apigateway_v1,
+ athena,
cloudwatch,
- ses,
- stepfunctions,
+ cloudwatch_logs,
+ cognito,
+ dynamodb,
ecs,
- rds,
elasticache,
- glue,
- athena,
- apigateway,
- apigateway_v1,
+ eventbridge,
firehose,
+ glue,
+ kinesis,
+ lambda_svc,
+ rds,
route53,
- cognito,
+ s3,
+ secretsmanager,
+ ses,
+ sns,
+ sqs,
+ ssm,
+ stepfunctions,
)
from ministack.services.iam_sts import handle_iam_request, handle_sts_request
@@ -9303,6 +9308,7 @@ def test_package_services_importable():
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)
@@ -10378,6 +10384,161 @@ def test_cognito_force_change_password_challenge(cognito_idp):
assert "Session" in auth
+# ---------------------------------------------------------------------------
+# Cognito TOTP MFA
+# ---------------------------------------------------------------------------
+
+
+def test_cognito_totp_full_flow(cognito_idp):
+ """Full TOTP MFA flow: SetUserPoolMfaConfig ON → AssociateSoftwareToken →
+ VerifySoftwareToken → InitiateAuth returns SOFTWARE_TOKEN_MFA challenge →
+ RespondToAuthChallenge with any code returns tokens."""
+ pid = cognito_idp.create_user_pool(PoolName="qa-totp-full")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid,
+ ClientName="qa-totp-app",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+
+ # Enable TOTP MFA on the pool
+ cognito_idp.set_user_pool_mfa_config(
+ UserPoolId=pid,
+ SoftwareTokenMfaConfiguration={"Enabled": True},
+ MfaConfiguration="ON",
+ )
+ cfg = cognito_idp.get_user_pool_mfa_config(UserPoolId=pid)
+ assert cfg["MfaConfiguration"] == "ON"
+ assert cfg["SoftwareTokenMfaConfiguration"]["Enabled"] is True
+
+ # Create and confirm user
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="totp-user", TemporaryPassword="Tmp1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="totp-user", Password="Perm1!", Permanent=True)
+
+ # Enroll TOTP: associate → get tokens first (MFA not yet enrolled, pool is ON but no enrollment)
+ # Pool ON with no enrollment → auth succeeds so user can enroll
+ auth = cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid,
+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "totp-user", "PASSWORD": "Perm1!"},
+ )
+ access_token = auth["AuthenticationResult"]["AccessToken"]
+
+ # Associate software token
+ assoc = cognito_idp.associate_software_token(AccessToken=access_token)
+ assert "SecretCode" in assoc
+ assert len(assoc["SecretCode"]) > 0
+
+ # Verify (accept any code)
+ verify = cognito_idp.verify_software_token(AccessToken=access_token, UserCode="123456")
+ assert verify["Status"] == "SUCCESS"
+
+ # Now auth should return SOFTWARE_TOKEN_MFA challenge
+ auth2 = cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid,
+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "totp-user", "PASSWORD": "Perm1!"},
+ )
+ assert auth2.get("ChallengeName") == "SOFTWARE_TOKEN_MFA"
+ assert "Session" in auth2
+
+ # Respond with any TOTP code → get tokens
+ result = cognito_idp.admin_respond_to_auth_challenge(
+ UserPoolId=pid, ClientId=cid,
+ ChallengeName="SOFTWARE_TOKEN_MFA",
+ ChallengeResponses={"USERNAME": "totp-user", "SOFTWARE_TOKEN_MFA_CODE": "123456"},
+ )
+ assert "AuthenticationResult" in result
+ assert "AccessToken" in result["AuthenticationResult"]
+
+
+def test_cognito_totp_optional_mfa(cognito_idp):
+ """OPTIONAL MFA: users without TOTP enrolled go straight to tokens;
+ users with TOTP enrolled get the challenge."""
+ pid = cognito_idp.create_user_pool(PoolName="qa-totp-optional")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="qa-totp-opt-app",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+
+ cognito_idp.set_user_pool_mfa_config(
+ UserPoolId=pid,
+ SoftwareTokenMfaConfiguration={"Enabled": True},
+ MfaConfiguration="OPTIONAL",
+ )
+
+ # User without MFA enrolled
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="no-mfa-user", TemporaryPassword="Tmp1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="no-mfa-user", Password="Perm1!", Permanent=True)
+ auth = cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid,
+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "no-mfa-user", "PASSWORD": "Perm1!"},
+ )
+ assert "AuthenticationResult" in auth # no challenge — not enrolled
+
+ # User with MFA enrolled via AdminSetUserMFAPreference
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-user", TemporaryPassword="Tmp1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-user", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_set_user_mfa_preference(
+ UserPoolId=pid, Username="mfa-user",
+ SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True},
+ )
+ auth2 = cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid,
+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "mfa-user", "PASSWORD": "Perm1!"},
+ )
+ assert auth2.get("ChallengeName") == "SOFTWARE_TOKEN_MFA"
+
+
+def test_cognito_admin_get_user_mfa_fields(cognito_idp):
+ """AdminGetUser returns correct UserMFASettingList and PreferredMfaSetting."""
+ pid = cognito_idp.create_user_pool(PoolName="qa-totp-getuser")["UserPool"]["Id"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-check-user", TemporaryPassword="Tmp1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-check-user", Password="Perm1!", Permanent=True)
+
+ # Before enrollment
+ u = cognito_idp.admin_get_user(UserPoolId=pid, Username="mfa-check-user")
+ assert u["UserMFASettingList"] == []
+ assert u["PreferredMfaSetting"] == ""
+
+ # After enrollment
+ cognito_idp.admin_set_user_mfa_preference(
+ UserPoolId=pid, Username="mfa-check-user",
+ SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True},
+ )
+ u2 = cognito_idp.admin_get_user(UserPoolId=pid, Username="mfa-check-user")
+ assert "SOFTWARE_TOKEN_MFA" in u2["UserMFASettingList"]
+ assert u2["PreferredMfaSetting"] == "SOFTWARE_TOKEN_MFA"
+
+
+def test_cognito_set_user_mfa_preference_via_token(cognito_idp):
+ """SetUserMFAPreference (public, uses AccessToken) enrolls TOTP on the user."""
+ pid = cognito_idp.create_user_pool(PoolName="qa-totp-selfenroll")["UserPool"]["Id"]
+ cid = cognito_idp.create_user_pool_client(
+ UserPoolId=pid, ClientName="qa-totp-self-app",
+ ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
+ )["UserPoolClient"]["ClientId"]
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="self-enroll", TemporaryPassword="Tmp1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="self-enroll", Password="Perm1!", Permanent=True)
+
+ auth = cognito_idp.admin_initiate_auth(
+ UserPoolId=pid, ClientId=cid,
+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",
+ AuthParameters={"USERNAME": "self-enroll", "PASSWORD": "Perm1!"},
+ )
+ access_token = auth["AuthenticationResult"]["AccessToken"]
+
+ cognito_idp.set_user_mfa_preference(
+ AccessToken=access_token,
+ SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True},
+ )
+
+ u = cognito_idp.admin_get_user(UserPoolId=pid, Username="self-enroll")
+ assert "SOFTWARE_TOKEN_MFA" in u["UserMFASettingList"]
+ assert u["PreferredMfaSetting"] == "SOFTWARE_TOKEN_MFA"
+
+
# ---------------------------------------------------------------------------
# DYNAMODB — edge cases
# ---------------------------------------------------------------------------
@@ -12047,6 +12208,67 @@ def test_athena_data_catalog_crud(athena):
assert not any(c["CatalogName"] == "qa-athena-catalog" for c in catalogs2)
+# ---------------------------------------------------------------------------
+# Athena engine control + /_ministack/config endpoint
+# ---------------------------------------------------------------------------
+
+
+def test_athena_engine_mock_via_config(athena):
+ """Switching ATHENA_ENGINE to 'mock' via /_ministack/config returns mock results."""
+ import json as _json
+ import urllib.request
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ req = urllib.request.Request(
+ f"{endpoint}/_ministack/config",
+ data=_json.dumps({"athena.ATHENA_ENGINE": "mock"}).encode(),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ resp = _json.loads(urllib.request.urlopen(req, timeout=5).read())
+ assert resp["applied"].get("athena.ATHENA_ENGINE") == "mock"
+
+ # Query executes and succeeds in mock mode
+ qid = athena.start_query_execution(
+ QueryString="SELECT 1",
+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},
+ )["QueryExecutionId"]
+ import time as _time
+ for _ in range(10):
+ state = athena.get_query_execution(QueryExecutionId=qid)["QueryExecution"]["Status"]["State"]
+ if state in ("SUCCEEDED", "FAILED"):
+ break
+ _time.sleep(0.2)
+ assert state == "SUCCEEDED"
+
+ # Reset back to auto
+ req2 = urllib.request.Request(
+ f"{endpoint}/_ministack/config",
+ data=_json.dumps({"athena.ATHENA_ENGINE": "auto"}).encode(),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ urllib.request.urlopen(req2, timeout=5)
+
+
+def test_ministack_config_invalid_key_ignored():
+ """/_ministack/config silently ignores unknown keys and only applies valid ones."""
+ import json as _json
+ import urllib.request
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ req = urllib.request.Request(
+ f"{endpoint}/_ministack/config",
+ data=_json.dumps({
+ "nonexistent_module.VAR": "val",
+ "athena.ATHENA_ENGINE": "auto",
+ }).encode(),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ resp = _json.loads(urllib.request.urlopen(req, timeout=5).read())
+ assert "nonexistent_module.VAR" not in resp["applied"]
+ assert resp["applied"].get("athena.ATHENA_ENGINE") == "auto"
+
+
# ---------------------------------------------------------------------------
# RDS — edge cases
# ---------------------------------------------------------------------------
@@ -13324,8 +13546,8 @@ def test_alb_dataplane_forward_lambda(elbv2, lam):
def test_alb_dataplane_event_shape(elbv2, lam):
"""ALB event passed to Lambda contains all required fields."""
- import urllib.request as _req
import urllib.parse as _parse
+ import urllib.request as _req
fn_code = (
"import json\n"
@@ -13356,8 +13578,8 @@ def test_alb_dataplane_event_shape(elbv2, lam):
def test_alb_dataplane_fixed_response(elbv2, lam):
"""ALB fixed-response action returns configured status/body without invoking Lambda."""
- import urllib.request as _req
import urllib.error as _err
+ import urllib.request as _req
fn_code = "def handler(event, context):\n return {'statusCode': 200, 'body': 'should-not-reach'}\n"
lb_arn = elbv2.create_load_balancer(Name="dp-alb-fixed")["LoadBalancers"][0]["LoadBalancerArn"]
@@ -13501,8 +13723,8 @@ def test_alb_dataplane_path_pattern_rule(elbv2, lam):
def test_alb_dataplane_no_listener_returns_503(elbv2):
"""Request to an ALB with no listeners returns 503."""
- import urllib.request as _req
import urllib.error as _err
+ import urllib.request as _req
lb_arn = elbv2.create_load_balancer(Name="dp-alb-empty")["LoadBalancers"][0]["LoadBalancerArn"]
try: