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
release v1.3.21 (#532)
Nahuel Nucera7ded88fc8468
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7fde63f..0fb45cec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,13 +7,17 @@ Versioning follows [Semantic Versioning](https://semver.org/).----## [Unreleased]+## [1.3.21] — 2026-04-29### Added- **ElastiCache: real Redis replication groups + opt-in real Redis Cluster mode** — `CreateReplicationGroup` now spawns live Redis containers per shard (was a metadata-only stub). Behind `ELASTICACHE_CLUSTER_MODE_REAL=1` + `DOCKER_NETWORK`, `NumNodeGroups=N`/`ReplicasPerNodeGroup=R` provisions `N × (1+R)` cluster-enabled nodes, runs `redis-cli --cluster create`, and serves real `CLUSTER SLOTS` / `MOVED` redirects. `NumNodeGroups=2` rejected with `InvalidParameterValue` (matches AWS: only 1 or ≥3 shards). Account-scoped container names + `account_id` label so accounts can share `rg_id`; orphan-container reaper at startup. Reported by @akursar.### Fixed- **ElastiCache list responses wrapped items in `<member>` instead of the AWS-spec element name** — `DescribeCacheClusters` and 10 other list-emitting ops emitted `<member>` where AWS uses the model-declared `locationName` (e.g. `<CacheCluster>`, `<Tag>`, `<Snapshot>`). Strict generated SDKs (`aws-sdk-go-v2`, Java/Rust v2) parse a `<member>`-wrapped list as empty; botocore is permissive, so boto3 / CLI users never saw it. 16 sites fixed; the 5 remaining `<member>` sites (`UserList`, `UserGroupList`, `UserIdList`, etc.) match AWS. Verified against botocore service-2.json. Reported by @jmickey (#530).+- **RDS error codes carried a stale `Fault` suffix on two not-found shapes** — `DescribeDBInstances` (and 7 other DBInstance ops) emitted `<Code>DBInstanceNotFoundFault</Code>` while real AWS returns `<Code>DBInstanceNotFound</Code>`; `DescribeDBParameters` (and 9 other DBParameterGroup ops) emitted `<Code>DBParameterGroupNotFoundFault</Code>` while real AWS returns `<Code>DBParameterGroupNotFound</Code>`. Verified against `botocore/data/rds/2014-10-31/service-2.json` (the wire `error.code` differs from the shape name on ~19 RDS not-found errors — these two were the ones ministack emitted with the wrong wire code). Breaks string-matching consumers like the ACK RDS controller's `sdkFind`, which compares `awsErr.ErrorCode() == "DBInstanceNotFound"` to detect the not-found branch and reach the create path; with the `Fault` suffix the branch never matched and the CR sat at `Ready=False`. Also affects `aws-sdk-go-v2` (`smithy.APIError.ErrorCode()`) and any boto3 caller matching on `e.response["Error"]["Code"]`. Reported by @jmickey.+- **RDS error responses were missing `<Type>Sender</Type>` / `<Type>Receiver</Type>`** — real AWS Query-protocol error envelopes include the fault type alongside `<Code>` and `<Message>`. The `_error` helper now emits `Sender` for 4xx and `Receiver` for 5xx. Cosmetic for SDKs that read `<Code>` only, but completes the documented AWS shape.+- **API Gateway REST API (v1): pagination missing on 10 list operations** — `GetRestApis`, `GetResources`, `GetDeployments`, `GetAuthorizers`, `GetModels`, `GetApiKeys`, `GetUsagePlans`, `GetUsagePlanKeys`, `GetDomainNames`, and `GetBasePathMappings` ignored the AWS-spec `limit` (default 25, max 500) + `position` query params and always returned the full list with no `position` cursor. Pagination-aware SDKs that round-trip the cursor (boto3 paginators, AWS CLI `--max-items`/`--starting-token`, Java SDK v2) silently received the same first page on every call. The 10 ops now slice per `limit`, return an opaque base64url-encoded `position` token when more pages remain, and reject malformed tokens with `BadRequestException`. `GetStages` is correctly **not** paginated — its AWS shape has no `limit`/`position` fields.+- **API Gateway REST API (v1) `PutMethodResponse` and `PutIntegrationResponse` returned HTTP 200 instead of 201.** Real AWS returns 201 on resource creation (verified against `botocore/data/apigateway/2015-07-09/service-2.json`); the AWS CLI prints the resource on 201 and is silent on 200, so scripts that branched on stderr would diverge. The remaining v1 Create/Put ops already returned 201.---diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 809998e8..658cc293 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -68,6 +68,7 @@ Data plane:"""import asyncio+import base64import datetimeimport jsonimport logging@@ -162,6 +163,69 @@ def _v1_error(code, message, status):return status, {"Content-Type": "application/json"}, json.dumps({"message": message, "__type": code}, ensure_ascii=False).encode("utf-8")+def _qp(query_params, key, default=None):+ """Read a single query-param value. Callers pass either str or [str]."""+ v = query_params.get(key, default) if query_params else default+ if isinstance(v, list):+ return v[0] if v else default+ return v+++def _v1_paginate(items_list, query_params):+ """Slice a list per AWS API Gateway v1 pagination semantics.++ Returns ``(slice, next_position)``; ``next_position`` is ``None`` when+ the caller has reached the end. ``position`` is opaque to callers — we+ encode the next-index into a base64url JSON blob. Raises ``ValueError``+ if the caller supplies a malformed token.++ Default ``limit`` is 25, max 500 (AWS spec — see service-2.json input+ shapes for ``GetRestApis`` et al.).+ """+ limit_raw = _qp(query_params, "limit", "25")+ try:+ limit = int(limit_raw) if limit_raw is not None else 25+ except (TypeError, ValueError):+ limit = 25+ if limit < 1:+ limit = 1+ if limit > 500:+ limit = 500++ pos_raw = _qp(query_params, "position")+ start = 0+ if pos_raw:+ try:+ padding = "=" * (-len(pos_raw) % 4)+ decoded = json.loads(base64.urlsafe_b64decode(pos_raw + padding).decode("utf-8"))+ start = int(decoded["i"])+ except Exception:+ raise ValueError("Invalid position token")+ if start < 0:+ start = 0++ end = start + limit+ sliced = items_list[start:end]+ next_pos = None+ if end < len(items_list):+ token = json.dumps({"i": end}, separators=(",", ":")).encode("utf-8")+ next_pos = base64.urlsafe_b64encode(token).decode("ascii").rstrip("=")+ return sliced, next_pos+++def _v1_paginated_response(items_list, query_params):+ """Build a paginated v1 response. Returns the standard 200 tuple, or a+ 400 ``BadRequestException`` if the position token is malformed."""+ try:+ sliced, pos = _v1_paginate(items_list, query_params)+ except ValueError as e:+ return _v1_error("BadRequestException", str(e), 400)+ out = {"item": sliced}+ if pos is not None:+ out["position"] = pos+ return _v1_response(out)++def _rest_api_arn(api_id):return f"arn:aws:apigateway:{get_region()}::/restapis/{api_id}"@@ -561,7 +625,7 @@ async def handle_request(method, path, headers, body, query_params):key_id = parts[1] if len(parts) > 1 else Noneif not key_id:if method == "GET":- return _get_api_keys()+ return _get_api_keys(query_params)if method == "POST":return _create_api_key(data)else:@@ -578,13 +642,13 @@ async def handle_request(method, path, headers, body, query_params):sub_id = parts[3] if len(parts) > 3 else Noneif not plan_id:if method == "GET":- return _get_usage_plans()+ return _get_usage_plans(query_params)if method == "POST":return _create_usage_plan(data)elif sub == "keys":if not sub_id:if method == "GET":- return _get_usage_plan_keys(plan_id)+ return _get_usage_plan_keys(plan_id, query_params)if method == "POST":return _create_usage_plan_key(plan_id, data)else:@@ -604,14 +668,14 @@ async def handle_request(method, path, headers, body, query_params):sub_id = parts[3] if len(parts) > 3 else Noneif not domain_name:if method == "GET":- return _get_domain_names()+ return _get_domain_names(query_params)if method == "POST":return _create_domain_name(data)elif sub == "basepathmappings":base_path = sub_idif not base_path:if method == "GET":- return _get_base_path_mappings(domain_name)+ return _get_base_path_mappings(domain_name, query_params)if method == "POST":return _create_base_path_mapping(domain_name, data)else:@@ -631,7 +695,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST":return _create_rest_api(data)if method == "GET":- return _get_rest_apis()+ return _get_rest_apis(query_params)api_id = parts[1]@@ -657,7 +721,7 @@ async def handle_request(method, path, headers, body, query_params):if not resource_id:# GET /restapis/{id}/resourcesif method == "GET":- return _get_resources(api_id)+ return _get_resources(api_id, query_params)elif method_part is None:# /restapis/{id}/resources/{resourceId}@@ -730,7 +794,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST":return _create_deployment(api_id, data)if method == "GET":- return _get_deployments(api_id)+ return _get_deployments(api_id, query_params)else:if method == "GET":return _get_deployment(api_id, deployment_id)@@ -762,7 +826,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST":return _create_authorizer(api_id, data)if method == "GET":- return _get_authorizers(api_id)+ return _get_authorizers(api_id, query_params)else:if method == "GET":return _get_authorizer(api_id, auth_id)@@ -778,7 +842,7 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST":return _create_model(api_id, data)if method == "GET":- return _get_models(api_id)+ return _get_models(api_id, query_params)else:if method == "GET":return _get_model(api_id, model_name)@@ -1053,8 +1117,8 @@ def _get_rest_api(api_id):return _v1_response(_rest_api_view(api))-def _get_rest_apis():- return _v1_response({"item": [_rest_api_view(a) for a in _rest_apis.values()]})+def _get_rest_apis(query_params):+ return _v1_paginated_response([_rest_api_view(a) for a in _rest_apis.values()], query_params)def _update_rest_api(api_id, data):@@ -1081,10 +1145,10 @@ def _delete_rest_api(api_id):# ---- Control plane: Resources -----def _get_resources(api_id):+def _get_resources(api_id, query_params):if api_id not in _rest_apis:return _v1_error("NotFoundException", "Invalid API identifier specified", 404)- return _v1_response({"item": list(_resources.get(api_id, {}).values())})+ return _v1_paginated_response(list(_resources.get(api_id, {}).values()), query_params)def _get_resource(api_id, resource_id):@@ -1203,7 +1267,7 @@ def _put_method_response(api_id, resource_id, http_method, status_code, data):"responseModels": data.get("responseModels", {}),}method_obj["methodResponses"][status_code] = method_response- return _v1_response(method_response)+ return _v1_response(method_response, 201)def _get_method_response(api_id, resource_id, http_method, status_code):@@ -1320,7 +1384,7 @@ def _put_integration_response(api_id, resource_id, http_method, status_code, dat"contentHandling": data.get("contentHandling"),}integration["integrationResponses"][status_code] = int_response- return _v1_response(int_response)+ return _v1_response(int_response, 201)def _get_integration_response(api_id, resource_id, http_method, status_code):@@ -1408,10 +1472,10 @@ def _create_deployment(api_id, data):return _v1_response(deployment, 201)-def _get_deployments(api_id):+def _get_deployments(api_id, query_params):if api_id not in _rest_apis:return _v1_error("NotFoundException", "Invalid API identifier specified", 404)- return _v1_response({"item": list(_deployments_v1.get(api_id, {}).values())})+ return _v1_paginated_response(list(_deployments_v1.get(api_id, {}).values()), query_params)def _get_deployment(api_id, deployment_id):@@ -1515,10 +1579,10 @@ def _create_authorizer(api_id, data):return _v1_response(authorizer, 201)-def _get_authorizers(api_id):+def _get_authorizers(api_id, query_params):if api_id not in _rest_apis:return _v1_error("NotFoundException", "Invalid API identifier specified", 404)- return _v1_response({"item": list(_authorizers_v1.get(api_id, {}).values())})+ return _v1_paginated_response(list(_authorizers_v1.get(api_id, {}).values()), query_params)def _get_authorizer(api_id, auth_id):@@ -1563,10 +1627,10 @@ def _create_model(api_id, data):return _v1_response(model, 201)-def _get_models(api_id):+def _get_models(api_id, query_params):if api_id not in _rest_apis:return _v1_error("NotFoundException", "Invalid API identifier specified", 404)- return _v1_response({"item": list(_models.get(api_id, {}).values())})+ return _v1_paginated_response(list(_models.get(api_id, {}).values()), query_params)def _get_model(api_id, model_name):@@ -1603,8 +1667,8 @@ def _create_api_key(data):return _v1_response(api_key, 201)-def _get_api_keys():- return _v1_response({"item": list(_api_keys.values())})+def _get_api_keys(query_params):+ return _v1_paginated_response(list(_api_keys.values()), query_params)def _get_api_key(key_id):@@ -1649,8 +1713,8 @@ def _create_usage_plan(data):return _v1_response(plan, 201)-def _get_usage_plans():- return _v1_response({"item": list(_usage_plans.values())})+def _get_usage_plans(query_params):+ return _v1_paginated_response(list(_usage_plans.values()), query_params)def _get_usage_plan(plan_id):@@ -1692,10 +1756,10 @@ def _create_usage_plan_key(plan_id, data):return _v1_response(plan_key, 201)-def _get_usage_plan_keys(plan_id):+def _get_usage_plan_keys(plan_id, query_params):if plan_id not in _usage_plans:return _v1_error("NotFoundException", "Invalid Usage Plan identifier specified", 404)- return _v1_response({"item": list(_usage_plan_keys.get(plan_id, {}).values())})+ return _v1_paginated_response(list(_usage_plan_keys.get(plan_id, {}).values()), query_params)def _delete_usage_plan_key(plan_id, key_id):@@ -1726,8 +1790,8 @@ def _create_domain_name(data):return _v1_response(dn, 201)-def _get_domain_names():- return _v1_response({"item": list(_domain_names.values())})+def _get_domain_names(query_params):+ return _v1_paginated_response(list(_domain_names.values()), query_params)def _get_domain_name(domain_name):@@ -1758,10 +1822,10 @@ def _create_base_path_mapping(domain_name, data):return _v1_response(mapping, 201)-def _get_base_path_mappings(domain_name):+def _get_base_path_mappings(domain_name, query_params):if domain_name not in _domain_names:return _v1_error("NotFoundException", "Invalid domain name identifier specified", 404)- return _v1_response({"item": list(_base_path_mappings.get(domain_name, {}).values())})+ return _v1_paginated_response(list(_base_path_mappings.get(domain_name, {}).values()), query_params)def _get_base_path_mapping(domain_name, base_path):diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 3599f493..417ccfd2 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -546,7 +546,7 @@ def _delete_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)_unregister_instance_from_clusters(db_id)@@ -581,7 +581,7 @@ def _describe_db_instances(p):if db_id:instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instances = [instance]else:instances = list(_instances.values())@@ -652,7 +652,7 @@ def _modify_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)apply_immediately = _p(p, "ApplyImmediately") == "true"@@ -724,7 +724,7 @@ def _start_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instance["DBInstanceStatus"] = "available"return _single_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)@@ -733,7 +733,7 @@ def _stop_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instance["DBInstanceStatus"] = "stopped"return _single_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)@@ -742,7 +742,7 @@ def _reboot_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)instance["DBInstanceStatus"] = "available"return _single_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)@@ -757,7 +757,7 @@ def _create_read_replica(p):source = _resolve_instance(source_id)if not source:- return _error("DBInstanceNotFoundFault", f"DBInstance {source_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {source_id} not found.", 404)if replica_id in _instances:return _error("DBInstanceAlreadyExistsFault", f"DBInstance {replica_id} already exists.", 400)@@ -1112,7 +1112,7 @@ def _create_db_snapshot(p):instance = _resolve_instance(db_id)if not instance:- return _error("DBInstanceNotFoundFault", f"DBInstance {db_id} not found.", 404)+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)snap = _create_snapshot_internal(snap_id, instance)@@ -1255,7 +1255,7 @@ def _delete_param_group(p):name = _p(p, "DBParameterGroupName")pg = _param_groups.pop(name, None)if not pg:- return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ return _error("DBParameterGroupNotFound", f"Parameter group {name} not found.", 404)_tags.pop(pg.get("DBParameterGroupArn", ""), None)return _xml(200, "DeleteDBParameterGroupResponse", "")@@ -1265,7 +1265,7 @@ def _describe_param_groups(p):if name:pg = _param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ return _error("DBParameterGroupNotFound", f"Parameter group {name} not found.", 404)groups = [pg]else:groups = list(_param_groups.values())@@ -1284,7 +1284,7 @@ def _describe_db_parameters(p):name = _p(p, "DBParameterGroupName")pg = _param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ return _error("DBParameterGroupNotFound", f"Parameter group {name} not found.", 404)source_filter = _p(p, "Source") # "user", "engine-default", or None (all)@@ -1351,7 +1351,7 @@ def _modify_param_group(p):name = _p(p, "DBParameterGroupName")pg = _param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ return _error("DBParameterGroupNotFound", f"Parameter group {name} not found.", 404)params = pg.setdefault("Parameters", {})prefix = _parameter_member_prefix(p)@@ -1371,7 +1371,7 @@ def _reset_param_group(p):name = _p(p, "DBParameterGroupName")pg = _param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault", f"Parameter group {name} not found.", 404)+ return _error("DBParameterGroupNotFound", f"Parameter group {name} not found.", 404)params = pg.setdefault("Parameters", {})prefix = _parameter_member_prefix(p)@@ -1434,7 +1434,7 @@ def _describe_db_cluster_param_groups(p):if name:pg = _db_cluster_param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault",+ return _error("DBParameterGroupNotFound",f"DB cluster parameter group {name} not found.", 404)groups = [pg]else:@@ -1454,7 +1454,7 @@ def _delete_db_cluster_param_group(p):name = _p(p, "DBClusterParameterGroupName")pg = _db_cluster_param_groups.pop(name, None)if not pg:- return _error("DBParameterGroupNotFoundFault",+ return _error("DBParameterGroupNotFound",f"DB cluster parameter group {name} not found.", 404)_tags.pop(pg.get("DBClusterParameterGroupArn", ""), None)return _xml(200, "DeleteDBClusterParameterGroupResponse", "")@@ -1465,7 +1465,7 @@ def _describe_db_cluster_parameters(p):source_filter = _p(p, "Source")pg = _db_cluster_param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault",+ return _error("DBParameterGroupNotFound",f"DB cluster parameter group {name} not found.", 404)params = pg.get("Parameters", {})# When filtering by source, treat all stored params as "user" source.@@ -1496,7 +1496,7 @@ def _modify_db_cluster_param_group(p):name = _p(p, "DBClusterParameterGroupName")pg = _db_cluster_param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault",+ return _error("DBParameterGroupNotFound",f"DB cluster parameter group {name} not found.", 404)params = pg.setdefault("Parameters", {})@@ -1517,7 +1517,7 @@ def _reset_db_cluster_param_group(p):name = _p(p, "DBClusterParameterGroupName")pg = _db_cluster_param_groups.get(name)if not pg:- return _error("DBParameterGroupNotFoundFault",+ return _error("DBParameterGroupNotFound",f"DB cluster parameter group {name} not found.", 404)params = pg.setdefault("Parameters", {})@@ -2649,9 +2649,13 @@ def _xml(status, root_tag, inner):def _error(code, message, status):+ # Real AWS Query-protocol responses include <Type>Sender|Receiver</Type>+ # — Sender for 4xx (caller's fault), Receiver for 5xx. Most SDKs ignore+ # this field but it's part of the documented AWS shape.+ fault_type = "Sender" if 400 <= status < 500 else "Receiver"body = f"""<?xml version="1.0" encoding="UTF-8"?><ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">- <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <Error><Type>{fault_type}</Type><Code>{code}</Code><Message>{message}</Message></Error><RequestId>{new_uuid()}</RequestId></ErrorResponse>""".encode("utf-8")return status, {"Content-Type": "application/xml"}, bodydiff --git a/pyproject.toml b/pyproject.tomlindex 0f2567d5..34028ea3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.3.20"+version = "1.3.21"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/conftest.py b/tests/conftest.pyindex 87b32fbf..9b039c66 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -4,8 +4,8 @@ Pytest fixtures for MiniStack integration tests.import contextlibimport osimport socket-from urllib.parse import urlparseimport urllib.request+from urllib.parse import urlparseimport boto3import pytest@@ -59,12 +59,12 @@ _SERIAL_TESTS = {"tests/test_ministack.py::test_ministack_config_invalid_key_ignored","tests/test_ses.py::test_ses_messages_endpoint_reset","tests/test_ses.py::test_ses_messages_endpoint_account_filter",- "tests/test_sfn.py::test_sfn_mock_config_return",- "tests/test_sfn.py::test_sfn_mock_config_throw",- "tests/test_sfn.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",- "tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait",- "tests/test_rds_lambda_network.py::test_rds_lambda_network_connectivity",- "tests/test_elasticache_lambda_network.py::test_elasticache_lambda_network_connectivity",+ "tests/test_stepfunctions.py::test_sfn_mock_config_return",+ "tests/test_stepfunctions.py::test_sfn_mock_config_throw",+ "tests/test_stepfunctions.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",+ "tests/test_stepfunctions.py::test_sfn_wait_scale_zero_skips_wait",+ "tests/test_rds.py::test_rds_lambda_network_connectivity",+ "tests/test_elasticache.py::test_elasticache_lambda_network_connectivity",# API Gateway execute-api → Lambda invoke under tight urlopen / WS recv# timeouts. These pass cleanly when run serially but are sensitive to# xdist parallel load on shared CI runners (cold-start time bursts past@@ -260,10 +260,6 @@ def emr():def elbv2():return make_client("elbv2")[email protected](scope="session")-def ebs():- return make_client("ec2")-@pytest.fixture(scope="session")def efs():return make_client("efs")diff --git a/tests/test_acm.py b/tests/test_acm.pyindex 0405c55a..b9e56d23 100644--- a/tests/test_acm.py+++ b/tests/test_acm.py@@ -108,3 +108,363 @@ def test_acm_resend_validation_email(acm_client):desc = acm_client.describe_certificate(CertificateArn=arn)assert desc["Certificate"]["DomainName"] == "resend.example.com"acm_client.delete_certificate(CertificateArn=arn)+++# ========== from test_acm_cert_body.py ==========+# Regression tests for ACM cert body fidelity (H-7 + M-7) and+# private-key persistence leak prevention.+TEST_CERT_PEM = (+ b"-----BEGIN CERTIFICATE-----\n"+ b"MIIB7TCCAVagAwIBAgIUR0Yc4xRoundTripTestCert1234567890wDQYJKoZIhvc\n"+ b"NAQELBQAwEjEQMA4GA1UEAwwHdGVzdGluZzAeFw0yNjAxMDEwMDAwMDBaFw0yNzAx\n"+ b"MDEwMDAwMDBaMBIxEDAOBgNVBAMMB3Rlc3RpbmcwgZ8wDQYJKoZIhvcNAQEBBQAD\n"+ b"-----END CERTIFICATE-----\n"+)+TEST_CHAIN_PEM = (+ b"-----BEGIN CERTIFICATE-----\n"+ b"MIIB7TCCAVagAwIBAgIUR0Yc4xRoundTripTestChain123456789wDQYJKoZIhv\n"+ b"NAQELBQAwEjEQMA4GA1UEAwwHdGVzdGluZzAeFw0yNjAxMDEwMDAwMDBaFw0yNzAx\n"+ b"-----END CERTIFICATE-----\n"+)+TEST_PRIVATE_KEY_PEM = (+ b"-----BEGIN PRIVATE KEY-----\n"+ b"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0IamGfakeKey1\n"+ b"-----END PRIVATE KEY-----\n"+)+++# ── H-7: GetCertificate returns the stored PEM, not a literal ─────────++def test_import_then_get_returns_supplied_certificate_body(acm_client):+ """ImportCertificate must store the Certificate bytes; GetCertificate+ must return the stored bytes verbatim. Without the fix, GetCertificate+ returned a hard-coded literal containing 'MIIFakeCertificateDataHere'."""+ acm = acm_client+ resp = acm.import_certificate(+ Certificate=TEST_CERT_PEM,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ arn = resp["CertificateArn"]++ got = acm.get_certificate(CertificateArn=arn)+ assert got["Certificate"] == TEST_CERT_PEM.decode(), (+ "GetCertificate did not return the imported Certificate body — "+ "ACM emulator is silently fabricating PEM data, breaking any "+ "consumer that parses or validates the cert."+ )++ # Defensive: the literal placeholder must not leak.+ assert "MIIFakeCertificateDataHere" not in got["Certificate"]+ assert "MIIFakeChainDataHere" not in got.get("CertificateChain", "")+++def test_import_then_get_returns_supplied_chain(acm_client):+ """ImportCertificate's CertificateChain must round-trip through+ GetCertificate."""+ acm = acm_client+ resp = acm.import_certificate(+ Certificate=TEST_CERT_PEM,+ CertificateChain=TEST_CHAIN_PEM,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ arn = resp["CertificateArn"]++ got = acm.get_certificate(CertificateArn=arn)+ assert got["CertificateChain"] == TEST_CHAIN_PEM.decode(), (+ "GetCertificate did not return the imported CertificateChain."+ )+++def test_get_certificate_omits_private_key(acm_client):+ """Real AWS GetCertificate never returns the private key (security).+ The emulator must match this behaviour even though it stores it+ internally for round-trip fidelity."""+ acm = acm_client+ resp = acm.import_certificate(+ Certificate=TEST_CERT_PEM,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ arn = resp["CertificateArn"]++ got = acm.get_certificate(CertificateArn=arn)+ assert "PrivateKey" not in got, (+ "GetCertificate response leaked the private key — real AWS "+ "ACM never returns the PrivateKey via GetCertificate, only via "+ "ExportCertificate (which requires a passphrase)."+ )+++# ── M-7: ImportCertificate must not lie about the domain ──────────────++def test_imported_certificate_does_not_lie_about_domain(acm_client):+ """Real AWS parses DomainName / SubjectAlternativeNames from the+ cert's CN/SAN extensions. The emulator does not implement X.509+ parsing (out of scope), so it MUST NOT advertise a fabricated+ 'imported.example.com' that bears no relation to the actual cert.++ Acceptable behaviour for an emulator without ASN.1 parsing:+ - Return an empty / null DomainName, OR+ - Return a placeholder that is clearly synthetic (contains the+ cert ARN, says 'unknown', etc.), OR+ - Echo a DomainName supplied via tags (escape hatch).++ Returning the literal "imported.example.com" misleads CDK /+ Terraform plans into believing the cert covers a domain it does+ not."""+ acm = acm_client+ resp = acm.import_certificate(+ Certificate=TEST_CERT_PEM,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ arn = resp["CertificateArn"]++ desc = acm.describe_certificate(CertificateArn=arn)["Certificate"]+ assert desc["DomainName"] != "imported.example.com", (+ "ImportCertificate emitted DomainName='imported.example.com' "+ "regardless of input — that's a fabricated domain that misleads "+ "consumers. Either parse from the cert, leave empty, or use a "+ "synthetic placeholder."+ )+++def test_re_import_preserves_arn_and_replaces_body(acm_client):+ """When CertificateArn is supplied to ImportCertificate, the cert+ body is replaced in-place (real AWS semantics for cert renewal).+ Without H-7's fix this test would still pass against literal data+ so it's a sanity-check of the new path."""+ acm = acm_client+ first = acm.import_certificate(+ Certificate=TEST_CERT_PEM,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ arn = first["CertificateArn"]++ new_cert = TEST_CERT_PEM.replace(b"RoundTripTestCert", b"ReimportRoundTrip")+ second = acm.import_certificate(+ CertificateArn=arn,+ Certificate=new_cert,+ PrivateKey=TEST_PRIVATE_KEY_PEM,+ )+ assert second["CertificateArn"] == arn, (+ "Re-import with explicit CertificateArn should preserve the ARN."+ )++ got = acm.get_certificate(CertificateArn=arn)+ assert got["Certificate"] == new_cert.decode()+++# ── PrivateKey persistence leak (in-process, not through the live server) ─++def test_get_state_strips_private_key_from_persisted_snapshot():+ """Private keys must not be written to ${STATE_DIR}/acm.json. Real+ AWS only exposes them via passphrase-protected ExportCertificate;+ the GetCertificate wire path already honours that. Persistence must+ not become a side-channel for material the wire refuses to leak.++ Calls the module's `get_state()` directly — the snapshot it returns+ is exactly what `core/persistence.save_state` would JSON-encode to+ disk, so anything in there ends up readable on the filesystem."""+ import importlib+ import json++ from ministack.core.persistence import _json_default+ from ministack.core.responses import _request_account_id+ mod = importlib.import_module("ministack.services.acm")+ mod._certificates._data.clear() # belt-and-braces++ # Two tenants — the request-scoped iteration would only see one of+ # them. Both must be scrubbed in the snapshot AND in the+ # production-encoder JSON blob.+ arn_a = "arn:aws:acm:us-east-1:000000000000:certificate/leak-check-a"+ arn_b = "arn:aws:acm:us-east-1:111111111111:certificate/leak-check-b"+ secret_a = "-----BEGIN PRIVATE KEY-----\nVERY_SECRET_KEY_TENANT_A\n-----END PRIVATE KEY-----\n"+ secret_b = "-----BEGIN PRIVATE KEY-----\nVERY_SECRET_KEY_TENANT_B\n-----END PRIVATE KEY-----\n"++ token_a = _request_account_id.set("000000000000")+ mod._certificates[arn_a] = {+ "CertificateArn": arn_a,+ "DomainName": "leak-check-a.invalid",+ "Status": "ISSUED",+ "Type": "IMPORTED",+ "_pem_body": "-----BEGIN CERTIFICATE-----\nBODY\n-----END CERTIFICATE-----\n",+ "_pem_chain": "",+ "_private_key": secret_a,+ }+ _request_account_id.reset(token_a)++ token_b = _request_account_id.set("111111111111")+ mod._certificates[arn_b] = {+ "CertificateArn": arn_b,+ "DomainName": "leak-check-b.invalid",+ "Status": "ISSUED",+ "Type": "IMPORTED",+ "_pem_body": "-----BEGIN CERTIFICATE-----\nBODY\n-----END CERTIFICATE-----\n",+ "_pem_chain": "",+ "_private_key": secret_b,+ }+ _request_account_id.reset(token_b)++ snapshot = mod.get_state()++ # Both tenants must have _private_key stripped — using _data so we+ # see all accounts, not just the request-scoped one.+ for cert in snapshot["_certificates"]._data.values():+ assert "_private_key" not in cert, (+ "PrivateKey leaked into the persistence snapshot — get_state() "+ "must scrub it for ALL tenants before save_state writes "+ "plaintext JSON to disk."+ )+ assert cert["_pem_body"].startswith("-----BEGIN CERTIFICATE-----")++ # Defensive: round-trip via the actual production encoder (used by+ # save_state) — `default=str` was request-scoped via __repr__ and+ # missed cross-tenant data.+ blob = json.dumps(snapshot, default=_json_default)+ assert "VERY_SECRET_KEY_TENANT_A" not in blob, (+ "Tenant A private-key material found in JSON-serialised "+ "snapshot — would be written verbatim to ${STATE_DIR}/acm.json."+ )+ assert "VERY_SECRET_KEY_TENANT_B" not in blob, (+ "Tenant B private-key material found in JSON-serialised "+ "snapshot — get_state() must scrub all tenants."+ )++ # Restoring the scrubbed snapshot must not crash and must preserve+ # both tenants' certs (minus the private keys).+ mod._certificates._data.clear()+ mod.restore_state(snapshot)+ restored_arns = {cert["CertificateArn"] for cert in mod._certificates._data.values()}+ assert arn_a in restored_arns+ assert arn_b in restored_arns+ mod._certificates._data.clear()+++def test_get_state_preserves_certs_across_all_tenants():+ """get_state() must persist every tenant's certificates, not just+ the current request's account. Iterating `_certificates.items()`+ is request-scoped via AccountScopedDict's contextvar; iterating+ `_certificates._data` captures all (account_id, key) pairs."""+ import importlib++ from ministack.core.responses import _request_account_id+ mod = importlib.import_module("ministack.services.acm")+ mod.reset() if hasattr(mod, "reset") else None+ mod._certificates._data.clear() # belt-and-braces++ # Pretend we're tenant A and write a cert.+ token_a = _request_account_id.set("111111111111")+ arn_a = "arn:aws:acm:us-east-1:111111111111:certificate/tenant-a"+ mod._certificates[arn_a] = {"CertificateArn": arn_a, "_pem_body": "a"}+ _request_account_id.reset(token_a)++ # Switch to tenant B and write another.+ token_b = _request_account_id.set("222222222222")+ arn_b = "arn:aws:acm:us-east-1:222222222222:certificate/tenant-b"+ mod._certificates[arn_b] = {"CertificateArn": arn_b, "_pem_body": "b"}+ _request_account_id.reset(token_b)++ # Snapshot from tenant B's request scope (worst case).+ token = _request_account_id.set("222222222222")+ snapshot = mod.get_state()+ _request_account_id.reset(token)++ persisted = snapshot["_certificates"]+ raw_keys = list(persisted._data.keys())+ accounts_persisted = {acct for acct, _ in raw_keys}+ assert accounts_persisted == {"111111111111", "222222222222"}, (+ "get_state() dropped a tenant's certs from the snapshot — only "+ f"persisted accounts: {accounts_persisted}. AccountScopedDict.items() "+ "is request-scoped; iterating _data is required to capture all "+ "tenants."+ )+ mod._certificates._data.clear()+++def test_restore_state_backfills_pem_body_for_pre_upgrade_snapshots():+ """Pre-fix `acm.json` snapshots have no `_pem_body` / `_pem_chain`+ keys (the old GetCertificate path returned a hard-coded literal+ regardless of stored data). Without backfill in restore_state,+ those certs would return an empty Certificate field after+ warm-boot — strictly worse than the old behaviour. Backfill must+ fill them with the synthetic placeholder so consumers that+ substring-check 'BEGIN CERTIFICATE' (Terraform / CDK) keep+ working."""+ import importlib+ mod = importlib.import_module("ministack.services.acm")+ mod._certificates._data.clear()++ arn = "arn:aws:acm:us-east-1:000000000000:certificate/legacy-cert"+ legacy_snapshot = {+ "_certificates": {+ arn: {+ "CertificateArn": arn,+ "DomainName": "legacy.example.com",+ "Status": "ISSUED",+ "Type": "AMAZON_ISSUED",+ # Note: no _pem_body, no _pem_chain — pre-upgrade shape.+ },+ },+ }+ mod.restore_state(legacy_snapshot)++ # _get_certificate hits the restored record and reads _pem_body.+ cert = mod._certificates.get(arn)+ assert cert is not None, "Restore failed — cert not in dict."+ assert "_pem_body" in cert, (+ "restore_state did not backfill _pem_body — pre-upgrade "+ "GetCertificate would return an empty Certificate field."+ )+ assert "BEGIN CERTIFICATE" in cert["_pem_body"]+ assert cert.get("_pem_chain") == ""+ mod._certificates._data.clear()+++def test_synthetic_pem_body_is_valid_base64():+ """The placeholder PEM body issued by RequestCertificate must be+ valid base64 — consumers that pre-decode (PyOpenSSL,+ cryptography) error before they reach ASN.1 parsing if it isn't."""+ import base64+ import importlib+ mod = importlib.import_module("ministack.services.acm")+ pem = mod._synthetic_pem("anything.example.com")+ body_lines = [+ line for line in pem.splitlines()+ if line and not line.startswith("-----")+ ]+ body = "".join(body_lines)+ # Must base64-decode without raising (binascii.Error otherwise).+ decoded = base64.b64decode(body)+ assert isinstance(decoded, bytes)+ assert len(decoded) > 0+++# ========== from test_misc_medium_low_fixes.py ==========+# ListCertificates wire response must omit NextToken when there's no next+# page. boto3 strips nulls client-side so a boto3-only test can't see this,+# but Java/Go SDKs and pagination loops checking `if "NextToken" in resp`+# loop forever against a literal null. Asserted at the raw-HTTP level.++import urllib.request as _acm_urlreq++_ACM_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+++def test_acm_list_certificates_omits_nexttoken_when_no_more_pages():+ req = _acm_urlreq.Request(+ _ACM_ENDPOINT.rstrip("/") + "/",+ method="POST",+ headers={+ "x-amz-target": "CertificateManager.ListCertificates",+ "Content-Type": "application/x-amz-json-1.1",+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/x/us-east-1/acm/aws4_request",+ },+ data=b"{}",+ )+ body = json.loads(_acm_urlreq.urlopen(req, timeout=5).read())++ assert "NextToken" not in body, (+ f"ListCertificates wire response contains NextToken when there is "+ f"no next page (got {body.get('NextToken')!r}). Real AWS omits the "+ "key. SDK consumers checking `if 'NextToken' in response` "+ "(Java, Go, raw HTTP — boto3 strips nulls) loop forever."+ )diff --git a/tests/test_acm_cert_body.py b/tests/test_acm_cert_body.pydeleted file mode 100644index 63747429..00000000--- a/tests/test_acm_cert_body.py+++ /dev/null@@ -1,347 +0,0 @@-"""-Regression tests for ACM cert body fidelity (H-7 + M-7).--Bug H-7 acm._get_certificate returned a hard-coded literal PEM- ("MIIFakeCertificateDataHere") regardless of what was stored.- Any consumer that parses the PEM (mTLS validators, ALB- attachment, X.509 validators) gets structurally invalid data.--Bug M-7 acm._import_certificate discarded the Certificate /- CertificateChain / PrivateKey fields from the request entirely.- It also hard-coded DomainName="imported.example.com" instead- of either parsing it from the cert (out of scope) or at least- not lying about its provenance.--These tests use boto3 against the running ministack server (matches-the existing tests/test_acm.py style).-"""-# Uses the session-scoped `acm_client` fixture from tests/conftest.py-# (matches the established convention in tests/test_acm.py).---# A minimal but well-formed PEM body — pure data round-trip; no actual-# X.509 parsing happens in either ministack or in these tests, so a-# plausible-looking string suffices.-TEST_CERT_PEM = (- b"-----BEGIN CERTIFICATE-----\n"- b"MIIB7TCCAVagAwIBAgIUR0Yc4xRoundTripTestCert1234567890wDQYJKoZIhvc\n"- b"NAQELBQAwEjEQMA4GA1UEAwwHdGVzdGluZzAeFw0yNjAxMDEwMDAwMDBaFw0yNzAx\n"- b"MDEwMDAwMDBaMBIxEDAOBgNVBAMMB3Rlc3RpbmcwgZ8wDQYJKoZIhvcNAQEBBQAD\n"- b"-----END CERTIFICATE-----\n"-)-TEST_CHAIN_PEM = (- b"-----BEGIN CERTIFICATE-----\n"- b"MIIB7TCCAVagAwIBAgIUR0Yc4xRoundTripTestChain123456789wDQYJKoZIhv\n"- b"NAQELBQAwEjEQMA4GA1UEAwwHdGVzdGluZzAeFw0yNjAxMDEwMDAwMDBaFw0yNzAx\n"- b"-----END CERTIFICATE-----\n"-)-TEST_PRIVATE_KEY_PEM = (- b"-----BEGIN PRIVATE KEY-----\n"- b"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0IamGfakeKey1\n"- b"-----END PRIVATE KEY-----\n"-)---# ── H-7: GetCertificate returns the stored PEM, not a literal ─────────--def test_import_then_get_returns_supplied_certificate_body(acm_client):- """ImportCertificate must store the Certificate bytes; GetCertificate- must return the stored bytes verbatim. Without the fix, GetCertificate- returned a hard-coded literal containing 'MIIFakeCertificateDataHere'."""- acm = acm_client- resp = acm.import_certificate(- Certificate=TEST_CERT_PEM,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- arn = resp["CertificateArn"]-- got = acm.get_certificate(CertificateArn=arn)- assert got["Certificate"] == TEST_CERT_PEM.decode(), (- "GetCertificate did not return the imported Certificate body — "- "ACM emulator is silently fabricating PEM data, breaking any "- "consumer that parses or validates the cert."- )-- # Defensive: the literal placeholder must not leak.- assert "MIIFakeCertificateDataHere" not in got["Certificate"]- assert "MIIFakeChainDataHere" not in got.get("CertificateChain", "")---def test_import_then_get_returns_supplied_chain(acm_client):- """ImportCertificate's CertificateChain must round-trip through- GetCertificate."""- acm = acm_client- resp = acm.import_certificate(- Certificate=TEST_CERT_PEM,- CertificateChain=TEST_CHAIN_PEM,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- arn = resp["CertificateArn"]-- got = acm.get_certificate(CertificateArn=arn)- assert got["CertificateChain"] == TEST_CHAIN_PEM.decode(), (- "GetCertificate did not return the imported CertificateChain."- )---def test_get_certificate_omits_private_key(acm_client):- """Real AWS GetCertificate never returns the private key (security).- The emulator must match this behaviour even though it stores it- internally for round-trip fidelity."""- acm = acm_client- resp = acm.import_certificate(- Certificate=TEST_CERT_PEM,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- arn = resp["CertificateArn"]-- got = acm.get_certificate(CertificateArn=arn)- assert "PrivateKey" not in got, (- "GetCertificate response leaked the private key — real AWS "- "ACM never returns the PrivateKey via GetCertificate, only via "- "ExportCertificate (which requires a passphrase)."- )---# ── M-7: ImportCertificate must not lie about the domain ──────────────--def test_imported_certificate_does_not_lie_about_domain(acm_client):- """Real AWS parses DomainName / SubjectAlternativeNames from the- cert's CN/SAN extensions. The emulator does not implement X.509- parsing (out of scope), so it MUST NOT advertise a fabricated- 'imported.example.com' that bears no relation to the actual cert.-- Acceptable behaviour for an emulator without ASN.1 parsing:- - Return an empty / null DomainName, OR- - Return a placeholder that is clearly synthetic (contains the- cert ARN, says 'unknown', etc.), OR- - Echo a DomainName supplied via tags (escape hatch).-- Returning the literal "imported.example.com" misleads CDK /- Terraform plans into believing the cert covers a domain it does- not."""- acm = acm_client- resp = acm.import_certificate(- Certificate=TEST_CERT_PEM,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- arn = resp["CertificateArn"]-- desc = acm.describe_certificate(CertificateArn=arn)["Certificate"]- assert desc["DomainName"] != "imported.example.com", (- "ImportCertificate emitted DomainName='imported.example.com' "- "regardless of input — that's a fabricated domain that misleads "- "consumers. Either parse from the cert, leave empty, or use a "- "synthetic placeholder."- )---def test_re_import_preserves_arn_and_replaces_body(acm_client):- """When CertificateArn is supplied to ImportCertificate, the cert- body is replaced in-place (real AWS semantics for cert renewal).- Without H-7's fix this test would still pass against literal data- so it's a sanity-check of the new path."""- acm = acm_client- first = acm.import_certificate(- Certificate=TEST_CERT_PEM,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- arn = first["CertificateArn"]-- new_cert = TEST_CERT_PEM.replace(b"RoundTripTestCert", b"ReimportRoundTrip")- second = acm.import_certificate(- CertificateArn=arn,- Certificate=new_cert,- PrivateKey=TEST_PRIVATE_KEY_PEM,- )- assert second["CertificateArn"] == arn, (- "Re-import with explicit CertificateArn should preserve the ARN."- )-- got = acm.get_certificate(CertificateArn=arn)- assert got["Certificate"] == new_cert.decode()---# ── PrivateKey persistence leak (in-process, not through the live server) ─--def test_get_state_strips_private_key_from_persisted_snapshot():- """Private keys must not be written to ${STATE_DIR}/acm.json. Real- AWS only exposes them via passphrase-protected ExportCertificate;- the GetCertificate wire path already honours that. Persistence must- not become a side-channel for material the wire refuses to leak.-- Calls the module's `get_state()` directly — the snapshot it returns- is exactly what `core/persistence.save_state` would JSON-encode to- disk, so anything in there ends up readable on the filesystem."""- import importlib- import json-- from ministack.core.persistence import _json_default- from ministack.core.responses import _request_account_id- mod = importlib.import_module("ministack.services.acm")- mod._certificates._data.clear() # belt-and-braces-- # Two tenants — the request-scoped iteration would only see one of- # them. Both must be scrubbed in the snapshot AND in the- # production-encoder JSON blob.- arn_a = "arn:aws:acm:us-east-1:000000000000:certificate/leak-check-a"- arn_b = "arn:aws:acm:us-east-1:111111111111:certificate/leak-check-b"- secret_a = "-----BEGIN PRIVATE KEY-----\nVERY_SECRET_KEY_TENANT_A\n-----END PRIVATE KEY-----\n"- secret_b = "-----BEGIN PRIVATE KEY-----\nVERY_SECRET_KEY_TENANT_B\n-----END PRIVATE KEY-----\n"-- token_a = _request_account_id.set("000000000000")- mod._certificates[arn_a] = {- "CertificateArn": arn_a,- "DomainName": "leak-check-a.invalid",- "Status": "ISSUED",- "Type": "IMPORTED",- "_pem_body": "-----BEGIN CERTIFICATE-----\nBODY\n-----END CERTIFICATE-----\n",- "_pem_chain": "",- "_private_key": secret_a,- }- _request_account_id.reset(token_a)-- token_b = _request_account_id.set("111111111111")- mod._certificates[arn_b] = {- "CertificateArn": arn_b,- "DomainName": "leak-check-b.invalid",- "Status": "ISSUED",- "Type": "IMPORTED",- "_pem_body": "-----BEGIN CERTIFICATE-----\nBODY\n-----END CERTIFICATE-----\n",- "_pem_chain": "",- "_private_key": secret_b,- }- _request_account_id.reset(token_b)-- snapshot = mod.get_state()-- # Both tenants must have _private_key stripped — using _data so we- # see all accounts, not just the request-scoped one.- for cert in snapshot["_certificates"]._data.values():- assert "_private_key" not in cert, (- "PrivateKey leaked into the persistence snapshot — get_state() "- "must scrub it for ALL tenants before save_state writes "- "plaintext JSON to disk."- )- assert cert["_pem_body"].startswith("-----BEGIN CERTIFICATE-----")-- # Defensive: round-trip via the actual production encoder (used by- # save_state) — `default=str` was request-scoped via __repr__ and- # missed cross-tenant data.- blob = json.dumps(snapshot, default=_json_default)- assert "VERY_SECRET_KEY_TENANT_A" not in blob, (- "Tenant A private-key material found in JSON-serialised "- "snapshot — would be written verbatim to ${STATE_DIR}/acm.json."- )- assert "VERY_SECRET_KEY_TENANT_B" not in blob, (- "Tenant B private-key material found in JSON-serialised "- "snapshot — get_state() must scrub all tenants."- )-- # Restoring the scrubbed snapshot must not crash and must preserve- # both tenants' certs (minus the private keys).- mod._certificates._data.clear()- mod.restore_state(snapshot)- restored_arns = {cert["CertificateArn"] for cert in mod._certificates._data.values()}- assert arn_a in restored_arns- assert arn_b in restored_arns- mod._certificates._data.clear()---def test_get_state_preserves_certs_across_all_tenants():- """get_state() must persist every tenant's certificates, not just- the current request's account. Iterating `_certificates.items()`- is request-scoped via AccountScopedDict's contextvar; iterating- `_certificates._data` captures all (account_id, key) pairs."""- import importlib-- from ministack.core.responses import _request_account_id- mod = importlib.import_module("ministack.services.acm")- mod.reset() if hasattr(mod, "reset") else None- mod._certificates._data.clear() # belt-and-braces-- # Pretend we're tenant A and write a cert.- token_a = _request_account_id.set("111111111111")- arn_a = "arn:aws:acm:us-east-1:111111111111:certificate/tenant-a"- mod._certificates[arn_a] = {"CertificateArn": arn_a, "_pem_body": "a"}- _request_account_id.reset(token_a)-- # Switch to tenant B and write another.- token_b = _request_account_id.set("222222222222")- arn_b = "arn:aws:acm:us-east-1:222222222222:certificate/tenant-b"- mod._certificates[arn_b] = {"CertificateArn": arn_b, "_pem_body": "b"}- _request_account_id.reset(token_b)-- # Snapshot from tenant B's request scope (worst case).- token = _request_account_id.set("222222222222")- snapshot = mod.get_state()- _request_account_id.reset(token)-- persisted = snapshot["_certificates"]- raw_keys = list(persisted._data.keys())- accounts_persisted = {acct for acct, _ in raw_keys}- assert accounts_persisted == {"111111111111", "222222222222"}, (- "get_state() dropped a tenant's certs from the snapshot — only "- f"persisted accounts: {accounts_persisted}. AccountScopedDict.items() "- "is request-scoped; iterating _data is required to capture all "- "tenants."- )- mod._certificates._data.clear()---def test_restore_state_backfills_pem_body_for_pre_upgrade_snapshots():- """Pre-fix `acm.json` snapshots have no `_pem_body` / `_pem_chain`- keys (the old GetCertificate path returned a hard-coded literal- regardless of stored data). Without backfill in restore_state,- those certs would return an empty Certificate field after- warm-boot — strictly worse than the old behaviour. Backfill must- fill them with the synthetic placeholder so consumers that- substring-check 'BEGIN CERTIFICATE' (Terraform / CDK) keep- working."""- import importlib- mod = importlib.import_module("ministack.services.acm")- mod._certificates._data.clear()-- arn = "arn:aws:acm:us-east-1:000000000000:certificate/legacy-cert"- legacy_snapshot = {- "_certificates": {- arn: {- "CertificateArn": arn,- "DomainName": "legacy.example.com",- "Status": "ISSUED",- "Type": "AMAZON_ISSUED",- # Note: no _pem_body, no _pem_chain — pre-upgrade shape.- },- },- }- mod.restore_state(legacy_snapshot)-- # _get_certificate hits the restored record and reads _pem_body.- cert = mod._certificates.get(arn)- assert cert is not None, "Restore failed — cert not in dict."- assert "_pem_body" in cert, (- "restore_state did not backfill _pem_body — pre-upgrade "- "GetCertificate would return an empty Certificate field."- )- assert "BEGIN CERTIFICATE" in cert["_pem_body"]- assert cert.get("_pem_chain") == ""- mod._certificates._data.clear()---def test_synthetic_pem_body_is_valid_base64():- """The placeholder PEM body issued by RequestCertificate must be- valid base64 — consumers that pre-decode (PyOpenSSL,- cryptography) error before they reach ASN.1 parsing if it isn't."""- import base64- import importlib- mod = importlib.import_module("ministack.services.acm")- pem = mod._synthetic_pem("anything.example.com")- body_lines = [- line for line in pem.splitlines()- if line and not line.startswith("-----")- ]- body = "".join(body_lines)- # Must base64-decode without raising (binascii.Error otherwise).- decoded = base64.b64decode(body)- assert isinstance(decoded, bytes)- assert len(decoded) > 0diff --git a/tests/test_elbv2.py b/tests/test_alb.pysimilarity index 100%rename from tests/test_elbv2.pyrename to tests/test_alb.pydiff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 3e4a883f..0a3babde 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -1426,3 +1426,162 @@ def test_apigwv1_lambda_proxy_emits_cloudwatch_logs_nodejs(apigw_v1, lam, logs):apigw_v1.delete_rest_api(restApiId=api_id)lam.delete_function(FunctionName=fname)+++# ========== from test_apigatewayv1_content_handling.py ==========+# Regression tests for API Gateway v1 (REST API) ContentHandling fidelity.+# H-8: PutIntegration was dropping contentHandling (same family as #439 for v2).+# M-6: PutIntegrationResponse pin (already fixed; pinned here so it stays fixed).+++def method_setup(apigw_v1):+ """Create a fresh REST API + resource + method as a foundation for+ integration tests. Yields (api_id, resource_id, http_method) and+ deletes the REST API in teardown so the session-scoped client+ doesn't leak state across tests."""+ api = apigw_v1.create_rest_api(name="ch-test-api")+ api_id = api["id"]+ root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ res = apigw_v1.create_resource(+ restApiId=api_id, parentId=root_id, pathPart="ch",+ )+ resource_id = res["id"]+ apigw_v1.put_method(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod="POST",+ authorizationType="NONE",+ )+ apigw_v1.put_method_response(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod="POST",+ statusCode="200",+ )+ try:+ yield api_id, resource_id, "POST"+ finally:+ try:+ apigw_v1.delete_rest_api(restApiId=api_id)+ except Exception:+ pass+++# ── H-8: PutIntegration / GetIntegration round-trip ───────────────────+[email protected]("ch_value", ["CONVERT_TO_TEXT", "CONVERT_TO_BINARY"])+def test_put_integration_persists_content_handling(apigw_v1, method_setup, ch_value):+ """PutIntegration accepting `contentHandling` must store the value+ so subsequent GetIntegration returns it. Without the fix, the field+ was silently dropped — breaking Terraform's+ `aws_api_gateway_integration.content_handling` round-trip."""+ api_id, resource_id, method = method_setup+ apigw_v1.put_integration(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ type="HTTP",+ integrationHttpMethod="POST",+ uri="https://httpbin.org/anything",+ contentHandling=ch_value,+ )++ got = apigw_v1.get_integration(+ restApiId=api_id, resourceId=resource_id, httpMethod=method,+ )+ assert got.get("contentHandling") == ch_value, (+ f"PutIntegration silently dropped contentHandling={ch_value!r}; "+ "GetIntegration returned: " + repr(got.get("contentHandling"))+ )+++def test_put_integration_omits_content_handling_when_not_set(apigw_v1, method_setup):+ """When the caller does NOT pass contentHandling, the response must+ not invent one. Real AWS omits the field; some boto3-driven+ Terraform plans diff against an emulator that returns an empty+ string or other default."""+ api_id, resource_id, method = method_setup+ apigw_v1.put_integration(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ type="HTTP",+ integrationHttpMethod="POST",+ uri="https://httpbin.org/anything",+ )++ got = apigw_v1.get_integration(+ restApiId=api_id, resourceId=resource_id, httpMethod=method,+ )+ # Either the key is absent or its value is None/null (boto3 strips+ # null fields). Anything else (empty string, "NONE") would be a+ # fabricated value that misleads consumers.+ assert got.get("contentHandling") in (None, ), (+ "GetIntegration returned a fabricated contentHandling value "+ f"{got.get('contentHandling')!r} when none was set."+ )+++def test_update_integration_can_patch_content_handling(apigw_v1, method_setup):+ """Terraform's apply path uses UpdateIntegration with a JSON Patch+ op (`replace /contentHandling`). The updated contentHandling value+ must persist and be returned by GetIntegration."""+ api_id, resource_id, method = method_setup+ apigw_v1.put_integration(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ type="HTTP",+ integrationHttpMethod="POST",+ uri="https://httpbin.org/anything",+ contentHandling="CONVERT_TO_TEXT",+ )+ apigw_v1.update_integration(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ patchOperations=[+ {"op": "replace", "path": "/contentHandling", "value": "CONVERT_TO_BINARY"},+ ],+ )++ got = apigw_v1.get_integration(+ restApiId=api_id, resourceId=resource_id, httpMethod=method,+ )+ assert got.get("contentHandling") == "CONVERT_TO_BINARY"+++# ── M-6 regression lock: PutIntegrationResponse still works ───────────+[email protected]("ch_value", ["CONVERT_TO_TEXT", "CONVERT_TO_BINARY"])+def test_put_integration_response_persists_content_handling(apigw_v1, method_setup, ch_value):+ """PutIntegrationResponse persisting `contentHandling` was already+ implemented in `_put_integration_response` (commit 0ef45048).+ This test pins that behaviour so a future refactor can't silently+ regress it (the audit's M-6 listed it as missing, which was wrong —+ keep it covered to make sure it stays right)."""+ api_id, resource_id, method = method_setup+ apigw_v1.put_integration(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ type="HTTP",+ integrationHttpMethod="POST",+ uri="https://httpbin.org/anything",+ )+ apigw_v1.put_integration_response(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ statusCode="200",+ contentHandling=ch_value,+ )++ got = apigw_v1.get_integration_response(+ restApiId=api_id,+ resourceId=resource_id,+ httpMethod=method,+ statusCode="200",+ )+ assert got.get("contentHandling") == ch_valuediff --git a/tests/test_apigatewayv1_content_handling.py b/tests/test_apigatewayv1_content_handling.pydeleted file mode 100644index 2e4a7b54..00000000--- a/tests/test_apigatewayv1_content_handling.py+++ /dev/null@@ -1,177 +0,0 @@-"""-Regression tests for API Gateway v1 (REST API) ContentHandling fidelity.--Background------------The AWS REST API Gateway v1 spec defines a `contentHandling` field on-both Integration (`PutIntegration`) and IntegrationResponse-(`PutIntegrationResponse`), with valid values `CONVERT_TO_BINARY` /-`CONVERT_TO_TEXT`. Terraform's `aws_api_gateway_integration` and-`aws_api_gateway_integration_response` resources both expose this-field; without it the AWS provider cannot mark the resource as-matched and plans to re-set it on every apply.--Bugs (per the project audit):-- H-8 PutIntegration silently dropped `contentHandling` — same family- as #439 which fixed it for v2 but never backported to v1.- M-6 PutIntegrationResponse historically dropped `contentHandling`;- turns out this was already added in `_put_integration_response`- (commit 0ef45048). The regression tests below pin both paths.--Uses the session-scoped `apigw_v1` fixture from tests/conftest.py.-"""-import pytest---def method_setup(apigw_v1):- """Create a fresh REST API + resource + method as a foundation for- integration tests. Yields (api_id, resource_id, http_method) and- deletes the REST API in teardown so the session-scoped client- doesn't leak state across tests."""- api = apigw_v1.create_rest_api(name="ch-test-api")- api_id = api["id"]- root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]- res = apigw_v1.create_resource(- restApiId=api_id, parentId=root_id, pathPart="ch",- )- resource_id = res["id"]- apigw_v1.put_method(- restApiId=api_id,- resourceId=resource_id,- httpMethod="POST",- authorizationType="NONE",- )- apigw_v1.put_method_response(- restApiId=api_id,- resourceId=resource_id,- httpMethod="POST",- statusCode="200",- )- try:- yield api_id, resource_id, "POST"- finally:- try:- apigw_v1.delete_rest_api(restApiId=api_id)- except Exception:- pass---# ── H-8: PutIntegration / GetIntegration round-trip ───────────────────-[email protected]("ch_value", ["CONVERT_TO_TEXT", "CONVERT_TO_BINARY"])-def test_put_integration_persists_content_handling(apigw_v1, method_setup, ch_value):- """PutIntegration accepting `contentHandling` must store the value- so subsequent GetIntegration returns it. Without the fix, the field- was silently dropped — breaking Terraform's- `aws_api_gateway_integration.content_handling` round-trip."""- api_id, resource_id, method = method_setup- apigw_v1.put_integration(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- type="HTTP",- integrationHttpMethod="POST",- uri="https://httpbin.org/anything",- contentHandling=ch_value,- )-- got = apigw_v1.get_integration(- restApiId=api_id, resourceId=resource_id, httpMethod=method,- )- assert got.get("contentHandling") == ch_value, (- f"PutIntegration silently dropped contentHandling={ch_value!r}; "- "GetIntegration returned: " + repr(got.get("contentHandling"))- )---def test_put_integration_omits_content_handling_when_not_set(apigw_v1, method_setup):- """When the caller does NOT pass contentHandling, the response must- not invent one. Real AWS omits the field; some boto3-driven- Terraform plans diff against an emulator that returns an empty- string or other default."""- api_id, resource_id, method = method_setup- apigw_v1.put_integration(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- type="HTTP",- integrationHttpMethod="POST",- uri="https://httpbin.org/anything",- )-- got = apigw_v1.get_integration(- restApiId=api_id, resourceId=resource_id, httpMethod=method,- )- # Either the key is absent or its value is None/null (boto3 strips- # null fields). Anything else (empty string, "NONE") would be a- # fabricated value that misleads consumers.- assert got.get("contentHandling") in (None, ), (- "GetIntegration returned a fabricated contentHandling value "- f"{got.get('contentHandling')!r} when none was set."- )---def test_update_integration_can_patch_content_handling(apigw_v1, method_setup):- """Terraform's apply path uses UpdateIntegration with a JSON Patch- op (`replace /contentHandling`). The updated contentHandling value- must persist and be returned by GetIntegration."""- api_id, resource_id, method = method_setup- apigw_v1.put_integration(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- type="HTTP",- integrationHttpMethod="POST",- uri="https://httpbin.org/anything",- contentHandling="CONVERT_TO_TEXT",- )- apigw_v1.update_integration(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- patchOperations=[- {"op": "replace", "path": "/contentHandling", "value": "CONVERT_TO_BINARY"},- ],- )-- got = apigw_v1.get_integration(- restApiId=api_id, resourceId=resource_id, httpMethod=method,- )- assert got.get("contentHandling") == "CONVERT_TO_BINARY"---# ── M-6 regression lock: PutIntegrationResponse still works ───────────-[email protected]("ch_value", ["CONVERT_TO_TEXT", "CONVERT_TO_BINARY"])-def test_put_integration_response_persists_content_handling(apigw_v1, method_setup, ch_value):- """PutIntegrationResponse persisting `contentHandling` was already- implemented in `_put_integration_response` (commit 0ef45048).- This test pins that behaviour so a future refactor can't silently- regress it (the audit's M-6 listed it as missing, which was wrong —- keep it covered to make sure it stays right)."""- api_id, resource_id, method = method_setup- apigw_v1.put_integration(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- type="HTTP",- integrationHttpMethod="POST",- uri="https://httpbin.org/anything",- )- apigw_v1.put_integration_response(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- statusCode="200",- contentHandling=ch_value,- )-- got = apigw_v1.get_integration_response(- restApiId=api_id,- resourceId=resource_id,- httpMethod=method,- statusCode="200",- )- assert got.get("contentHandling") == ch_valuediff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex ac13b8b3..cc79199f 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -2224,3 +2224,37 @@ def test_apigw_lambda_proxy_emits_cloudwatch_logs_nodejs(apigw, lam, logs):apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)apigw.delete_api(ApiId=api_id)lam.delete_function(FunctionName=fname)+++# ========== from test_misc_medium_low_fixes.py ==========+# get_state() on both apigateway modules must deep-copy. A live reference+# in the snapshot would let a concurrent write during shutdown+# serialisation corrupt the persisted JSON.++import importlib as _importlib_get_state++[email protected]("mod_name", ["apigateway", "apigateway_v1"])+def test_apigateway_get_state_returns_independent_copy(mod_name):+ mod = _importlib_get_state.import_module(f"ministack.services.{mod_name}")+ if hasattr(mod, "reset"):+ mod.reset()++ snapshot = mod.get_state()++ leaks = []+ for key, snap_value in snapshot.items():+ live = getattr(mod, f"_{key}", None)+ if live is None:+ continue+ if snap_value is live:+ leaks.append(key)++ assert not leaks, (+ f"{mod_name}.get_state() returned LIVE references for keys: {leaks}. "+ "A concurrent write to one of these dicts during shutdown serialisation "+ "would corrupt the persisted JSON. Wrap each value in copy.deepcopy(...)."+ )++ if hasattr(mod, "reset"):+ mod.reset()diff --git a/tests/test_logs.py b/tests/test_cloudwatch_logs.pysimilarity index 80%rename from tests/test_logs.pyrename to tests/test_cloudwatch_logs.pyindex 8b2d51f0..5b2394df 100644--- a/tests/test_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -677,3 +677,179 @@ def test_logs_create_delivery_rejects_duplicate_pair(logs):finally:logs.delete_delivery_destination(name=dest_name)logs.delete_delivery_source(name=src_name)+++# ========== from test_cloudwatch_logs_persistence.py ==========+# CloudWatch Logs persistence symmetry.+import importlib++import pytest++from ministack.core import persistence+++def _module():+ return importlib.import_module("ministack.services.cloudwatch_logs")++[email protected](autouse=True)+def _enable_persistence(monkeypatch, tmp_path):+ """Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the+ duration of each test so save_state / load_state actually write and+ read JSON instead of short-circuiting."""+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+++def _round_trip(mod, svc_key="cloudwatch_logs"):+ """Simulate a full warm-boot through the on-disk JSON path."""+ persistence.save_state(svc_key, mod.get_state())+ mod.reset()+ loaded = persistence.load_state(svc_key)+ assert loaded is not None, (+ f"persistence.load_state({svc_key!r}) returned None — state "+ "file was not written by save_state(). Check get_state() "+ "correctness and that PERSIST_STATE is True."+ )+ mod.restore_state(loaded)+++# ── _destinations ──────────────────────────────────────────────────────++def test_destinations_survive_warm_boot():+ mod = _module()+ mod.reset()+ mod._destinations["my-dest"] = {+ "destinationName": "my-dest",+ "targetArn": "arn:aws:kinesis:us-east-1:000000000000:stream/log-stream",+ "roleArn": "arn:aws:iam::000000000000:role/CWLtoKinesis",+ "accessPolicy": "",+ "arn": "arn:aws:logs:us-east-1:000000000000:destination:my-dest",+ "creationTime": 1700000000000,+ }++ _round_trip(mod)++ assert "my-dest" in mod._destinations, (+ "CloudWatch Logs destination lost across get_state → restore_state — "+ "_destinations must be in both."+ )+ assert mod._destinations["my-dest"]["targetArn"].endswith(":stream/log-stream")+ mod.reset()+++# ── _metric_filters ────────────────────────────────────────────────────++def test_metric_filters_survive_warm_boot():+ mod = _module()+ mod.reset()+ # Create the parent log group first — _put_metric_filter would normally+ # require it; we mirror that pre-condition for realism.+ mod._log_groups["/aws/lambda/foo"] = {+ "arn": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/foo:*",+ "creationTime": 1700000000000,+ "retentionInDays": None,+ "tags": {},+ "subscriptionFilters": {},+ "streams": {},+ }+ mod._metric_filters[("/aws/lambda/foo", "ErrorCount")] = {+ "filterName": "ErrorCount",+ "logGroupName": "/aws/lambda/foo",+ "filterPattern": "ERROR",+ "metricTransformations": [{+ "metricName": "Errors",+ "metricNamespace": "Lambda",+ "metricValue": "1",+ }],+ "creationTime": 1700000000000,+ }++ _round_trip(mod)++ assert ("/aws/lambda/foo", "ErrorCount") in mod._metric_filters, (+ "Metric filter lost across get_state → restore_state — "+ "_metric_filters must be in both. Tuple keys are round-tripped "+ "by AccountScopedDict's JSON encoder hook."+ )+ mod.reset()+++# ── _queries ───────────────────────────────────────────────────────────++def test_queries_survive_warm_boot():+ mod = _module()+ mod.reset()+ mod._queries["q-12345"] = {+ "queryId": "q-12345",+ "logGroupName": "/aws/lambda/foo",+ "startTime": 1700000000,+ "endTime": 1700001000,+ "queryString": "fields @timestamp, @message | limit 20",+ "status": "Complete",+ }++ _round_trip(mod)++ assert "q-12345" in mod._queries, (+ "CloudWatch Logs Insights query lost across get_state → "+ "restore_state — _queries must be in both."+ )+ mod.reset()+++# ── subscription-filter ↔ destination consistency ──────────────────────++def test_subscription_filter_destination_resolvable_after_warm_boot():+ """A subscription filter on a log group references a destination ARN.+ The filter lives inside _log_groups (persisted), the destination lives+ in _destinations (was NOT persisted). After warm-boot the filter+ pointed at a vanished destination — split-brain. With _destinations+ persistence, the destination must still resolve."""+ mod = _module()+ mod.reset()++ dest_arn = "arn:aws:logs:us-east-1:000000000000:destination:cross-account"+ mod._destinations["cross-account"] = {+ "destinationName": "cross-account",+ "targetArn": "arn:aws:kinesis:us-east-1:222222222222:stream/audit",+ "roleArn": "arn:aws:iam::000000000000:role/CWLtoKinesis",+ "accessPolicy": "",+ "arn": dest_arn,+ "creationTime": 1700000000000,+ }+ mod._log_groups["/aws/lambda/audited"] = {+ "arn": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/audited:*",+ "creationTime": 1700000000000,+ "retentionInDays": None,+ "tags": {},+ "subscriptionFilters": {+ "to-cross-account": {+ "filterName": "to-cross-account",+ "logGroupName": "/aws/lambda/audited",+ "filterPattern": "",+ "destinationArn": dest_arn,+ "roleArn": "",+ "distribution": "ByLogStream",+ "creationTime": 1700000000000,+ },+ },+ "streams": {},+ }++ _round_trip(mod)++ # The log-group side already round-tripped on main; what was missing+ # is the destination it references.+ assert "/aws/lambda/audited" in mod._log_groups+ sub_filter = mod._log_groups["/aws/lambda/audited"]["subscriptionFilters"]["to-cross-account"]+ referenced_arn = sub_filter["destinationArn"]++ # Find the destination that ought to back this ARN.+ matching = [d for d in mod._destinations.values() if d.get("arn") == referenced_arn]+ assert matching, (+ "Subscription filter references a destination ARN that no "+ "longer exists in _destinations after warm-boot — split-brain "+ "state. _destinations must be persisted alongside _log_groups."+ )+ mod.reset()diff --git a/tests/test_cloudwatch_logs_persistence.py b/tests/test_cloudwatch_logs_persistence.pydeleted file mode 100644index e998474d..00000000--- a/tests/test_cloudwatch_logs_persistence.py+++ /dev/null@@ -1,205 +0,0 @@-"""-Regression tests for the CloudWatch Logs persistence drops.--Three module-level AccountScopedDicts are mutated by public APIs but-were missing from `get_state()` / `restore_state()`:-- - cloudwatch_logs._destinations (PutDestination)- - cloudwatch_logs._metric_filters (PutMetricFilter)- - cloudwatch_logs._queries (StartQuery)--Plus a follow-on consistency bug:-- - Subscription filters live inside _log_groups (persisted) but- reference destination ARNs in _destinations (not persisted).- After warm-boot you get split-brain: the filter on the log group- still references a destination that no longer exists in- _destinations.--Each test exercises the FULL warm-boot path:- 1. populate the in-memory dict- 2. `get_state()` snapshot- 3. `persistence.save_state()` → JSON-encode to a tmp `STATE_DIR`- 4. `mod.reset()` (simulate process restart)- 5. `persistence.load_state()` → JSON-decode from disk- 6. `restore_state(loaded)`--Going through `save_state` / `load_state` (rather than just calling-get_state / restore_state in-memory) is what catches encoder /-decoder regressions — most notably the tuple-key path used by-`_metric_filters`, which round-trips through repr → JSON string →-ast.literal_eval in `core/persistence.py::_json_default` /-`_json_object_hook`.-"""-import importlib--import pytest--from ministack.core import persistence---def _module():- return importlib.import_module("ministack.services.cloudwatch_logs")--[email protected](autouse=True)-def _enable_persistence(monkeypatch, tmp_path):- """Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the- duration of each test so save_state / load_state actually write and- read JSON instead of short-circuiting."""- monkeypatch.setattr(persistence, "PERSIST_STATE", True)- monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))---def _round_trip(mod, svc_key="cloudwatch_logs"):- """Simulate a full warm-boot through the on-disk JSON path."""- persistence.save_state(svc_key, mod.get_state())- mod.reset()- loaded = persistence.load_state(svc_key)- assert loaded is not None, (- f"persistence.load_state({svc_key!r}) returned None — state "- "file was not written by save_state(). Check get_state() "- "correctness and that PERSIST_STATE is True."- )- mod.restore_state(loaded)---# ── _destinations ──────────────────────────────────────────────────────--def test_destinations_survive_warm_boot():- mod = _module()- mod.reset()- mod._destinations["my-dest"] = {- "destinationName": "my-dest",- "targetArn": "arn:aws:kinesis:us-east-1:000000000000:stream/log-stream",- "roleArn": "arn:aws:iam::000000000000:role/CWLtoKinesis",- "accessPolicy": "",- "arn": "arn:aws:logs:us-east-1:000000000000:destination:my-dest",- "creationTime": 1700000000000,- }-- _round_trip(mod)-- assert "my-dest" in mod._destinations, (- "CloudWatch Logs destination lost across get_state → restore_state — "- "_destinations must be in both."- )- assert mod._destinations["my-dest"]["targetArn"].endswith(":stream/log-stream")- mod.reset()---# ── _metric_filters ────────────────────────────────────────────────────--def test_metric_filters_survive_warm_boot():- mod = _module()- mod.reset()- # Create the parent log group first — _put_metric_filter would normally- # require it; we mirror that pre-condition for realism.- mod._log_groups["/aws/lambda/foo"] = {- "arn": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/foo:*",- "creationTime": 1700000000000,- "retentionInDays": None,- "tags": {},- "subscriptionFilters": {},- "streams": {},- }- mod._metric_filters[("/aws/lambda/foo", "ErrorCount")] = {- "filterName": "ErrorCount",- "logGroupName": "/aws/lambda/foo",- "filterPattern": "ERROR",- "metricTransformations": [{- "metricName": "Errors",- "metricNamespace": "Lambda",- "metricValue": "1",- }],- "creationTime": 1700000000000,- }-- _round_trip(mod)-- assert ("/aws/lambda/foo", "ErrorCount") in mod._metric_filters, (- "Metric filter lost across get_state → restore_state — "- "_metric_filters must be in both. Tuple keys are round-tripped "- "by AccountScopedDict's JSON encoder hook."- )- mod.reset()---# ── _queries ───────────────────────────────────────────────────────────--def test_queries_survive_warm_boot():- mod = _module()- mod.reset()- mod._queries["q-12345"] = {- "queryId": "q-12345",- "logGroupName": "/aws/lambda/foo",- "startTime": 1700000000,- "endTime": 1700001000,- "queryString": "fields @timestamp, @message | limit 20",- "status": "Complete",- }-- _round_trip(mod)-- assert "q-12345" in mod._queries, (- "CloudWatch Logs Insights query lost across get_state → "- "restore_state — _queries must be in both."- )- mod.reset()---# ── subscription-filter ↔ destination consistency ──────────────────────--def test_subscription_filter_destination_resolvable_after_warm_boot():- """A subscription filter on a log group references a destination ARN.- The filter lives inside _log_groups (persisted), the destination lives- in _destinations (was NOT persisted). After warm-boot the filter- pointed at a vanished destination — split-brain. With _destinations- persistence, the destination must still resolve."""- mod = _module()- mod.reset()-- dest_arn = "arn:aws:logs:us-east-1:000000000000:destination:cross-account"- mod._destinations["cross-account"] = {- "destinationName": "cross-account",- "targetArn": "arn:aws:kinesis:us-east-1:222222222222:stream/audit",- "roleArn": "arn:aws:iam::000000000000:role/CWLtoKinesis",- "accessPolicy": "",- "arn": dest_arn,- "creationTime": 1700000000000,- }- mod._log_groups["/aws/lambda/audited"] = {- "arn": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/audited:*",- "creationTime": 1700000000000,- "retentionInDays": None,- "tags": {},- "subscriptionFilters": {- "to-cross-account": {- "filterName": "to-cross-account",- "logGroupName": "/aws/lambda/audited",- "filterPattern": "",- "destinationArn": dest_arn,- "roleArn": "",- "distribution": "ByLogStream",- "creationTime": 1700000000000,- },- },- "streams": {},- }-- _round_trip(mod)-- # The log-group side already round-tripped on main; what was missing- # is the destination it references.- assert "/aws/lambda/audited" in mod._log_groups- sub_filter = mod._log_groups["/aws/lambda/audited"]["subscriptionFilters"]["to-cross-account"]- referenced_arn = sub_filter["destinationArn"]-- # Find the destination that ought to back this ARN.- matching = [d for d in mod._destinations.values() if d.get("arn") == referenced_arn]- assert matching, (- "Subscription filter references a destination ARN that no "- "longer exists in _destinations after warm-boot — split-brain "- "state. _destinations must be persisted alongside _log_groups."- )- mod.reset()diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 5507de92..5fa7021e 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1,6 +1,7 @@-"""Cognito tests — user pools, identity pools, OAuth2/OIDC flows."""+"""Cognito tests — user pools, identity pools, OAuth2/OIDC flows, auth-code persistence."""import base64+import importlibimport ioimport jsonimport os@@ -16,6 +17,8 @@ from urllib.parse import urlparseimport pytestfrom botocore.exceptions import ClientError+from ministack.core import persistence+# ========== from test_cognito.py ==========def test_cognito_create_and_describe_user_pool(cognito_idp):@@ -2192,3 +2195,77 @@ def test_oauth2_full_flow():status, headers, _ = _get(logout_url, follow_redirects=False)assert status == 302assert headers.get('location', '') == 'http://localhost:3000/logout'+++# ========== from test_cognito_auth_codes_persistence.py ==========+# Two distinct OAuth2 code stores exist in services/cognito.py:+# - _authorization_codes — managed-login PKCE flow (already persisted)+# - _auth_codes — hosted-UI / SAML-OIDC federation relay flow (5-minute TTL)+# Both must survive warm-boot. Both stay PLAIN dicts (not AccountScopedDict)+# because the OAuth2 token endpoint has no AWS auth context — lookup is by+# random unguessable token, so wrapping them in AccountScopedDict would+# silently break the flow under any non-default tenant.+++def _cognito_module():+ return importlib.import_module("ministack.services.cognito")+++def _enable_persistence(monkeypatch, tmp_path):+ """Force PERSIST_STATE on and point STATE_DIR at a tmp dir so+ save_state / load_state actually write and read JSON files."""+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+++def _cognito_round_trip(mod, svc_key="cognito"):+ """Simulate a full warm-boot via the on-disk JSON path."""+ persistence.save_state(svc_key, mod.get_state())+ mod.reset()+ loaded = persistence.load_state(svc_key)+ assert loaded is not None, "load_state returned None — get_state may be wrong"+ mod.restore_state(loaded)+++def test_auth_codes_survive_warm_boot(_enable_persistence):+ """`_auth_codes` populated by the hosted-UI / federation flow must+ survive a warm-boot through the on-disk JSON path. Without the fix+ `_auth_codes` was missing from get_state/restore_state, so any+ in-flight hosted-UI sign-in within the 5-minute code TTL was+ silently invalidated by a restart."""+ mod = _cognito_module()+ mod.reset()++ relay_state = "test-relay-12345"+ mod._auth_codes[relay_state] = {+ "type": "code",+ "pool_id": "us-east-1_TestPool",+ "client_id": "client-id-abc",+ "username": "[email protected]",+ "sub": "user-sub-12345",+ "redirect_uri": "https://app.example.com/callback",+ "scopes": "openid email",+ "created_at": 1700000000.0,+ }++ _cognito_round_trip(mod)++ assert relay_state in mod._auth_codes, (+ "Hosted-UI relay code lost across warm-boot — _auth_codes must "+ "be in both get_state() and restore_state()."+ )+ assert mod._auth_codes[relay_state]["pool_id"] == "us-east-1_TestPool"+ assert mod._auth_codes[relay_state]["client_id"] == "client-id-abc"+ mod.reset()+++def test_auth_codes_dict_types_are_plain_builtin_dict():+ """`_auth_codes` and `_authorization_codes` must remain plain `dict`+ instances. They're looked up by random unguessable token from a public+ OAuth2 callback with no AWS auth context — wrapping in AccountScopedDict+ would make the lookup happen under a default account, invisible to codes+ issued under any other tenant."""+ mod = _cognito_module()+ assert type(mod._auth_codes) is dict+ assert type(mod._authorization_codes) is dictdiff --git a/tests/test_cognito_auth_codes_persistence.py b/tests/test_cognito_auth_codes_persistence.pydeleted file mode 100644index 225021f8..00000000--- a/tests/test_cognito_auth_codes_persistence.py+++ /dev/null@@ -1,117 +0,0 @@-"""-Regression test for cognito hosted-UI / federation `_auth_codes`-persistence.--Background------------Two distinct OAuth2 code stores exist in `services/cognito.py`:-- - `_authorization_codes` — managed-login PKCE flow. Was already- persisted in get_state/restore_state.- - `_auth_codes` — hosted-UI / SAML-OIDC federation relay flow. Was- declared with the comment "ephemeral, not persisted" but the codes- have a 5-minute TTL and any in-flight Cognito hosted-UI sign-in- that straddles a warm-boot becomes invalid for no good reason- (the user has to re-auth even though the code itself is still- well within its TTL).--Why these dicts are intentionally PLAIN dicts (not AccountScopedDict):-the OAuth2 token endpoint (`cognito.py:_oauth2_token`) is a public-endpoint with no AWS authentication context — it identifies the-caller via the OAuth2 `code` + `client_id` + `client_secret` (HTTP-Basic), NOT via a SigV4 access key. If these dicts were AccountScopedDict,-the code lookup would happen under whatever default account the-callback runs in, and codes issued under one tenant would be invisible-to other tenants, breaking the OAuth2 flow entirely. Effective tenant-isolation is provided by the random unguessable token namespace.-"""-import importlib--import pytest--from ministack.core import persistence---def _module():- return importlib.import_module("ministack.services.cognito")--[email protected](autouse=True)-def _enable_persistence(monkeypatch, tmp_path):- """Force PERSIST_STATE on and point STATE_DIR at a tmp dir so- save_state / load_state actually write and read JSON files."""- monkeypatch.setattr(persistence, "PERSIST_STATE", True)- monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))---def _round_trip(mod, svc_key="cognito"):- """Simulate a full warm-boot via the on-disk JSON path."""- persistence.save_state(svc_key, mod.get_state())- mod.reset()- loaded = persistence.load_state(svc_key)- assert loaded is not None, "load_state returned None — get_state may be wrong"- mod.restore_state(loaded)---def test_auth_codes_survive_warm_boot():- """`_auth_codes` populated by the hosted-UI / federation flow must- survive a warm-boot through the on-disk JSON path. Without the fix- `_auth_codes` was missing from get_state/restore_state, so any- in-flight hosted-UI sign-in within the 5-minute code TTL was- silently invalidated by a restart."""- mod = _module()- mod.reset()-- # Match the actual production payload shape written by the SAML/OIDC- # callback handler in `cognito.py` — `type: "code"` entries store- # `scopes` as a space-separated string (copied from `relay["scope"]`)- # and have no `state` field (state lives on the sibling `type: "relay"`- # entry that this code-type one is created from).- relay_state = "test-relay-12345"- mod._auth_codes[relay_state] = {- "type": "code",- "pool_id": "us-east-1_TestPool",- "client_id": "client-id-abc",- "username": "[email protected]",- "sub": "user-sub-12345",- "redirect_uri": "https://app.example.com/callback",- "scopes": "openid email",- "created_at": 1700000000.0,- }-- _round_trip(mod)-- assert relay_state in mod._auth_codes, (- "Hosted-UI relay code lost across warm-boot — _auth_codes must "- "be in both get_state() and restore_state()."- )- assert mod._auth_codes[relay_state]["pool_id"] == "us-east-1_TestPool"- assert mod._auth_codes[relay_state]["client_id"] == "client-id-abc"- mod.reset()---def test_auth_codes_dict_types_are_plain_builtin_dict():- """Belt-and-braces: assert that `_auth_codes` and- `_authorization_codes` remain plain built-in `dict` instances —- not AccountScopedDict, not any other dict-like wrapper.-- These dicts are looked up by random unguessable token from a public- OAuth2 callback with no AWS auth context. Wrapping them in- AccountScopedDict (or anything else with request-scoped lookup- semantics) would make the callback lookup happen under a default- account, invisible to codes issued under any other tenant —- breaking the entire OAuth2 flow. This test pins the type so a- well-meaning future refactor doesn't silently break OAuth2.-- `type(x) is dict` (strict identity) catches not just AccountScopedDict- but also any other Mapping subclass that might quietly slip in."""- mod = _module()-- assert type(mod._auth_codes) is dict, (- "_auth_codes must remain a plain built-in dict — see the "- "docstring for why."- )- assert type(mod._authorization_codes) is dict, (- "_authorization_codes must remain a plain built-in dict — same "- "reason."- )diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex b429110b..7b479ac0 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -1568,3 +1568,279 @@ def test_ddb_sse_description_shape_matches_aws(ddb, kms_client):sse = ddb.describe_table(TableName=tname)["Table"]["SSEDescription"]assert sse["Status"] == "DISABLED"ddb.delete_table(TableName=tname)+++# ========== from test_dynamodb_kinesis_destination.py ==========+# DDB→Kinesis streaming destination (Enable/Disable/Describe/Update + envelope).++import base64+import json+import time++import pytest+from botocore.exceptions import ClientError+++def _make_table(ddb, name):+ try:+ ddb.delete_table(TableName=name)+ except ClientError:+ pass+ ddb.create_table(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ )+++def _make_stream(kin, name):+ try:+ kin.delete_stream(StreamName=name)+ except ClientError:+ pass+ kin.create_stream(StreamName=name, ShardCount=1)+ # Streams are ACTIVE immediately in MiniStack, but the DescribeStream call+ # is cheap and keeps the test robust if that ever changes.+ kin.describe_stream(StreamName=name)+ return kin.describe_stream(StreamName=name)["StreamDescription"]["StreamARN"]+++def _drain_kinesis(kin, stream_name):+ shards = kin.describe_stream(StreamName=stream_name)["StreamDescription"]["Shards"]+ out = []+ for shard in shards:+ it = kin.get_shard_iterator(+ StreamName=stream_name,+ ShardId=shard["ShardId"],+ ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]+ for _ in range(5):+ resp = kin.get_records(ShardIterator=it, Limit=1000)+ out.extend(resp.get("Records", []))+ nxt = resp.get("NextShardIterator")+ if not nxt or nxt == it or not resp.get("Records"):+ break+ it = nxt+ return out+++# ---------------------------------------------------------------------------+# Lifecycle+# ---------------------------------------------------------------------------++def test_enable_returns_active_and_describe_lists_it(ddb, kin):+ _make_table(ddb, "KdsLifecycle")+ arn = _make_stream(kin, "ministack-kds-lifecycle")++ resp = ddb.enable_kinesis_streaming_destination(+ TableName="KdsLifecycle", StreamArn=arn,+ )+ # AWS returns ENABLING immediately; the destination flips to ACTIVE+ # by the time Describe is called.+ assert resp["DestinationStatus"] == "ENABLING"+ assert resp["StreamArn"] == arn+ assert resp["TableName"] == "KdsLifecycle"++ desc = ddb.describe_kinesis_streaming_destination(TableName="KdsLifecycle")+ dests = desc["KinesisDataStreamDestinations"]+ assert len(dests) == 1+ assert dests[0]["StreamArn"] == arn+ assert dests[0]["DestinationStatus"] == "ACTIVE"+ assert dests[0]["ApproximateCreationDateTimePrecision"] == "MILLISECOND"+++def test_enable_twice_same_table_and_arn_raises(ddb, kin):+ _make_table(ddb, "KdsDup")+ arn = _make_stream(kin, "ministack-kds-dup")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)++ with pytest.raises(ClientError) as ei:+ ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceInUseException"+++def test_enable_requires_existing_table(ddb, kin):+ arn = _make_stream(kin, "ministack-kds-missing")+ with pytest.raises(ClientError) as ei:+ ddb.enable_kinesis_streaming_destination(TableName="ThisTableDoesNotExist", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Delivery: item mutations end up as Kinesis records when ACTIVE+# ---------------------------------------------------------------------------++def test_item_mutations_land_in_kinesis_stream(ddb, kin):+ _make_table(ddb, "KdsDeliver")+ arn = _make_stream(kin, "ministack-kds-deliver")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDeliver", StreamArn=arn)++ ddb.put_item(TableName="KdsDeliver", Item={"pk": {"S": "a"}, "val": {"N": "1"}})+ ddb.update_item(+ TableName="KdsDeliver",+ Key={"pk": {"S": "a"}},+ UpdateExpression="SET val = :v",+ ExpressionAttributeValues={":v": {"N": "2"}},+ )+ ddb.delete_item(TableName="KdsDeliver", Key={"pk": {"S": "a"}})++ records = _drain_kinesis(kin, "ministack-kds-deliver")+ assert len(records) == 3++ decoded = []+ for r in records:+ payload = r["Data"]+ # boto3 normalises the base64-encoded Data back into bytes for us+ if isinstance(payload, str):+ payload = base64.b64decode(payload)+ decoded.append(json.loads(payload.decode("utf-8")))++ event_names = [d["eventName"] for d in decoded]+ assert event_names == ["INSERT", "MODIFY", "REMOVE"]+ for d in decoded:+ assert d["eventSource"] == "aws:dynamodb"+ assert d["dynamodb"]["Keys"] == {"pk": {"S": "a"}}+++def test_disable_stops_delivery(ddb, kin):+ _make_table(ddb, "KdsDisable")+ arn = _make_stream(kin, "ministack-kds-disable")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)++ ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "before"}})++ resp = ddb.disable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)+ # AWS returns DISABLING immediately; storage is DISABLED so Describe+ # below shows the steady-state.+ assert resp["DestinationStatus"] == "DISABLING"++ # Describe still lists the now-DISABLED entry (matches AWS ~24h retention).+ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsDisable")[+ "KinesisDataStreamDestinations"+ ]+ assert len(dests) == 1+ assert dests[0]["DestinationStatus"] == "DISABLED"++ ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "after"}})++ records = _drain_kinesis(kin, "ministack-kds-disable")+ assert len(records) == 1 # only the pre-disable INSERT+++def test_disable_without_active_raises(ddb, kin):+ _make_table(ddb, "KdsNoActive")+ arn = _make_stream(kin, "ministack-kds-no-active")+ with pytest.raises(ClientError) as ei:+ ddb.disable_kinesis_streaming_destination(TableName="KdsNoActive", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Update+# ---------------------------------------------------------------------------++def test_update_precision(ddb, kin):+ _make_table(ddb, "KdsUpdate")+ arn = _make_stream(kin, "ministack-kds-update")+ ddb.enable_kinesis_streaming_destination(TableName="KdsUpdate", StreamArn=arn)++ resp = ddb.update_kinesis_streaming_destination(+ TableName="KdsUpdate",+ StreamArn=arn,+ UpdateKinesisStreamingConfiguration={+ "ApproximateCreationDateTimePrecision": "MICROSECOND",+ },+ )+ # AWS returns UPDATING immediately; Describe below shows steady-state ACTIVE.+ assert resp["DestinationStatus"] == "UPDATING"+ assert (+ resp["UpdateKinesisStreamingConfiguration"]["ApproximateCreationDateTimePrecision"]+ == "MICROSECOND"+ )++ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsUpdate")[+ "KinesisDataStreamDestinations"+ ]+ assert dests[0]["ApproximateCreationDateTimePrecision"] == "MICROSECOND"+++def test_update_rejects_invalid_precision(ddb, kin):+ """boto3 catches `NANOSECOND` client-side via enum validation, so we hit+ the server with a raw HTTP POST to verify the server-side ValidationException+ actually fires (not just the SDK)."""+ import urllib.error+ import urllib.request++ _make_table(ddb, "KdsUpdateInvalid")+ arn = _make_stream(kin, "ministack-kds-update-invalid")+ ddb.enable_kinesis_streaming_destination(TableName="KdsUpdateInvalid", StreamArn=arn)++ body = json.dumps({+ "TableName": "KdsUpdateInvalid",+ "StreamArn": arn,+ "UpdateKinesisStreamingConfiguration": {"ApproximateCreationDateTimePrecision": "NANOSECOND"},+ }).encode("utf-8")+ req = urllib.request.Request(+ "http://localhost:4566/",+ data=body,+ headers={+ "Content-Type": "application/x-amz-json-1.0",+ "X-Amz-Target": "DynamoDB_20120810.UpdateKinesisStreamingDestination",+ },+ method="POST",+ )+ try:+ urllib.request.urlopen(req)+ pytest.fail("Expected server to reject NANOSECOND precision")+ except urllib.error.HTTPError as e:+ assert e.code == 400+ err_body = json.loads(e.read().decode("utf-8"))+ assert err_body.get("__type", "").endswith("ValidationException")+++# ---------------------------------------------------------------------------+# Cleanup on table delete+# ---------------------------------------------------------------------------++def test_delete_table_removes_destinations(ddb, kin):+ _make_table(ddb, "KdsAutoclean")+ arn = _make_stream(kin, "ministack-kds-autoclean")+ ddb.enable_kinesis_streaming_destination(TableName="KdsAutoclean", StreamArn=arn)++ ddb.delete_table(TableName="KdsAutoclean")+ # After a fresh CreateTable there should be zero destinations.+ _make_table(ddb, "KdsAutoclean")+ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsAutoclean")[+ "KinesisDataStreamDestinations"+ ]+ assert dests == []+++# ---------------------------------------------------------------------------+# Order stability (smoke)+# ---------------------------------------------------------------------------++def test_multiple_puts_land_in_order(ddb, kin):+ _make_table(ddb, "KdsOrder")+ arn = _make_stream(kin, "ministack-kds-order")+ ddb.enable_kinesis_streaming_destination(TableName="KdsOrder", StreamArn=arn)++ for i in range(5):+ ddb.put_item(TableName="KdsOrder", Item={"pk": {"S": f"k{i}"}})++ # Short sleep to make sure arrival timestamps settle (not strictly needed).+ time.sleep(0.05)+ records = _drain_kinesis(kin, "ministack-kds-order")+ assert len(records) == 5+ decoded = [+ json.loads(+ (base64.b64decode(r["Data"]) if isinstance(r["Data"], str) else r["Data"]).decode("utf-8")+ )+ for r in records+ ]+ keys = [d["dynamodb"]["Keys"]["pk"]["S"] for d in decoded]+ assert keys == [f"k{i}" for i in range(5)]++diff --git a/tests/test_dynamodb_kinesis_destination.py b/tests/test_dynamodb_kinesis_destination.pydeleted file mode 100644index cb4a6c17..00000000--- a/tests/test_dynamodb_kinesis_destination.py+++ /dev/null@@ -1,281 +0,0 @@-"""-Integration tests for the DynamoDB -> Kinesis streaming destination API-(`aws_dynamodb_kinesis_streaming_destination`).--Exercises the full lifecycle:- Enable -> Describe(ACTIVE) -> item mutations fan out to Kinesis ->- Disable -> Describe(DISABLED) -> mutations NO LONGER fan out ->- Update ApproximateCreationDateTimePrecision.-"""--import base64-import json-import time--import pytest-from botocore.exceptions import ClientError---def _make_table(ddb, name):- try:- ddb.delete_table(TableName=name)- except ClientError:- pass- ddb.create_table(- TableName=name,- KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],- AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],- BillingMode="PAY_PER_REQUEST",- StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},- )---def _make_stream(kin, name):- try:- kin.delete_stream(StreamName=name)- except ClientError:- pass- kin.create_stream(StreamName=name, ShardCount=1)- # Streams are ACTIVE immediately in MiniStack, but the DescribeStream call- # is cheap and keeps the test robust if that ever changes.- kin.describe_stream(StreamName=name)- return kin.describe_stream(StreamName=name)["StreamDescription"]["StreamARN"]---def _drain_kinesis(kin, stream_name):- shards = kin.describe_stream(StreamName=stream_name)["StreamDescription"]["Shards"]- out = []- for shard in shards:- it = kin.get_shard_iterator(- StreamName=stream_name,- ShardId=shard["ShardId"],- ShardIteratorType="TRIM_HORIZON",- )["ShardIterator"]- for _ in range(5):- resp = kin.get_records(ShardIterator=it, Limit=1000)- out.extend(resp.get("Records", []))- nxt = resp.get("NextShardIterator")- if not nxt or nxt == it or not resp.get("Records"):- break- it = nxt- return out---# ----------------------------------------------------------------------------# Lifecycle-# -----------------------------------------------------------------------------def test_enable_returns_active_and_describe_lists_it(ddb, kin):- _make_table(ddb, "KdsLifecycle")- arn = _make_stream(kin, "ministack-kds-lifecycle")-- resp = ddb.enable_kinesis_streaming_destination(- TableName="KdsLifecycle", StreamArn=arn,- )- # AWS returns ENABLING immediately; the destination flips to ACTIVE- # by the time Describe is called.- assert resp["DestinationStatus"] == "ENABLING"- assert resp["StreamArn"] == arn- assert resp["TableName"] == "KdsLifecycle"-- desc = ddb.describe_kinesis_streaming_destination(TableName="KdsLifecycle")- dests = desc["KinesisDataStreamDestinations"]- assert len(dests) == 1- assert dests[0]["StreamArn"] == arn- assert dests[0]["DestinationStatus"] == "ACTIVE"- assert dests[0]["ApproximateCreationDateTimePrecision"] == "MILLISECOND"---def test_enable_twice_same_table_and_arn_raises(ddb, kin):- _make_table(ddb, "KdsDup")- arn = _make_stream(kin, "ministack-kds-dup")- ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)-- with pytest.raises(ClientError) as ei:- ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)- assert ei.value.response["Error"]["Code"] == "ResourceInUseException"---def test_enable_requires_existing_table(ddb, kin):- arn = _make_stream(kin, "ministack-kds-missing")- with pytest.raises(ClientError) as ei:- ddb.enable_kinesis_streaming_destination(TableName="ThisTableDoesNotExist", StreamArn=arn)- assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"---# ----------------------------------------------------------------------------# Delivery: item mutations end up as Kinesis records when ACTIVE-# -----------------------------------------------------------------------------def test_item_mutations_land_in_kinesis_stream(ddb, kin):- _make_table(ddb, "KdsDeliver")- arn = _make_stream(kin, "ministack-kds-deliver")- ddb.enable_kinesis_streaming_destination(TableName="KdsDeliver", StreamArn=arn)-- ddb.put_item(TableName="KdsDeliver", Item={"pk": {"S": "a"}, "val": {"N": "1"}})- ddb.update_item(- TableName="KdsDeliver",- Key={"pk": {"S": "a"}},- UpdateExpression="SET val = :v",- ExpressionAttributeValues={":v": {"N": "2"}},- )- ddb.delete_item(TableName="KdsDeliver", Key={"pk": {"S": "a"}})-- records = _drain_kinesis(kin, "ministack-kds-deliver")- assert len(records) == 3-- decoded = []- for r in records:- payload = r["Data"]- # boto3 normalises the base64-encoded Data back into bytes for us- if isinstance(payload, str):- payload = base64.b64decode(payload)- decoded.append(json.loads(payload.decode("utf-8")))-- event_names = [d["eventName"] for d in decoded]- assert event_names == ["INSERT", "MODIFY", "REMOVE"]- for d in decoded:- assert d["eventSource"] == "aws:dynamodb"- assert d["dynamodb"]["Keys"] == {"pk": {"S": "a"}}---def test_disable_stops_delivery(ddb, kin):- _make_table(ddb, "KdsDisable")- arn = _make_stream(kin, "ministack-kds-disable")- ddb.enable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)-- ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "before"}})-- resp = ddb.disable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)- # AWS returns DISABLING immediately; storage is DISABLED so Describe- # below shows the steady-state.- assert resp["DestinationStatus"] == "DISABLING"-- # Describe still lists the now-DISABLED entry (matches AWS ~24h retention).- dests = ddb.describe_kinesis_streaming_destination(TableName="KdsDisable")[- "KinesisDataStreamDestinations"- ]- assert len(dests) == 1- assert dests[0]["DestinationStatus"] == "DISABLED"-- ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "after"}})-- records = _drain_kinesis(kin, "ministack-kds-disable")- assert len(records) == 1 # only the pre-disable INSERT---def test_disable_without_active_raises(ddb, kin):- _make_table(ddb, "KdsNoActive")- arn = _make_stream(kin, "ministack-kds-no-active")- with pytest.raises(ClientError) as ei:- ddb.disable_kinesis_streaming_destination(TableName="KdsNoActive", StreamArn=arn)- assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"---# ----------------------------------------------------------------------------# Update-# -----------------------------------------------------------------------------def test_update_precision(ddb, kin):- _make_table(ddb, "KdsUpdate")- arn = _make_stream(kin, "ministack-kds-update")- ddb.enable_kinesis_streaming_destination(TableName="KdsUpdate", StreamArn=arn)-- resp = ddb.update_kinesis_streaming_destination(- TableName="KdsUpdate",- StreamArn=arn,- UpdateKinesisStreamingConfiguration={- "ApproximateCreationDateTimePrecision": "MICROSECOND",- },- )- # AWS returns UPDATING immediately; Describe below shows steady-state ACTIVE.- assert resp["DestinationStatus"] == "UPDATING"- assert (- resp["UpdateKinesisStreamingConfiguration"]["ApproximateCreationDateTimePrecision"]- == "MICROSECOND"- )-- dests = ddb.describe_kinesis_streaming_destination(TableName="KdsUpdate")[- "KinesisDataStreamDestinations"- ]- assert dests[0]["ApproximateCreationDateTimePrecision"] == "MICROSECOND"---def test_update_rejects_invalid_precision(ddb, kin):- """boto3 catches `NANOSECOND` client-side via enum validation, so we hit- the server with a raw HTTP POST to verify the server-side ValidationException- actually fires (not just the SDK)."""- import urllib.error- import urllib.request-- _make_table(ddb, "KdsUpdateInvalid")- arn = _make_stream(kin, "ministack-kds-update-invalid")- ddb.enable_kinesis_streaming_destination(TableName="KdsUpdateInvalid", StreamArn=arn)-- body = json.dumps({- "TableName": "KdsUpdateInvalid",- "StreamArn": arn,- "UpdateKinesisStreamingConfiguration": {"ApproximateCreationDateTimePrecision": "NANOSECOND"},- }).encode("utf-8")- req = urllib.request.Request(- "http://localhost:4566/",- data=body,- headers={- "Content-Type": "application/x-amz-json-1.0",- "X-Amz-Target": "DynamoDB_20120810.UpdateKinesisStreamingDestination",- },- method="POST",- )- try:- urllib.request.urlopen(req)- pytest.fail("Expected server to reject NANOSECOND precision")- except urllib.error.HTTPError as e:- assert e.code == 400- err_body = json.loads(e.read().decode("utf-8"))- assert err_body.get("__type", "").endswith("ValidationException")---# ----------------------------------------------------------------------------# Cleanup on table delete-# -----------------------------------------------------------------------------def test_delete_table_removes_destinations(ddb, kin):- _make_table(ddb, "KdsAutoclean")- arn = _make_stream(kin, "ministack-kds-autoclean")- ddb.enable_kinesis_streaming_destination(TableName="KdsAutoclean", StreamArn=arn)-- ddb.delete_table(TableName="KdsAutoclean")- # After a fresh CreateTable there should be zero destinations.- _make_table(ddb, "KdsAutoclean")- dests = ddb.describe_kinesis_streaming_destination(TableName="KdsAutoclean")[- "KinesisDataStreamDestinations"- ]- assert dests == []---# ----------------------------------------------------------------------------# Order stability (smoke)-# -----------------------------------------------------------------------------def test_multiple_puts_land_in_order(ddb, kin):- _make_table(ddb, "KdsOrder")- arn = _make_stream(kin, "ministack-kds-order")- ddb.enable_kinesis_streaming_destination(TableName="KdsOrder", StreamArn=arn)-- for i in range(5):- ddb.put_item(TableName="KdsOrder", Item={"pk": {"S": f"k{i}"}})-- # Short sleep to make sure arrival timestamps settle (not strictly needed).- time.sleep(0.05)- records = _drain_kinesis(kin, "ministack-kds-order")- assert len(records) == 5- decoded = [- json.loads(- (base64.b64decode(r["Data"]) if isinstance(r["Data"], str) else r["Data"]).decode("utf-8")- )- for r in records- ]- keys = [d["dynamodb"]["Keys"]["pk"]["S"] for d in decoded]- assert keys == [f"k{i}" for i in range(5)]--diff --git a/tests/test_ebs.py b/tests/test_ebs.pydeleted file mode 100644index 4c838d68..00000000--- a/tests/test_ebs.py+++ /dev/null@@ -1,153 +0,0 @@-import io-import json-import os-import time-import uuid as _uuid_mod-import zipfile-from urllib.parse import urlparse--import pytest-from botocore.exceptions import ClientError---def test_ebs_create_and_describe_volume(ebs):- resp = ebs.create_volume(- AvailabilityZone="us-east-1a",- Size=20,- VolumeType="gp3",- )- vol_id = resp["VolumeId"]- assert vol_id.startswith("vol-")- assert resp["State"] == "available"- assert resp["Size"] == 20- assert resp["VolumeType"] == "gp3"-- desc = ebs.describe_volumes(VolumeIds=[vol_id])- assert len(desc["Volumes"]) == 1- assert desc["Volumes"][0]["VolumeId"] == vol_id--def test_ebs_attach_detach_volume(ebs):- inst = ebs.run_instances(ImageId="ami-00000001", MinCount=1, MaxCount=1)- instance_id = inst["Instances"][0]["InstanceId"]-- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]-- ebs.attach_volume(VolumeId=vol_id, InstanceId=instance_id, Device="/dev/xvdf")- desc = ebs.describe_volumes(VolumeIds=[vol_id])- assert desc["Volumes"][0]["State"] == "in-use"- assert desc["Volumes"][0]["Attachments"][0]["InstanceId"] == instance_id-- ebs.detach_volume(VolumeId=vol_id)- desc2 = ebs.describe_volumes(VolumeIds=[vol_id])- assert desc2["Volumes"][0]["State"] == "available"- assert desc2["Volumes"][0]["Attachments"] == []--def test_ebs_delete_volume(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=5, VolumeType="gp2")- vol_id = vol["VolumeId"]- ebs.delete_volume(VolumeId=vol_id)- with pytest.raises(ClientError) as exc:- ebs.describe_volumes(VolumeIds=[vol_id])- assert exc.value.response["Error"]["Code"] == "InvalidVolume.NotFound"--def test_ebs_modify_volume(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- resp = ebs.modify_volume(VolumeId=vol_id, Size=50, VolumeType="gp3")- assert resp["VolumeModification"]["TargetSize"] == 50- assert resp["VolumeModification"]["TargetVolumeType"] == "gp3"--def test_ebs_volume_status(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=8, VolumeType="gp2")- vol_id = vol["VolumeId"]- resp = ebs.describe_volume_status(VolumeIds=[vol_id])- assert len(resp["VolumeStatuses"]) == 1- assert resp["VolumeStatuses"][0]["VolumeStatus"]["Status"] == "ok"--def test_ebs_create_and_describe_snapshot(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- snap = ebs.create_snapshot(VolumeId=vol_id, Description="test snapshot")- snap_id = snap["SnapshotId"]- assert snap_id.startswith("snap-")- assert snap["State"] == "completed"-- desc = ebs.describe_snapshots(SnapshotIds=[snap_id])- assert len(desc["Snapshots"]) == 1- assert desc["Snapshots"][0]["VolumeId"] == vol_id- assert desc["Snapshots"][0]["Description"] == "test snapshot"--def test_ebs_delete_snapshot(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- snap = ebs.create_snapshot(VolumeId=vol["VolumeId"])- snap_id = snap["SnapshotId"]- ebs.delete_snapshot(SnapshotId=snap_id)- with pytest.raises(ClientError) as exc:- ebs.describe_snapshots(SnapshotIds=[snap_id])- assert exc.value.response["Error"]["Code"] == "InvalidSnapshot.NotFound"--def test_ebs_copy_snapshot(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- snap = ebs.create_snapshot(VolumeId=vol["VolumeId"], Description="original")- snap_id = snap["SnapshotId"]- copy = ebs.copy_snapshot(SourceRegion="us-east-1", SourceSnapshotId=snap_id, Description="copy")- new_snap_id = copy["SnapshotId"]- assert new_snap_id != snap_id- assert new_snap_id.startswith("snap-")--def test_ebs_snapshot_attribute(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- snap = ebs.create_snapshot(VolumeId=vol["VolumeId"], Description="attr test")- snap_id = snap["SnapshotId"]-- ebs.modify_snapshot_attribute(- SnapshotId=snap_id,- Attribute="createVolumePermission",- OperationType="add",- UserIds=["123456789012"],- )- resp = ebs.describe_snapshot_attribute(- SnapshotId=snap_id, Attribute="createVolumePermission"- )- assert resp["SnapshotId"] == snap_id- assert any(- p.get("UserId") == "123456789012"- for p in resp.get("CreateVolumePermissions", [])- )--def test_ebs_volume_attribute(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- resp = ebs.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")- assert resp["VolumeId"] == vol_id- assert "AutoEnableIO" in resp--def test_ebs_describe_volumes_modifications(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- ebs.modify_volume(VolumeId=vol_id, Size=50, VolumeType="gp3")- resp = ebs.describe_volumes_modifications(VolumeIds=[vol_id])- mods = resp["VolumesModifications"]- assert len(mods) >= 1- assert mods[0]["VolumeId"] == vol_id- assert mods[0]["TargetSize"] == 50- assert mods[0]["TargetVolumeType"] == "gp3"---def test_ebs_enable_volume_io(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- ebs.enable_volume_io(VolumeId=vol_id)- # Stub — just verify it doesn't error- resp = ebs.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")- assert resp["VolumeId"] == vol_id---def test_ebs_modify_volume_attribute(ebs):- vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")- vol_id = vol["VolumeId"]- ebs.modify_volume_attribute(VolumeId=vol_id, AutoEnableIO={"Value": True})- # Stub — just verify it doesn't error- resp = ebs.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")- assert resp["VolumeId"] == vol_iddiff --git a/tests/test_ec2.py b/tests/test_ec2.pyindex 840826f1..deb3ef68 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -1550,3 +1550,150 @@ def test_ec2_vpc_cidr_block_association_set(ec2):desc = ec2.describe_vpcs(VpcIds=[vpc["VpcId"]])["Vpcs"][0]assert len(desc.get("CidrBlockAssociationSet", [])) >= 1ec2.delete_vpc(VpcId=vpc["VpcId"])+++# ========== from test_ebs.py ==========+# EBS volumes / snapshots are EC2-service operations on AWS — same+# botocore client ("ec2"), same SigV4 scope. The conftest `ebs`+# fixture was a thin alias for `ec2`.+def test_ebs_create_and_describe_volume(ec2):+ resp = ec2.create_volume(+ AvailabilityZone="us-east-1a",+ Size=20,+ VolumeType="gp3",+ )+ vol_id = resp["VolumeId"]+ assert vol_id.startswith("vol-")+ assert resp["State"] == "available"+ assert resp["Size"] == 20+ assert resp["VolumeType"] == "gp3"++ desc = ec2.describe_volumes(VolumeIds=[vol_id])+ assert len(desc["Volumes"]) == 1+ assert desc["Volumes"][0]["VolumeId"] == vol_id++def test_ebs_attach_detach_volume(ec2):+ inst = ec2.run_instances(ImageId="ami-00000001", MinCount=1, MaxCount=1)+ instance_id = inst["Instances"][0]["InstanceId"]++ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]++ ec2.attach_volume(VolumeId=vol_id, InstanceId=instance_id, Device="/dev/xvdf")+ desc = ec2.describe_volumes(VolumeIds=[vol_id])+ assert desc["Volumes"][0]["State"] == "in-use"+ assert desc["Volumes"][0]["Attachments"][0]["InstanceId"] == instance_id++ ec2.detach_volume(VolumeId=vol_id)+ desc2 = ec2.describe_volumes(VolumeIds=[vol_id])+ assert desc2["Volumes"][0]["State"] == "available"+ assert desc2["Volumes"][0]["Attachments"] == []++def test_ebs_delete_volume(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=5, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ec2.delete_volume(VolumeId=vol_id)+ with pytest.raises(ClientError) as exc:+ ec2.describe_volumes(VolumeIds=[vol_id])+ assert exc.value.response["Error"]["Code"] == "InvalidVolume.NotFound"++def test_ebs_modify_volume(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ resp = ec2.modify_volume(VolumeId=vol_id, Size=50, VolumeType="gp3")+ assert resp["VolumeModification"]["TargetSize"] == 50+ assert resp["VolumeModification"]["TargetVolumeType"] == "gp3"++def test_ebs_volume_status(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=8, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ resp = ec2.describe_volume_status(VolumeIds=[vol_id])+ assert len(resp["VolumeStatuses"]) == 1+ assert resp["VolumeStatuses"][0]["VolumeStatus"]["Status"] == "ok"++def test_ebs_create_and_describe_snapshot(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ snap = ec2.create_snapshot(VolumeId=vol_id, Description="test snapshot")+ snap_id = snap["SnapshotId"]+ assert snap_id.startswith("snap-")+ assert snap["State"] == "completed"++ desc = ec2.describe_snapshots(SnapshotIds=[snap_id])+ assert len(desc["Snapshots"]) == 1+ assert desc["Snapshots"][0]["VolumeId"] == vol_id+ assert desc["Snapshots"][0]["Description"] == "test snapshot"++def test_ebs_delete_snapshot(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ snap = ec2.create_snapshot(VolumeId=vol["VolumeId"])+ snap_id = snap["SnapshotId"]+ ec2.delete_snapshot(SnapshotId=snap_id)+ with pytest.raises(ClientError) as exc:+ ec2.describe_snapshots(SnapshotIds=[snap_id])+ assert exc.value.response["Error"]["Code"] == "InvalidSnapshot.NotFound"++def test_ebs_copy_snapshot(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ snap = ec2.create_snapshot(VolumeId=vol["VolumeId"], Description="original")+ snap_id = snap["SnapshotId"]+ copy = ec2.copy_snapshot(SourceRegion="us-east-1", SourceSnapshotId=snap_id, Description="copy")+ new_snap_id = copy["SnapshotId"]+ assert new_snap_id != snap_id+ assert new_snap_id.startswith("snap-")++def test_ebs_snapshot_attribute(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ snap = ec2.create_snapshot(VolumeId=vol["VolumeId"], Description="attr test")+ snap_id = snap["SnapshotId"]++ ec2.modify_snapshot_attribute(+ SnapshotId=snap_id,+ Attribute="createVolumePermission",+ OperationType="add",+ UserIds=["123456789012"],+ )+ resp = ec2.describe_snapshot_attribute(+ SnapshotId=snap_id, Attribute="createVolumePermission"+ )+ assert resp["SnapshotId"] == snap_id+ assert any(+ p.get("UserId") == "123456789012"+ for p in resp.get("CreateVolumePermissions", [])+ )++def test_ebs_volume_attribute(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ resp = ec2.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")+ assert resp["VolumeId"] == vol_id+ assert "AutoEnableIO" in resp++def test_ebs_describe_volumes_modifications(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ec2.modify_volume(VolumeId=vol_id, Size=50, VolumeType="gp3")+ resp = ec2.describe_volumes_modifications(VolumeIds=[vol_id])+ mods = resp["VolumesModifications"]+ assert len(mods) >= 1+ assert mods[0]["VolumeId"] == vol_id+ assert mods[0]["TargetSize"] == 50+ assert mods[0]["TargetVolumeType"] == "gp3"+++def test_ebs_enable_volume_io(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ec2.enable_volume_io(VolumeId=vol_id)+ # Stub — just verify it doesn't error+ resp = ec2.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")+ assert resp["VolumeId"] == vol_id+++def test_ebs_modify_volume_attribute(ec2):+ vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ec2.modify_volume_attribute(VolumeId=vol_id, AutoEnableIO={"Value": True})+ # Stub — just verify it doesn't error+ resp = ec2.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")+ assert resp["VolumeId"] == vol_iddiff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex 88a4803c..0b94886e 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -647,140 +647,144 @@ def test_serverless_cache_not_implemented(ec):)-# ----------------------------------------------------------------------------# 12. Cluster-mode (real sharded redis) — opt-in, requires Docker + network-# ----------------------------------------------------------------------------def _cluster_mode_env_ready():- """True only if the host can actually exercise the cluster-mode path:- the flag is set, DOCKER_NETWORK is set, and `docker` is importable+usable.- """- if os.environ.get("ELASTICACHE_CLUSTER_MODE_REAL") != "1":- return False- if not os.environ.get("DOCKER_NETWORK"):- return False- try:- import docker- client = docker.from_env()- client.ping()- return True- except Exception:- return False+# ========== from test_elasticache_lambda_network.py ==========+# ElastiCache+Lambda network reachability via DOCKER_NETWORK auto-detect.+import io+import json+import os+import time+import zipfile+import pytest- not _cluster_mode_env_ready(),- reason="cluster-mode requires ELASTICACHE_CLUSTER_MODE_REAL=1 + DOCKER_NETWORK + docker",+pytestmark = pytest.mark.skipif(+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set — skipping network connectivity test",)-def test_elasticache_real_cluster_mode(ec):- """Bootstraps a real 3-shard redis cluster via redis-cli and verifies- CLUSTER SLOTS topology + cluster-aware SET/GET via an ephemeral client- container on the same network."""- import subprocess- rg_id = "pytest-cluster"- network = os.environ["DOCKER_NETWORK"]-- # Cleanup any leftover from a prior aborted run.- try:- ec.delete_replication_group(ReplicationGroupId=rg_id)- time.sleep(2)- except ClientError:- pass- resp = ec.create_replication_group(- ReplicationGroupId=rg_id,- ReplicationGroupDescription="pytest cluster mode",- CacheNodeType="cache.t3.micro",+_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"+++def _make_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def _make_zip_js(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.js", code)+ return buf.getvalue()+++def test_elasticache_lambda_network_connectivity(ec, lam):+ """Prove that Lambda containers can TCP-connect to an ElastiCache container."""+ cluster_id = "net-test-redis"+ fn_py = "ec-net-test-py"+ fn_js = "ec-net-test-js"++ # 1. Create ElastiCache Redis cluster+ ec.create_cache_cluster(+ CacheClusterId=cluster_id,Engine="redis",- EngineVersion="7.0.12",- NumNodeGroups=3,- ReplicasPerNodeGroup=1,+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,)- rg = resp["ReplicationGroup"]- assert rg["ClusterEnabled"] is True- assert len(rg["NodeGroups"]) == 3- config_ep = rg["ConfigurationEndpoint"]- assert config_ep and config_ep["Port"] == 6379-- def cli(args):- cmd = (- ["docker", "run", "--rm", "--network", network, "redis:7-alpine", "redis-cli"]- + args- )- return subprocess.run(cmd, capture_output=True, text=True, timeout=15)-- info = cli(["-h", config_ep["Address"], "-p", "6379", "CLUSTER", "INFO"]).stdout- assert "cluster_state:ok" in info, info- assert "cluster_known_nodes:6" in info, info- assert "cluster_size:3" in info, info- for k, v in [("alpha", "1"), ("beta", "2"), ("gamma", "3"), ("delta", "4")]:- r = cli(["-c", "-h", config_ep["Address"], "-p", "6379", "SET", k, v])- assert r.returncode == 0 and r.stdout.strip() == "OK", r.stdout + r.stderr- r = cli(["-c", "-h", config_ep["Address"], "-p", "6379", "GET", k])- assert r.stdout.strip() == v, r.stdout+ try:+ resp = ec.describe_cache_clusters(CacheClusterId=cluster_id)+ cluster = resp["CacheClusters"][0]+ node = cluster["CacheNodes"][0]+ host = node["Endpoint"]["Address"]+ port = int(node["Endpoint"]["Port"])++ # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set+ assert host not in ("localhost", "redis"), (+ f"Expected container IP, got '{host}' — DOCKER_NETWORK not working"+ )- ec.delete_replication_group(ReplicationGroupId=rg_id)- time.sleep(1)- leftover = subprocess.run(- ["docker", "ps", "-a", "--filter", f"label=rg_id={rg_id}", "--format", "{{.Names}}"],- capture_output=True, text=True,- ).stdout.strip()- assert leftover == "", f"leftover containers after delete: {leftover}"----# ========== Regression: AWS XML list wrappers (issue #530) ==========-# ElastiCache list responses must use the AWS-spec locationName for each-# list (e.g. <CacheCluster> for CacheClusterList.member) — NOT <member>.-# Strict generated SDKs (aws-sdk-go-v2, Java/Rust v2) parse a <member>--# wrapped list as empty when the model declares a custom locationName.-# botocore is permissive and accepts both, so a boto3-only test cannot-# catch this — these tests assert on the wire shape via raw HTTP.---def test_describe_cache_clusters_wraps_in_cachecluster_not_member():- """Real AWS uses <CacheCluster>...</CacheCluster> for each list item;- aws-sdk-go-v2 sees an empty CacheClusters slice if we emit <member>."""- import urllib.request- cluster_id = f"shape-test-{_uuid_mod.uuid4().hex[:8]}"- create = urllib.request.urlopen(urllib.request.Request(- f"{ENDPOINT}/",- data=(- f"Action=CreateCacheCluster&Version=2015-02-02"- f"&CacheClusterId={cluster_id}&CacheNodeType=cache.t3.micro"- f"&Engine=redis&NumCacheNodes=1"- ).encode(),- headers={"Content-Type": "application/x-www-form-urlencoded"},- method="POST",- ))- create.read()+ # 3. Wait for Redis container to accept connections+ import socket+ deadline = time.time() + 60+ while time.time() < deadline:+ try:+ with socket.create_connection((host, port), timeout=2):+ break+ except OSError:+ time.sleep(1)+ else:+ pytest.fail(f"ElastiCache container at {host}:{port} not reachable after 60s")++ # 4. Python Lambda — TCP connect to ElastiCache endpoint+ py_code = f"""\+import socket, json+def handler(event, context):try:- resp = urllib.request.urlopen(urllib.request.Request(- f"{ENDPOINT}/",- data=(- f"Action=DescribeCacheClusters&Version=2015-02-02"- f"&CacheClusterId={cluster_id}"- ).encode(),- headers={"Content-Type": "application/x-www-form-urlencoded"},- method="POST",- ))- body = resp.read().decode()- assert "<CacheCluster>" in body, (- "DescribeCacheClusters list items must be wrapped in "- "<CacheCluster> per AWS shape — strict SDKs (aws-sdk-go-v2, "- "Java/Rust v2) parse a <member>-wrapped list as empty (#530)."+ s = socket.create_connection(("{host}", {port}), timeout=5)+ s.close()+ return {{"connected": True}}+ except Exception as e:+ return {{"connected": False, "error": str(e)}}+"""+ lam.create_function(+ FunctionName=fn_py,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(py_code)},+ Timeout=15,)- assert "<member><CacheClusterId>" not in body, (- "Found legacy <member> wrapper for cluster — regression of #530"++ resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"Python Lambda failed: {result}"++ # 5. JS Lambda — TCP connect to ElastiCache endpoint+ js_code = f"""\+const net = require("net");+exports.handler = async (event) => {{+ return new Promise((resolve) => {{+ const sock = new net.Socket();+ sock.setTimeout(5000);+ sock.connect({port}, "{host}", () => {{+ sock.destroy();+ resolve({{ connected: true }});+ }});+ sock.on("error", (err) => {{+ sock.destroy();+ resolve({{ connected: false, error: err.message }});+ }});+ sock.on("timeout", () => {{+ sock.destroy();+ resolve({{ connected: false, error: "timeout" }});+ }});+ }});+}};+"""+ lam.create_function(+ FunctionName=fn_js,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip_js(js_code)},+ Timeout=15,)++ resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"JS Lambda failed: {result}"+finally:- urllib.request.urlopen(urllib.request.Request(- f"{ENDPOINT}/",- data=(- f"Action=DeleteCacheCluster&Version=2015-02-02"- f"&CacheClusterId={cluster_id}"- ).encode(),- headers={"Content-Type": "application/x-www-form-urlencoded"},- method="POST",- )).read()+ # 6. Cleanup+ for fn in (fn_py, fn_js):+ try:+ lam.delete_function(FunctionName=fn)+ except Exception:+ pass+ try:+ ec.delete_cache_cluster(CacheClusterId=cluster_id)+ except Exception:+ passdiff --git a/tests/test_elasticache_lambda_network.py b/tests/test_elasticache_lambda_network.pydeleted file mode 100644index 69222c0c..00000000--- a/tests/test_elasticache_lambda_network.py+++ /dev/null@@ -1,143 +0,0 @@-"""-E2E test: Lambda containers can reach ElastiCache containers over DOCKER_NETWORK.--Skipped when DOCKER_NETWORK is not set (requires Docker networking).-"""-import io-import json-import os-import time-import zipfile--import pytest--pytestmark = pytest.mark.skipif(- not os.environ.get("DOCKER_NETWORK"),- reason="DOCKER_NETWORK not set — skipping network connectivity test",-)--_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"---def _make_zip(code: str) -> bytes:- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("index.py", code)- return buf.getvalue()---def _make_zip_js(code: str) -> bytes:- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("index.js", code)- return buf.getvalue()---def test_elasticache_lambda_network_connectivity(ec, lam):- """Prove that Lambda containers can TCP-connect to an ElastiCache container."""- cluster_id = "net-test-redis"- fn_py = "ec-net-test-py"- fn_js = "ec-net-test-js"-- # 1. Create ElastiCache Redis cluster- ec.create_cache_cluster(- CacheClusterId=cluster_id,- Engine="redis",- CacheNodeType="cache.t3.micro",- NumCacheNodes=1,- )-- try:- resp = ec.describe_cache_clusters(CacheClusterId=cluster_id)- cluster = resp["CacheClusters"][0]- node = cluster["CacheNodes"][0]- host = node["Endpoint"]["Address"]- port = int(node["Endpoint"]["Port"])-- # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set- assert host not in ("localhost", "redis"), (- f"Expected container IP, got '{host}' — DOCKER_NETWORK not working"- )-- # 3. Wait for Redis container to accept connections- import socket- deadline = time.time() + 60- while time.time() < deadline:- try:- with socket.create_connection((host, port), timeout=2):- break- except OSError:- time.sleep(1)- else:- pytest.fail(f"ElastiCache container at {host}:{port} not reachable after 60s")-- # 4. Python Lambda — TCP connect to ElastiCache endpoint- py_code = f"""\-import socket, json-def handler(event, context):- try:- s = socket.create_connection(("{host}", {port}), timeout=5)- s.close()- return {{"connected": True}}- except Exception as e:- return {{"connected": False, "error": str(e)}}-"""- lam.create_function(- FunctionName=fn_py,- Runtime="python3.12",- Role=_LAMBDA_ROLE,- Handler="index.handler",- Code={"ZipFile": _make_zip(py_code)},- Timeout=15,- )-- resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))- result = json.loads(resp["Payload"].read())- assert result.get("connected") is True, f"Python Lambda failed: {result}"-- # 5. JS Lambda — TCP connect to ElastiCache endpoint- js_code = f"""\-const net = require("net");-exports.handler = async (event) => {{- return new Promise((resolve) => {{- const sock = new net.Socket();- sock.setTimeout(5000);- sock.connect({port}, "{host}", () => {{- sock.destroy();- resolve({{ connected: true }});- }});- sock.on("error", (err) => {{- sock.destroy();- resolve({{ connected: false, error: err.message }});- }});- sock.on("timeout", () => {{- sock.destroy();- resolve({{ connected: false, error: "timeout" }});- }});- }});-}};-"""- lam.create_function(- FunctionName=fn_js,- Runtime="nodejs20.x",- Role=_LAMBDA_ROLE,- Handler="index.handler",- Code={"ZipFile": _make_zip_js(js_code)},- Timeout=15,- )-- resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))- result = json.loads(resp["Payload"].read())- assert result.get("connected") is True, f"JS Lambda failed: {result}"-- finally:- # 6. Cleanup- for fn in (fn_py, fn_js):- try:- lam.delete_function(FunctionName=fn)- except Exception:- pass- try:- ec.delete_cache_cluster(CacheClusterId=cluster_id)- except Exception:- passdiff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex c031ad06..b6e304b1 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -642,7 +642,8 @@ def test_persistence_s3_writes_state_after_ownership_and_public_access_block(tmp# Unit tests for _S3_VHOST_RE / _S3_VHOST_EXCLUDE_RE / _NON_S3_VHOST_NAMES# ----------------------------------------------------------------------------from ministack.app import _S3_VHOST_EXCLUDE_RE, _NON_S3_VHOST_NAMES+from ministack.app import _NON_S3_VHOST_NAMES, _S3_VHOST_EXCLUDE_RE+class TestS3VhostExcludeRe:"""_S3_VHOST_EXCLUDE_RE gates out sub-service hostnames that look like vhosts."""diff --git a/tests/test_misc_medium_low_fixes.py b/tests/test_misc_medium_low_fixes.pydeleted file mode 100644index 637a9332..00000000--- a/tests/test_misc_medium_low_fixes.py+++ /dev/null@@ -1,165 +0,0 @@-"""-Regression tests for three medium/low correctness bugs:-- - apigateway + apigateway_v1 get_state() returned live- AccountScopedDict references rather than deep copies. A- concurrent write during shutdown serialisation could corrupt- the persisted snapshot.-- - secretsmanager._delete_secret(force=True) deleted the secret- record but left orphan entries in `_resource_policies` (keyed- by ARN) — invisible to the API but accumulating in memory and- surviving warm-boot via the persistence path.-- - acm._list_certificates returned `{"NextToken": null}`- unconditionally. Real AWS omits the key when there is no next- page; SDK consumers that paginate via- `if "NextToken" in response` will loop forever.--Each test bypasses boto3 to inspect a layer it would otherwise hide:-in-process module state for the first two, or the wire-level JSON-before client-side null-stripping for the NextToken case.-"""-import importlib-import json-import os-import urllib.request--import pytest--# Match the project convention from tests/conftest.py — honours-# `MINISTACK_ENDPOINT` so tests run unchanged against a non-default-# host / port (Docker networking, alternate CI bind, etc.).-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")---def _module(name):- return importlib.import_module(f"ministack.services.{name}")---# ── apigateway / apigateway_v1 get_state must deep-copy ───────────────-[email protected]("mod_name", ["apigateway", "apigateway_v1"])-def test_apigateway_get_state_returns_independent_copy(mod_name):- """`get_state()` must return a snapshot decoupled from live module- state — i.e. a `copy.deepcopy()` of each dict, not the live- reference. If it returns the live ref, a concurrent write during- shutdown serialisation corrupts the persisted JSON.-- Asserted by identity (`is not`) on every dict returned: each value- in the snapshot must be a different Python object than the- corresponding module-level state dict, so any subsequent mutation- on either side cannot affect the other."""- mod = _module(mod_name)- if hasattr(mod, "reset"):- mod.reset()-- snapshot = mod.get_state()-- leaks = []- for key, snap_value in snapshot.items():- live = getattr(mod, f"_{key}", None)- if live is None:- continue # snapshot key without a matching `_key` attr- if snap_value is live:- leaks.append(key)-- assert not leaks, (- f"{mod_name}.get_state() returned LIVE references for these keys: "- f"{leaks}. A concurrent write to one of these dicts during "- "shutdown serialisation would corrupt the persisted JSON. "- f"Wrap each value in `copy.deepcopy(...)`."- )-- if hasattr(mod, "reset"):- mod.reset()---# ── secretsmanager force-delete must clean up orphan policies ─────────--def test_secretsmanager_force_delete_removes_resource_policy():- """ForceDeleteWithoutRecovery must remove not just the secret but- also its associated `_resource_policies[arn]` entry. Otherwise the- policy lingers as an orphan referenced by an ARN no longer in- `_secrets` — invisible to APIs but accumulating in memory.-- Tests the in-process module directly (rather than via boto3- against the live server) so the assertion can observe both the- `_secrets` and `_resource_policies` dicts together."""- sm = _module("secretsmanager")- sm.reset()-- # Stage 1: create a secret with a resource policy via the module's- # action handlers, mirroring what boto3 -> handle_request would do.- create_resp = json.loads(_invoke_action(- sm, "CreateSecret",- {"Name": "force-delete-canary", "SecretString": "x"},- ))- arn = create_resp["ARN"]- _invoke_action(sm, "PutResourcePolicy", {- "SecretId": arn,- "ResourcePolicy": '{"Version":"2012-10-17","Statement":[]}',- })- assert arn in sm._resource_policies, "Test setup failed — policy didn't register"-- # Stage 2: force-delete.- _invoke_action(sm, "DeleteSecret", {- "SecretId": arn,- "ForceDeleteWithoutRecovery": True,- })-- # Stage 3: assert the policy entry is also gone.- assert arn not in sm._resource_policies, (- "Force-deleting a secret left an orphan entry in "- "`_resource_policies` keyed by the now-deleted ARN. The "- "delete path must pop both `_secrets[name]` AND "- "`_resource_policies[arn]`."- )- sm.reset()---def _invoke_action(mod, action, params):- """Mini-helper: run a service module's action handler synchronously- and return the raw JSON body. Bypasses boto3 + HTTP so tests can- observe in-process module state."""- import asyncio- headers = {"x-amz-target": f"secretsmanager.{action}"}- body = json.dumps(params).encode()- status, _resp_headers, resp_body = asyncio.run(- mod.handle_request("POST", "/", headers, body, {})- )- if status >= 300:- raise AssertionError(f"{action} failed: {status} {resp_body!r}")- return resp_body.decode() if isinstance(resp_body, bytes) else resp_body---# ── ACM ListCertificates must omit NextToken when no more pages ───────--def test_acm_list_certificates_omits_nexttoken_when_no_more_pages():- """Returning `{"NextToken": null}` is non-standard AWS — real AWS- omits the key. boto3 strips null fields client-side so a boto3-- only test can't see this, but other SDKs (Java, Go, raw HTTP) and- pagination loops checking `if "NextToken" in response` see the- literal null and loop forever.-- Asserted at the wire level via raw HTTP to bypass boto3's null- stripping."""- req = urllib.request.Request(- ENDPOINT.rstrip("/") + "/",- method="POST",- headers={- "x-amz-target": "CertificateManager.ListCertificates",- "Content-Type": "application/x-amz-json-1.1",- "Authorization": "AWS4-HMAC-SHA256 Credential=test/x/us-east-1/acm/aws4_request",- },- data=b"{}",- )- body = json.loads(urllib.request.urlopen(req, timeout=5).read())-- assert "NextToken" not in body, (- f"ListCertificates wire response contains NextToken when "- f"there is no next page (got {body.get('NextToken')!r}). "- "Real AWS omits the key. SDK consumers checking "- "`if 'NextToken' in response` (Java, Go, raw HTTP — boto3 "- "strips nulls) loop forever against a literal null."- )diff --git a/tests/test_persistence_symmetry.py b/tests/test_persistence.pysimilarity index 50%rename from tests/test_persistence_symmetry.pyrename to tests/test_persistence.pyindex 838ea673..01d64f03 100644--- a/tests/test_persistence_symmetry.py+++ b/tests/test_persistence.py@@ -305,3 +305,297 @@ def test_load_state_is_noop_when_persist_state_disabled(monkeypatch, svc_key, tmf"load_state({svc_key!r}) returned non-None even though ""PERSIST_STATE is False — restore must be gated.")+++# ========== from test_state_dict_persistence.py ==========+# Companion to the symmetry tests above. Symmetry tests check that+# *every service* participates in get_state/restore_state. These tests+# check that within services, *every AccountScopedDict mutated by the+# public API* is captured — the 'dict dropped from get_state' bug pattern.+import importlib++import pytest++from ministack.core import persistence+++def _get_module(mod_name):+ return importlib.import_module(f"ministack.services.{mod_name}")++[email protected](autouse=True)+def _enable_persistence_dict(monkeypatch, tmp_path):+ """Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the+ duration of each test so save_state / load_state actually write and+ read JSON files instead of short-circuiting."""+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+++def _round_trip_dict(mod, svc_key):+ """Simulate a full warm-boot through the on-disk JSON path.++ Going through `save_state` / `load_state` (rather than calling+ `get_state` / `restore_state` directly in-memory) catches encoder+ / decoder regressions AND import-order bugs (a `restore_state`+ that references a globals-only symbol declared further down the+ module would NameError on real warm-boot but pass an in-memory+ test that already has the symbol bound)."""+ persistence.save_state(svc_key, mod.get_state())+ mod.reset()+ loaded = persistence.load_state(svc_key)+ assert loaded is not None, (+ f"persistence.load_state({svc_key!r}) returned None — state "+ "file was not written by save_state()."+ )+ mod.restore_state(loaded)+++# ── secretsmanager._resource_policies ──────────────────────────────────++def test_secretsmanager_resource_policies_survive_warm_boot():+ """`PutResourcePolicy` writes to `_resource_policies`, but if that+ dict is missing from `get_state()` the policy is gone after restart.+ Terraform `aws_secretsmanager_secret_policy` would silently drop."""+ mod = _get_module("secretsmanager")+ mod.reset()+ arn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:my-secret-AbCdEf"+ mod._resource_policies[arn] = '{"Version":"2012-10-17","Statement":[]}'++ _round_trip_dict(mod, "secretsmanager")++ assert mod._resource_policies.get(arn) == '{"Version":"2012-10-17","Statement":[]}', (+ "Resource policy lost across get_state → restore_state — "+ "_resource_policies must be in both."+ )+ mod.reset()+++# ── kinesis._consumers ─────────────────────────────────────────────────++def test_kinesis_consumers_survive_warm_boot():+ """`RegisterStreamConsumer` writes to `_consumers`. Without+ persistence symmetry, every enhanced fan-out registration is lost on+ restart and `DescribeStreamConsumer` returns ResourceNotFoundException."""+ mod = _get_module("kinesis")+ mod.reset()+ consumer_arn = (+ "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream/consumer/c1:123"+ )+ mod._consumers[consumer_arn] = {+ "ConsumerARN": consumer_arn,+ "ConsumerName": "c1",+ "ConsumerStatus": "ACTIVE",+ "StreamARN": "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream",+ "ConsumerCreationTimestamp": 1700000000.0,+ }++ _round_trip_dict(mod, "kinesis")++ assert consumer_arn in mod._consumers, (+ "Kinesis consumer lost across get_state → restore_state — "+ "_consumers must be in both."+ )+ mod.reset()+++# ── ecs._attributes ────────────────────────────────────────────────────++def test_ecs_attributes_survive_warm_boot():+ """`PutAttributes` writes to `_attributes`. Lost on restart without+ persistence wiring."""+ mod = _get_module("ecs")+ mod.reset()+ mod._attributes["i-deadbeef:my-attr"] = {+ "name": "my-attr",+ "value": "v1",+ "targetType": "container-instance",+ "targetId": "i-deadbeef",+ }++ _round_trip_dict(mod, "ecs")++ assert "i-deadbeef:my-attr" in mod._attributes, (+ "ECS attribute lost across get_state → restore_state — "+ "_attributes must be in both."+ )+ mod.reset()+++# ── sns._platform_applications + sns._platform_endpoints ──────────────++def test_sns_platform_applications_survive_warm_boot():+ """`CreatePlatformApplication` writes to `_platform_applications`.+ Mobile push topology is lost on restart without persistence wiring."""+ mod = _get_module("sns")+ mod.reset()+ app_arn = "arn:aws:sns:us-east-1:000000000000:app/GCM/MyApp"+ mod._platform_applications[app_arn] = {+ "PlatformApplicationArn": app_arn,+ "Attributes": {"Platform": "GCM"},+ }++ _round_trip_dict(mod, "sns")++ assert app_arn in mod._platform_applications, (+ "SNS platform application lost across get_state → restore_state — "+ "_platform_applications must be in both."+ )+ mod.reset()+++def test_sns_platform_endpoints_survive_warm_boot():+ """`CreatePlatformEndpoint` writes to `_platform_endpoints`."""+ mod = _get_module("sns")+ mod.reset()+ ep_arn = "arn:aws:sns:us-east-1:000000000000:endpoint/GCM/MyApp/abc"+ mod._platform_endpoints[ep_arn] = {+ "EndpointArn": ep_arn,+ "Token": "device-token-xyz",+ "Enabled": "true",+ }++ _round_trip_dict(mod, "sns")++ assert ep_arn in mod._platform_endpoints, (+ "SNS platform endpoint lost across get_state → restore_state — "+ "_platform_endpoints must be in both."+ )+ mod.reset()+++# ── Import-order regression for the ECS NameError trap ───────────────++def test_ecs_module_reload_with_persisted_attributes_does_not_namerror():+ """Regression for the import-order trap: `restore_state()` runs at+ module import time (via the `try: load_state("ecs")` block at the+ bottom of services/ecs.py). If `_attributes` is declared AFTER that+ block, the restore call NameErrors and the surrounding try/except+ silently swallows it — wiping all ECS state on warm-boot.++ This test simulates a real warm-boot: write a populated `ecs.json`+ to STATE_DIR, then `importlib.reload()` the module so the load_state+ block runs against the file. If `_attributes` (or any other+ referenced symbol) is declared too late, the restored state will+ be missing because the entire restore_state body crashed."""+ mod = _get_module("ecs")+ mod.reset()+ arn = "arn:aws:ecs:us-east-1:000000000000:cluster/reload-canary"+ mod._clusters[arn] = {"clusterArn": arn, "status": "ACTIVE"}+ mod._attributes["i-canary:reload-attr"] = {+ "name": "reload-attr",+ "value": "v",+ "targetType": "container-instance",+ "targetId": "i-canary",+ }++ # Persist via the same path save_all uses on shutdown.+ persistence.save_state("ecs", mod.get_state())++ # Force a full reload so the module-level try/load_state/restore_state+ # block at the bottom of ecs.py executes against the on-disk JSON.+ importlib.reload(mod)++ assert arn in mod._clusters, (+ "Cluster lost after reload — likely NameError in restore_state "+ "swallowed by the try/except. Check that every referenced state "+ "dict (_attributes etc.) is declared BEFORE the load_state block."+ )+ assert "i-canary:reload-attr" in mod._attributes, (+ "ECS _attributes lost after reload — same root cause."+ )+ mod.reset()+++# ── Generic NameError-at-import regression for ALL persisted services ─++def _persisted_services():+ """Return a sorted list of ``(svc_key, mod_name)`` pairs from+ ``ministack.app._state_map``.++ Evaluated by ``@pytest.mark.parametrize(...)`` at test collection+ time — `_state_map` is therefore imported when pytest collects this+ module, NOT lazily per test case. (Calling it inside the parametrize+ decorator means it runs once, at collection.)"""+ from ministack.app import _state_map+ return sorted(_state_map.items())++[email protected]("svc_key,mod_name", _persisted_services())+def test_module_cold_import_with_typical_snapshot_does_not_log_restore_failure(+ svc_key, mod_name, caplog,+):+ """Generic regression for the NameError-at-import pattern that hit+ `ecs._attributes` (#492) and `acm._synthetic_pem` (#494).++ The bug shape: `restore_state(data)` references a module-level+ symbol declared further down the file. The import-time `try:+ load_state(...)` block calls `restore_state()` BEFORE Python+ evaluates the later definition, so the lookup NameErrors. The+ surrounding try/except logs `Failed to restore persisted state` and+ swallows the exception, so the module appears to import cleanly+ while ALL its persisted state silently disappears.++ The test:+ 1. Captures the module's current `get_state()` snapshot (a+ non-empty dict-of-empty-dicts — important so `restore_state`+ doesn't early-return on truthy emptiness checks).+ 2. Persists that to disk via the production `save_state` path.+ 3. **Removes the module from `sys.modules` and re-imports it+ fresh** — `importlib.reload()` would NOT catch the bug+ because it merges new definitions into the existing+ namespace, leaving any late-declared symbol bound from the+ previous import.+ 4. Asserts no WARNING+ log record mentioning "restore" / "failed"+ / "continuing fresh" was emitted during the cold import.++ Catches: unconditional symbol references in restore_state+ (ECS-style). Does NOT catch: conditional references inside loops+ over restored data when the data is empty (ACM-style needs+ populated state — see the per-service tests above).+ """+ import sys++ # Persistence is already enabled and STATE_DIR is already pointed at+ # a per-test tmp by the autouse `_enable_persistence_dict` fixture.++ # Step 1+2: produce + persist a snapshot using the already-loaded+ # module (so we get a valid get_state() shape).+ mod = _get_module(mod_name)+ if hasattr(mod, "reset"):+ mod.reset()+ persistence.save_state(svc_key, mod.get_state())++ # Step 3: cold-import — wipe sys.modules and re-import.+ # importlib.reload() won't work because it merges into the+ # existing namespace; the late-declared symbol stays bound from+ # the prior import.+ full_name = f"ministack.services.{mod_name}"+ sys.modules.pop(full_name, None)++ caplog.clear()+ with caplog.at_level("WARNING"):+ mod = importlib.import_module(full_name)++ bad = [+ r for r in caplog.records+ if r.levelno >= 30 # WARNING++ and any(needle in r.getMessage().lower()+ for needle in ("failed to restore", "restore failed",+ "continuing fresh", "continuing with fresh"))+ ]+ if hasattr(mod, "reset"):+ mod.reset()++ assert not bad, (+ f"Cold import of `{mod_name}` (state-key `{svc_key}`) emitted "+ f"a restore-failure log:\n "+ + "\n ".join(r.getMessage() for r in bad)+ + "\n\nThis usually means `restore_state` references a "+ "module-level symbol that's declared further down the file. "+ "The import-time `try: load_state()` block runs before the "+ "later definition, so the symbol lookup NameErrors and the "+ "surrounding try/except swallows it. Hoist the symbol above "+ "the import-time `load_state` block (see ECS `_attributes` "+ "or ACM `_synthetic_pem` for the canonical fix)."+ )diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 6e9e6f4d..2121d8cd 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -97,7 +97,7 @@ def test_rds_delete_instance_v2(rds):rds.delete_db_instance(DBInstanceIdentifier="rds-del-v2", SkipFinalSnapshot=True)with pytest.raises(ClientError) as exc:rds.describe_db_instances(DBInstanceIdentifier="rds-del-v2")- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"def test_rds_modify_instance_v2(rds):rds.create_db_instance(@@ -874,7 +874,7 @@ def test_rds_create_read_replica_source_not_found(rds):DBInstanceIdentifier="rr-orphan",SourceDBInstanceIdentifier="rr-nonexistent",)- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"def test_rds_reboot_db_instance(rds):@@ -901,7 +901,7 @@ def test_rds_reboot_db_instance_not_found(rds):"""RebootDBInstance fails for a non-existent instance."""with pytest.raises(ClientError) as exc:rds.reboot_db_instance(DBInstanceIdentifier="no-such-instance")- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"def test_rds_restore_from_snapshot(rds):@@ -985,7 +985,7 @@ def test_rds_start_db_instance_not_found(rds):"""StartDBInstance fails for a non-existent instance."""with pytest.raises(ClientError) as exc:rds.start_db_instance(DBInstanceIdentifier="ghost-instance")- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"def test_rds_stop_db_instance(rds):@@ -1012,7 +1012,7 @@ def test_rds_stop_db_instance_not_found(rds):"""StopDBInstance fails for a non-existent instance."""with pytest.raises(ClientError) as exc:rds.stop_db_instance(DBInstanceIdentifier="ghost-instance-2")- assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFound"def test_rds_describe_option_group_options(rds):@@ -1202,3 +1202,159 @@ def test_rds_create_db_instance_postgres_18(rds):assert "Address" in inst["Endpoint"]finally:rds.delete_db_instance(DBInstanceIdentifier="pg18-test", SkipFinalSnapshot=True)+++# ========== from test_rds_lambda_network.py ==========+# RDS+Lambda network reachability via DOCKER_NETWORK auto-detect.+import io+import json+import os+import time+import zipfile++import pytest++pytestmark = pytest.mark.skipif(+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set — skipping network connectivity test",+)++_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"+++def _make_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def _make_zip_js(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.js", code)+ return buf.getvalue()+++def _wait_for_rds(rds_client, db_id, timeout=120):+ """Poll DescribeDBInstances until the instance is available."""+ deadline = time.time() + timeout+ while time.time() < deadline:+ resp = rds_client.describe_db_instances(DBInstanceIdentifier=db_id)+ inst = resp["DBInstances"][0]+ if inst["DBInstanceStatus"] == "available":+ return inst+ time.sleep(2)+ raise TimeoutError(f"RDS instance {db_id} not available after {timeout}s")+++def test_rds_lambda_network_connectivity(rds, lam):+ """Prove that Lambda containers can TCP-connect to an RDS container."""+ db_id = "net-test-pg"+ fn_py = "rds-net-test-py"+ fn_js = "rds-net-test-js"++ # 1. Create RDS Postgres instance+ rds.create_db_instance(+ DBInstanceIdentifier=db_id,+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )++ try:+ inst = _wait_for_rds(rds, db_id)+ endpoint = inst["Endpoint"]+ host = endpoint["Address"]+ port = int(endpoint["Port"])++ # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set+ assert host != "localhost", (+ "Expected container IP, got 'localhost' — DOCKER_NETWORK not working"+ )++ # 3. Wait for the Postgres container to accept connections+ import socket+ deadline = time.time() + 60+ while time.time() < deadline:+ try:+ with socket.create_connection((host, port), timeout=2):+ break+ except OSError:+ time.sleep(1)+ else:+ pytest.fail(f"RDS container at {host}:{port} not reachable after 60s")++ # 4. Python Lambda — TCP connect to RDS endpoint+ py_code = f"""\+import socket, json+def handler(event, context):+ try:+ s = socket.create_connection(("{host}", {port}), timeout=5)+ s.close()+ return {{"connected": True}}+ except Exception as e:+ return {{"connected": False, "error": str(e)}}+"""+ lam.create_function(+ FunctionName=fn_py,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(py_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"Python Lambda failed: {result}"++ # 5. JS Lambda — TCP connect to RDS endpoint+ js_code = f"""\+const net = require("net");+exports.handler = async (event) => {{+ return new Promise((resolve) => {{+ const sock = new net.Socket();+ sock.setTimeout(5000);+ sock.connect({port}, "{host}", () => {{+ sock.destroy();+ resolve({{ connected: true }});+ }});+ sock.on("error", (err) => {{+ sock.destroy();+ resolve({{ connected: false, error: err.message }});+ }});+ sock.on("timeout", () => {{+ sock.destroy();+ resolve({{ connected: false, error: "timeout" }});+ }});+ }});+}};+"""+ lam.create_function(+ FunctionName=fn_js,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip_js(js_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"JS Lambda failed: {result}"++ finally:+ # 6. Cleanup+ for fn in (fn_py, fn_js):+ try:+ lam.delete_function(FunctionName=fn)+ except Exception:+ pass+ try:+ rds.delete_db_instance(+ DBInstanceIdentifier=db_id, SkipFinalSnapshot=True+ )+ except Exception:+ passdiff --git a/tests/test_rds_lambda_network.py b/tests/test_rds_lambda_network.pydeleted file mode 100644index 34fd6702..00000000--- a/tests/test_rds_lambda_network.py+++ /dev/null@@ -1,157 +0,0 @@-"""-E2E test: Lambda containers can reach RDS containers over DOCKER_NETWORK.--Skipped when DOCKER_NETWORK is not set (requires Docker networking).-"""-import io-import json-import os-import time-import zipfile--import pytest--pytestmark = pytest.mark.skipif(- not os.environ.get("DOCKER_NETWORK"),- reason="DOCKER_NETWORK not set — skipping network connectivity test",-)--_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"---def _make_zip(code: str) -> bytes:- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("index.py", code)- return buf.getvalue()---def _make_zip_js(code: str) -> bytes:- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("index.js", code)- return buf.getvalue()---def _wait_for_rds(rds_client, db_id, timeout=120):- """Poll DescribeDBInstances until the instance is available."""- deadline = time.time() + timeout- while time.time() < deadline:- resp = rds_client.describe_db_instances(DBInstanceIdentifier=db_id)- inst = resp["DBInstances"][0]- if inst["DBInstanceStatus"] == "available":- return inst- time.sleep(2)- raise TimeoutError(f"RDS instance {db_id} not available after {timeout}s")---def test_rds_lambda_network_connectivity(rds, lam):- """Prove that Lambda containers can TCP-connect to an RDS container."""- db_id = "net-test-pg"- fn_py = "rds-net-test-py"- fn_js = "rds-net-test-js"-- # 1. Create RDS Postgres instance- rds.create_db_instance(- DBInstanceIdentifier=db_id,- DBInstanceClass="db.t3.micro",- Engine="postgres",- MasterUsername="admin",- MasterUserPassword="password123",- )-- try:- inst = _wait_for_rds(rds, db_id)- endpoint = inst["Endpoint"]- host = endpoint["Address"]- port = int(endpoint["Port"])-- # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set- assert host != "localhost", (- "Expected container IP, got 'localhost' — DOCKER_NETWORK not working"- )-- # 3. Wait for the Postgres container to accept connections- import socket- deadline = time.time() + 60- while time.time() < deadline:- try:- with socket.create_connection((host, port), timeout=2):- break- except OSError:- time.sleep(1)- else:- pytest.fail(f"RDS container at {host}:{port} not reachable after 60s")-- # 4. Python Lambda — TCP connect to RDS endpoint- py_code = f"""\-import socket, json-def handler(event, context):- try:- s = socket.create_connection(("{host}", {port}), timeout=5)- s.close()- return {{"connected": True}}- except Exception as e:- return {{"connected": False, "error": str(e)}}-"""- lam.create_function(- FunctionName=fn_py,- Runtime="python3.12",- Role=_LAMBDA_ROLE,- Handler="index.handler",- Code={"ZipFile": _make_zip(py_code)},- Timeout=15,- )-- resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))- result = json.loads(resp["Payload"].read())- assert result.get("connected") is True, f"Python Lambda failed: {result}"-- # 5. JS Lambda — TCP connect to RDS endpoint- js_code = f"""\-const net = require("net");-exports.handler = async (event) => {{- return new Promise((resolve) => {{- const sock = new net.Socket();- sock.setTimeout(5000);- sock.connect({port}, "{host}", () => {{- sock.destroy();- resolve({{ connected: true }});- }});- sock.on("error", (err) => {{- sock.destroy();- resolve({{ connected: false, error: err.message }});- }});- sock.on("timeout", () => {{- sock.destroy();- resolve({{ connected: false, error: "timeout" }});- }});- }});-}};-"""- lam.create_function(- FunctionName=fn_js,- Runtime="nodejs20.x",- Role=_LAMBDA_ROLE,- Handler="index.handler",- Code={"ZipFile": _make_zip_js(js_code)},- Timeout=15,- )-- resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))- result = json.loads(resp["Payload"].read())- assert result.get("connected") is True, f"JS Lambda failed: {result}"-- finally:- # 6. Cleanup- for fn in (fn_py, fn_js):- try:- lam.delete_function(FunctionName=fn)- except Exception:- pass- try:- rds.delete_db_instance(- DBInstanceIdentifier=db_id, SkipFinalSnapshot=True- )- except Exception:- passdiff --git a/tests/test_s3.py b/tests/test_s3.pyindex 18cac2ff..feccd182 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -4,8 +4,8 @@ from urllib.parse import urlparseimport pytestfrom botocore.exceptions import ClientError+from conftest import ENDPOINT_HOST, make_client, patch_endpoint_dns-from conftest import make_client, patch_endpoint_dns, ENDPOINT_HOSTdef test_s3_create_bucket(s3):s3.create_bucket(Bucket="intg-s3-create")diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.pyindex 4c32c41d..b70f3119 100644--- a/tests/test_secretsmanager.py+++ b/tests/test_secretsmanager.py@@ -362,3 +362,53 @@ def test_secretsmanager_list_include_planned_deletion(sm):assert entry is not Noneassert "DeletedDate" in entry+++# ========== from test_misc_medium_low_fixes.py ==========+# ForceDeleteWithoutRecovery must clean up the orphan _resource_policies[arn]+# entry, not just the _secrets[name] entry. Tests the in-process module+# directly so it can observe both dicts together.++import asyncio as _sm_asyncio+import importlib as _sm_importlib+import json as _sm_json+++def _sm_invoke_action(mod, action, params):+ """Run a service module's action handler synchronously, return raw JSON body."""+ headers = {"x-amz-target": f"secretsmanager.{action}"}+ body = _sm_json.dumps(params).encode()+ status, _resp_headers, resp_body = _sm_asyncio.run(+ mod.handle_request("POST", "/", headers, body, {})+ )+ if status >= 300:+ raise AssertionError(f"{action} failed: {status} {resp_body!r}")+ return resp_body.decode() if isinstance(resp_body, bytes) else resp_body+++def test_secretsmanager_force_delete_removes_resource_policy():+ sm = _sm_importlib.import_module("ministack.services.secretsmanager")+ sm.reset()++ create_resp = _sm_json.loads(_sm_invoke_action(+ sm, "CreateSecret",+ {"Name": "force-delete-canary", "SecretString": "x"},+ ))+ arn = create_resp["ARN"]+ _sm_invoke_action(sm, "PutResourcePolicy", {+ "SecretId": arn,+ "ResourcePolicy": '{"Version":"2012-10-17","Statement":[]}',+ })+ assert arn in sm._resource_policies, "Test setup failed — policy didn't register"++ _sm_invoke_action(sm, "DeleteSecret", {+ "SecretId": arn,+ "ForceDeleteWithoutRecovery": True,+ })++ assert arn not in sm._resource_policies, (+ "Force-deleting a secret left an orphan entry in _resource_policies "+ "keyed by the now-deleted ARN. The delete path must pop both "+ "_secrets[name] AND _resource_policies[arn]."+ )+ sm.reset()diff --git a/tests/test_state_dict_persistence.py b/tests/test_state_dict_persistence.pydeleted file mode 100644index 1d18bbd1..00000000--- a/tests/test_state_dict_persistence.py+++ /dev/null@@ -1,307 +0,0 @@-"""-Regression tests for "state dict dropped from get_state/restore_state" bugs.--Pattern: a service exposes an API that mutates an `AccountScopedDict`,-but the dict is missing from `get_state()` and/or `restore_state()`. With-PERSIST_STATE=1, every record stored via that API silently disappears on-the next restart.--This file covers five distinct state-dict persistence drops:-- - secretsmanager._resource_policies- - kinesis._consumers (enhanced fan-out)- - ecs._attributes (PutAttributes / ListAttributes)- - sns._platform_applications- - sns._platform_endpoints--Each test populates the dict, snapshots state via the public-`get_state()` / `restore_state()` contract, simulates a restart, and-asserts the record survived.-"""-import importlib--import pytest--from ministack.core import persistence---def _module(mod_name):- return importlib.import_module(f"ministack.services.{mod_name}")--[email protected](autouse=True)-def _enable_persistence(monkeypatch, tmp_path):- """Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the- duration of each test so save_state / load_state actually write and- read JSON files instead of short-circuiting."""- monkeypatch.setattr(persistence, "PERSIST_STATE", True)- monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))---def _round_trip(mod, svc_key):- """Simulate a full warm-boot through the on-disk JSON path.-- Going through `save_state` / `load_state` (rather than calling- `get_state` / `restore_state` directly in-memory) catches encoder- / decoder regressions AND import-order bugs (a `restore_state`- that references a globals-only symbol declared further down the- module would NameError on real warm-boot but pass an in-memory- test that already has the symbol bound)."""- persistence.save_state(svc_key, mod.get_state())- mod.reset()- loaded = persistence.load_state(svc_key)- assert loaded is not None, (- f"persistence.load_state({svc_key!r}) returned None — state "- "file was not written by save_state()."- )- mod.restore_state(loaded)---# ── secretsmanager._resource_policies ──────────────────────────────────--def test_secretsmanager_resource_policies_survive_warm_boot():- """`PutResourcePolicy` writes to `_resource_policies`, but if that- dict is missing from `get_state()` the policy is gone after restart.- Terraform `aws_secretsmanager_secret_policy` would silently drop."""- mod = _module("secretsmanager")- mod.reset()- arn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:my-secret-AbCdEf"- mod._resource_policies[arn] = '{"Version":"2012-10-17","Statement":[]}'-- _round_trip(mod, "secretsmanager")-- assert mod._resource_policies.get(arn) == '{"Version":"2012-10-17","Statement":[]}', (- "Resource policy lost across get_state → restore_state — "- "_resource_policies must be in both."- )- mod.reset()---# ── kinesis._consumers ─────────────────────────────────────────────────--def test_kinesis_consumers_survive_warm_boot():- """`RegisterStreamConsumer` writes to `_consumers`. Without- persistence symmetry, every enhanced fan-out registration is lost on- restart and `DescribeStreamConsumer` returns ResourceNotFoundException."""- mod = _module("kinesis")- mod.reset()- consumer_arn = (- "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream/consumer/c1:123"- )- mod._consumers[consumer_arn] = {- "ConsumerARN": consumer_arn,- "ConsumerName": "c1",- "ConsumerStatus": "ACTIVE",- "StreamARN": "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream",- "ConsumerCreationTimestamp": 1700000000.0,- }-- _round_trip(mod, "kinesis")-- assert consumer_arn in mod._consumers, (- "Kinesis consumer lost across get_state → restore_state — "- "_consumers must be in both."- )- mod.reset()---# ── ecs._attributes ────────────────────────────────────────────────────--def test_ecs_attributes_survive_warm_boot():- """`PutAttributes` writes to `_attributes`. Lost on restart without- persistence wiring."""- mod = _module("ecs")- mod.reset()- mod._attributes["i-deadbeef:my-attr"] = {- "name": "my-attr",- "value": "v1",- "targetType": "container-instance",- "targetId": "i-deadbeef",- }-- _round_trip(mod, "ecs")-- assert "i-deadbeef:my-attr" in mod._attributes, (- "ECS attribute lost across get_state → restore_state — "- "_attributes must be in both."- )- mod.reset()---# ── sns._platform_applications + sns._platform_endpoints ──────────────--def test_sns_platform_applications_survive_warm_boot():- """`CreatePlatformApplication` writes to `_platform_applications`.- Mobile push topology is lost on restart without persistence wiring."""- mod = _module("sns")- mod.reset()- app_arn = "arn:aws:sns:us-east-1:000000000000:app/GCM/MyApp"- mod._platform_applications[app_arn] = {- "PlatformApplicationArn": app_arn,- "Attributes": {"Platform": "GCM"},- }-- _round_trip(mod, "sns")-- assert app_arn in mod._platform_applications, (- "SNS platform application lost across get_state → restore_state — "- "_platform_applications must be in both."- )- mod.reset()---def test_sns_platform_endpoints_survive_warm_boot():- """`CreatePlatformEndpoint` writes to `_platform_endpoints`."""- mod = _module("sns")- mod.reset()- ep_arn = "arn:aws:sns:us-east-1:000000000000:endpoint/GCM/MyApp/abc"- mod._platform_endpoints[ep_arn] = {- "EndpointArn": ep_arn,- "Token": "device-token-xyz",- "Enabled": "true",- }-- _round_trip(mod, "sns")-- assert ep_arn in mod._platform_endpoints, (- "SNS platform endpoint lost across get_state → restore_state — "- "_platform_endpoints must be in both."- )- mod.reset()---# ── Import-order regression for the ECS NameError trap ───────────────--def test_ecs_module_reload_with_persisted_attributes_does_not_namerror():- """Regression for the import-order trap: `restore_state()` runs at- module import time (via the `try: load_state("ecs")` block at the- bottom of services/ecs.py). If `_attributes` is declared AFTER that- block, the restore call NameErrors and the surrounding try/except- silently swallows it — wiping all ECS state on warm-boot.-- This test simulates a real warm-boot: write a populated `ecs.json`- to STATE_DIR, then `importlib.reload()` the module so the load_state- block runs against the file. If `_attributes` (or any other- referenced symbol) is declared too late, the restored state will- be missing because the entire restore_state body crashed."""- mod = _module("ecs")- mod.reset()- arn = "arn:aws:ecs:us-east-1:000000000000:cluster/reload-canary"- mod._clusters[arn] = {"clusterArn": arn, "status": "ACTIVE"}- mod._attributes["i-canary:reload-attr"] = {- "name": "reload-attr",- "value": "v",- "targetType": "container-instance",- "targetId": "i-canary",- }-- # Persist via the same path save_all uses on shutdown.- persistence.save_state("ecs", mod.get_state())-- # Force a full reload so the module-level try/load_state/restore_state- # block at the bottom of ecs.py executes against the on-disk JSON.- importlib.reload(mod)-- assert arn in mod._clusters, (- "Cluster lost after reload — likely NameError in restore_state "- "swallowed by the try/except. Check that every referenced state "- "dict (_attributes etc.) is declared BEFORE the load_state block."- )- assert "i-canary:reload-attr" in mod._attributes, (- "ECS _attributes lost after reload — same root cause."- )- mod.reset()---# ── Generic NameError-at-import regression for ALL persisted services ─--def _persisted_services():- """Return a sorted list of ``(svc_key, mod_name)`` pairs from- ``ministack.app._state_map``.-- Evaluated by ``@pytest.mark.parametrize(...)`` at test collection- time — `_state_map` is therefore imported when pytest collects this- module, NOT lazily per test case. (Calling it inside the parametrize- decorator means it runs once, at collection.)"""- from ministack.app import _state_map- return sorted(_state_map.items())--[email protected]("svc_key,mod_name", _persisted_services())-def test_module_cold_import_with_typical_snapshot_does_not_log_restore_failure(- svc_key, mod_name, caplog,-):- """Generic regression for the NameError-at-import pattern that hit- `ecs._attributes` (#492) and `acm._synthetic_pem` (#494).-- The bug shape: `restore_state(data)` references a module-level- symbol declared further down the file. The import-time `try:- load_state(...)` block calls `restore_state()` BEFORE Python- evaluates the later definition, so the lookup NameErrors. The- surrounding try/except logs `Failed to restore persisted state` and- swallows the exception, so the module appears to import cleanly- while ALL its persisted state silently disappears.-- The test:- 1. Captures the module's current `get_state()` snapshot (a- non-empty dict-of-empty-dicts — important so `restore_state`- doesn't early-return on truthy emptiness checks).- 2. Persists that to disk via the production `save_state` path.- 3. **Removes the module from `sys.modules` and re-imports it- fresh** — `importlib.reload()` would NOT catch the bug- because it merges new definitions into the existing- namespace, leaving any late-declared symbol bound from the- previous import.- 4. Asserts no WARNING+ log record mentioning "restore" / "failed"- / "continuing fresh" was emitted during the cold import.-- Catches: unconditional symbol references in restore_state- (ECS-style). Does NOT catch: conditional references inside loops- over restored data when the data is empty (ACM-style needs- populated state — see the per-service tests above).- """- import sys-- # Persistence is already enabled and STATE_DIR is already pointed at- # a per-test tmp by the autouse `_enable_persistence` fixture.-- # Step 1+2: produce + persist a snapshot using the already-loaded- # module (so we get a valid get_state() shape).- mod = _module(mod_name)- if hasattr(mod, "reset"):- mod.reset()- persistence.save_state(svc_key, mod.get_state())-- # Step 3: cold-import — wipe sys.modules and re-import.- # importlib.reload() won't work because it merges into the- # existing namespace; the late-declared symbol stays bound from- # the prior import.- full_name = f"ministack.services.{mod_name}"- sys.modules.pop(full_name, None)-- caplog.clear()- with caplog.at_level("WARNING"):- mod = importlib.import_module(full_name)-- bad = [- r for r in caplog.records- if r.levelno >= 30 # WARNING+- and any(needle in r.getMessage().lower()- for needle in ("failed to restore", "restore failed",- "continuing fresh", "continuing with fresh"))- ]- if hasattr(mod, "reset"):- mod.reset()-- assert not bad, (- f"Cold import of `{mod_name}` (state-key `{svc_key}`) emitted "- f"a restore-failure log:\n "- + "\n ".join(r.getMessage() for r in bad)- + "\n\nThis usually means `restore_state` references a "- "module-level symbol that's declared further down the file. "- "The import-time `try: load_state()` block runs before the "- "later definition, so the symbol lookup NameErrors and the "- "surrounding try/except swallows it. Hoist the symbol above "- "the import-time `load_state` block (see ECS `_attributes` "- "or ACM `_synthetic_pem` for the canonical fix)."- )diff --git a/tests/test_sfn.py b/tests/test_stepfunctions.pysimilarity index 100%rename from tests/test_sfn.pyrename to tests/test_stepfunctions.pydiff --git a/tests/test_transfer.py b/tests/test_transfer.pyindex b821c71a..dfb2a27a 100644--- a/tests/test_transfer.py+++ b/tests/test_transfer.py@@ -315,3 +315,424 @@ def test_transfer_workos_sftp_workflow(transfer):with pytest.raises(ClientError) as exc:transfer.describe_user(ServerId=sid, UserName="sftp-org123")assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ========== from test_transfer_sftp.py ==========+# Transfer Family — real asyncssh SFTP server (separate test surface from REST control plane).++import asyncio+import os+import socket+import time+import urllib.request+import uuid++import pytest++asyncssh = pytest.importorskip("asyncssh")+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ed25519++ENDPOINT_HOST = os.environ.get("MINISTACK_HOST", "127.0.0.1")+SFTP_PORT = int(os.environ.get("SFTP_PORT", "2222"))++# Honour MINISTACK_ENDPOINT (e.g. http://localhost:14566) so the same test+# file works against a locally-built MiniStack on port 4566 *and* against a+# preview Docker image bound to a different host port.+_endpoint = os.environ.get("MINISTACK_ENDPOINT", f"http://{ENDPOINT_HOST}:4566")+ADMIN_BASE = _endpoint.rstrip("/")+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _gen_keypair():+ """Return ``(private_pem_text, public_openssh_text)`` for an ed25519 key.++ asyncssh's ``connect(client_keys=...)`` accepts in-memory PEM, so we+ avoid touching the filesystem.+ """+ priv = ed25519.Ed25519PrivateKey.generate()+ priv_pem = priv.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.OpenSSH,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode("utf-8")+ pub = priv.public_key().public_bytes(+ encoding=serialization.Encoding.OpenSSH,+ format=serialization.PublicFormat.OpenSSH,+ ).decode("utf-8")+ return priv_pem, pub+++def _sftp_listening() -> bool:+ """Best-effort probe: return True if something is accepting TCP on+ SFTP_PORT. Skips the whole module if the listener isn't up."""+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ s.settimeout(1.0)+ try:+ s.connect((ENDPOINT_HOST, SFTP_PORT))+ except Exception:+ return False+ finally:+ s.close()+ return True+++pytestmark = pytest.mark.skipif(+ not _sftp_listening(),+ reason=f"SFTP listener not reachable at {ENDPOINT_HOST}:{SFTP_PORT} — start MiniStack first",+)+++def _connect(username, priv_pem, port=None):+ """Return an asyncssh connection coroutine for the given creds."""+ return asyncssh.connect(+ host=ENDPOINT_HOST,+ port=port or SFTP_PORT,+ username=username,+ client_keys=[asyncssh.import_private_key(priv_pem)],+ known_hosts=None,+ )+++def _provision(transfer, s3, *, bucket=None, home_prefix="", logical_mappings=None):+ """CreateServer + CreateBucket + CreateUser. Returns the dict the+ individual tests need: server_id, user_name, priv_pem, bucket name.+ """+ suffix = uuid.uuid4().hex[:8]+ server_id = transfer.create_server()["ServerId"]+ user_name = f"u-{suffix}"+ bucket = bucket or f"sftp-bucket-{suffix}"+ s3.create_bucket(Bucket=bucket)+ priv_pem, pub_ssh = _gen_keypair()++ user_kwargs = {+ "ServerId": server_id,+ "UserName": user_name,+ "Role": f"arn:aws:iam::000000000000:role/sftp-{suffix}",+ "SshPublicKeyBody": pub_ssh,+ }+ if logical_mappings is not None:+ user_kwargs["HomeDirectoryType"] = "LOGICAL"+ user_kwargs["HomeDirectoryMappings"] = logical_mappings+ else:+ user_kwargs["HomeDirectoryType"] = "PATH"+ user_kwargs["HomeDirectory"] = f"/{bucket}/{home_prefix}".rstrip("/")++ transfer.create_user(**user_kwargs)+ return {+ "server_id": server_id,+ "user_name": user_name,+ "priv_pem": priv_pem,+ "bucket": bucket,+ "describe": transfer.describe_server(ServerId=server_id)["Server"],+ }+++# ---------------------------------------------------------------------------+# Happy path+# ---------------------------------------------------------------------------+++def test_sftp_basic_upload_download(transfer, s3):+ """Connect, upload a file via SFTP, verify it landed in S3, download+ it back. End-to-end smoke test."""+ ctx = _provision(transfer, s3)++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/hello.txt", "wb") as f:+ await f.write(b"hello sftp\n")+ # Re-list to confirm the file appears.+ names = await sftp.listdir("/")+ assert "hello.txt" in [n for n in names]+ # Download and verify.+ async with sftp.open("/hello.txt", "rb") as f:+ body = await f.read()+ assert body == b"hello sftp\n"++ asyncio.run(_run())++ # Verify it actually landed in S3 via the standard API.+ obj = s3.get_object(Bucket=ctx["bucket"], Key="hello.txt")+ assert obj["Body"].read() == b"hello sftp\n"+ transfer.delete_server(ServerId=ctx["server_id"])+++# ---------------------------------------------------------------------------+# Auth-failure cases+# ---------------------------------------------------------------------------+++def test_sftp_wrong_key_rejected(transfer, s3):+ """A connecting client with a public key that wasn't ImportSshPublicKey'd+ for the user must be rejected — not silently allowed in."""+ ctx = _provision(transfer, s3)+ _other_priv, _ = _gen_keypair()+ other_priv_pem, _ = _gen_keypair()++ async def _run():+ with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):+ await _connect(ctx["user_name"], other_priv_pem)++ asyncio.run(_run())+ transfer.delete_server(ServerId=ctx["server_id"])+++def test_sftp_unknown_user_rejected(transfer, s3):+ """A username with no matching Transfer user must be rejected."""+ ctx = _provision(transfer, s3)++ async def _run():+ with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):+ await _connect("nobody-" + uuid.uuid4().hex[:8], ctx["priv_pem"])++ asyncio.run(_run())+ transfer.delete_server(ServerId=ctx["server_id"])+++def test_sftp_offline_server_rejects_auth(transfer, s3):+ """StopServer flips State=OFFLINE; the SFTP listener must refuse+ auth for that server's users (matches AWS — a stopped server doesn't+ serve traffic). Bringing it back ONLINE re-allows auth."""+ ctx = _provision(transfer, s3)+ transfer.stop_server(ServerId=ctx["server_id"])++ async def _denied():+ with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):+ await _connect(ctx["user_name"], ctx["priv_pem"])++ asyncio.run(_denied())++ transfer.start_server(ServerId=ctx["server_id"])++ async def _allowed():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/probe", "wb") as f:+ await f.write(b"x")++ asyncio.run(_allowed())+ transfer.delete_server(ServerId=ctx["server_id"])+++# ---------------------------------------------------------------------------+# VFS / S3 semantics+# ---------------------------------------------------------------------------+++def test_sftp_rename_across_prefixes(transfer, s3):+ """Rename should work across nested prefixes — implemented as S3+ copy + delete since S3 has no atomic rename."""+ ctx = _provision(transfer, s3)++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/a.txt", "wb") as f:+ await f.write(b"alpha")+ await sftp.rename("/a.txt", "/sub/b.txt")+ async with sftp.open("/sub/b.txt", "rb") as f:+ assert await f.read() == b"alpha"+ # Source must be gone.+ with pytest.raises(asyncssh.SFTPError):+ await sftp.stat("/a.txt")++ asyncio.run(_run())+ transfer.delete_server(ServerId=ctx["server_id"])+++def test_sftp_large_file_roundtrip(transfer, s3):+ """1 MiB file uploaded and read back — exercises the buffer-then-PUT+ write path under non-trivial load."""+ ctx = _provision(transfer, s3)+ payload = (b"abcdef0123" * 1024) * 100 # ~1 MiB++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/big.bin", "wb") as f:+ await f.write(payload)+ async with sftp.open("/big.bin", "rb") as f:+ got = await f.read()+ assert got == payload++ asyncio.run(_run())+ transfer.delete_server(ServerId=ctx["server_id"])+++def test_sftp_mkdir_listdir_rmdir(transfer, s3):+ """mkdir creates a zero-byte placeholder under the prefix; listdir+ sees it as a directory; rmdir removes it (only when empty)."""+ ctx = _provision(transfer, s3)++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ await sftp.mkdir("/inbox")+ names = await sftp.listdir("/")+ assert "inbox" in names++ # rmdir on non-empty must fail; create a file then try.+ async with sftp.open("/inbox/x", "wb") as f:+ await f.write(b"x")+ with pytest.raises(asyncssh.SFTPError):+ await sftp.rmdir("/inbox")++ # Remove the file, then rmdir succeeds.+ await sftp.remove("/inbox/x")+ await sftp.rmdir("/inbox")++ asyncio.run(_run())+ transfer.delete_server(ServerId=ctx["server_id"])+++def test_sftp_logical_home_directory_mappings(transfer, s3):+ """LOGICAL home dir maps virtual `/inbox` → bucket prefix; an upload+ to /inbox/foo lands at the mapped S3 key."""+ suffix = uuid.uuid4().hex[:8]+ bucket = f"sftp-logical-{suffix}"+ s3.create_bucket(Bucket=bucket)+ ctx = _provision(+ transfer,+ s3,+ bucket=bucket,+ logical_mappings=[+ {"Entry": "/inbox", "Target": f"/{bucket}/incoming"},+ {"Entry": "/archive", "Target": f"/{bucket}/old"},+ ],+ )++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/inbox/today.txt", "wb") as f:+ await f.write(b"hi")++ asyncio.run(_run())++ obj = s3.get_object(Bucket=bucket, Key="incoming/today.txt")+ assert obj["Body"].read() == b"hi"+ transfer.delete_server(ServerId=ctx["server_id"])+++# ---------------------------------------------------------------------------+# Multi-user / multi-server+# ---------------------------------------------------------------------------+++def test_sftp_concurrent_uploads_two_users(transfer, s3):+ """Two distinct users on two distinct servers each upload concurrently+ — exercises the SSH key disambiguation path (single-port mode)."""+ a = _provision(transfer, s3)+ b = _provision(transfer, s3)++ async def _upload(ctx, body):+ async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/concurrent.bin", "wb") as f:+ await f.write(body)++ async def _run():+ await asyncio.gather(+ _upload(a, b"AAAA"),+ _upload(b, b"BBBB"),+ )++ asyncio.run(_run())++ assert s3.get_object(Bucket=a["bucket"], Key="concurrent.bin")["Body"].read() == b"AAAA"+ assert s3.get_object(Bucket=b["bucket"], Key="concurrent.bin")["Body"].read() == b"BBBB"+ transfer.delete_server(ServerId=a["server_id"])+ transfer.delete_server(ServerId=b["server_id"])+++def test_sftp_key_disambiguates_overlapping_usernames(transfer, s3):+ """Two servers, same UserName, different keys: each user's key routes+ to the correct server's bucket. This is the AWS-faithful single-port+ behavior — username alone isn't enough, the SSH key is the+ disambiguator."""+ suffix = uuid.uuid4().hex[:8]+ user_name = f"shared-{suffix}"+ bucket_a = f"sftp-share-a-{suffix}"+ bucket_b = f"sftp-share-b-{suffix}"+ s3.create_bucket(Bucket=bucket_a)+ s3.create_bucket(Bucket=bucket_b)++ sid_a = transfer.create_server()["ServerId"]+ sid_b = transfer.create_server()["ServerId"]+ priv_a, pub_a = _gen_keypair()+ priv_b, pub_b = _gen_keypair()+ transfer.create_user(+ ServerId=sid_a, UserName=user_name,+ Role="arn:aws:iam::000000000000:role/r",+ HomeDirectoryType="PATH", HomeDirectory=f"/{bucket_a}",+ SshPublicKeyBody=pub_a,+ )+ transfer.create_user(+ ServerId=sid_b, UserName=user_name,+ Role="arn:aws:iam::000000000000:role/r",+ HomeDirectoryType="PATH", HomeDirectory=f"/{bucket_b}",+ SshPublicKeyBody=pub_b,+ )++ async def _put(priv, body):+ async with await _connect(user_name, priv) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/marker", "wb") as f:+ await f.write(body)++ asyncio.run(_put(priv_a, b"from-a"))+ asyncio.run(_put(priv_b, b"from-b"))++ assert s3.get_object(Bucket=bucket_a, Key="marker")["Body"].read() == b"from-a"+ assert s3.get_object(Bucket=bucket_b, Key="marker")["Body"].read() == b"from-b"+ transfer.delete_server(ServerId=sid_a)+ transfer.delete_server(ServerId=sid_b)+++# ---------------------------------------------------------------------------+# Per-server-port mode (env-gated)+# ---------------------------------------------------------------------------+++def _sftp_port_state():+ """Hit /_ministack/transfer/sftp-ports — returns the JSON dict, or None+ on any failure (used to skip per-server-mode tests cleanly)."""+ import json as _json+ try:+ with urllib.request.urlopen(+ f"{ADMIN_BASE}/_ministack/transfer/sftp-ports", timeout=2+ ) as resp:+ return _json.loads(resp.read())+ except Exception:+ return None+++ not (_sftp_port_state() or {}).get("port_per_server"),+ reason="MiniStack server not started with SFTP_PORT_PER_SERVER=1",+)+def test_sftp_port_per_server_mode(transfer, s3):+ """In per-server mode, the admin endpoint surfaces a unique port for+ each Transfer server and connecting on that port reaches only that+ server's users. Mirrors AWS Transfer's per-server endpoint model."""+ ctx = _provision(transfer, s3)+ state = _sftp_port_state()+ port = state["per_server"].get(ctx["server_id"])+ assert port and port != SFTP_PORT, "expected a unique per-server SFTP port"++ async def _run():+ async with await _connect(ctx["user_name"], ctx["priv_pem"], port=port) as conn:+ async with conn.start_sftp_client() as sftp:+ async with sftp.open("/per-server-marker", "wb") as f:+ await f.write(b"ok")++ asyncio.run(_run())+ obj = s3.get_object(Bucket=ctx["bucket"], Key="per-server-marker")+ assert obj["Body"].read() == b"ok"+ transfer.delete_server(ServerId=ctx["server_id"])diff --git a/tests/test_transfer_sftp.py b/tests/test_transfer_sftp.pydeleted file mode 100644index afb9b049..00000000--- a/tests/test_transfer_sftp.py+++ /dev/null@@ -1,436 +0,0 @@-"""-Integration tests for the Transfer Family SFTP layer.--These tests require the MiniStack server to be running (the standard-``MINISTACK_ENDPOINT`` env var picks up the address). They also require-``asyncssh`` to be importable — if the host's MiniStack process started-without asyncssh installed, the SFTP listener won't be up and every test-in this file is skipped.--Coverage beyond the happy path:-- Wrong key rejected, unknown user rejected, OFFLINE server rejected.-- Rename across prefixes (S3 copy + delete).-- Large file (> 1 MiB) round-trip.-- Concurrent uploads from two distinct users.-- LOGICAL HomeDirectoryMappings: virtual `/inbox` → bucket prefix.-- mkdir + listing + rmdir against the S3-prefix VFS.-- Per-server-port mode (skipped unless ``SFTP_PORT_PER_SERVER=1`` is set- on the running server).-"""--import asyncio-import os-import socket-import time-import urllib.request-import uuid--import pytest--asyncssh = pytest.importorskip("asyncssh")-from cryptography.hazmat.primitives import serialization-from cryptography.hazmat.primitives.asymmetric import ed25519--ENDPOINT_HOST = os.environ.get("MINISTACK_HOST", "127.0.0.1")-SFTP_PORT = int(os.environ.get("SFTP_PORT", "2222"))--# Honour MINISTACK_ENDPOINT (e.g. http://localhost:14566) so the same test-# file works against a locally-built MiniStack on port 4566 *and* against a-# preview Docker image bound to a different host port.-_endpoint = os.environ.get("MINISTACK_ENDPOINT", f"http://{ENDPOINT_HOST}:4566")-ADMIN_BASE = _endpoint.rstrip("/")---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _gen_keypair():- """Return ``(private_pem_text, public_openssh_text)`` for an ed25519 key.-- asyncssh's ``connect(client_keys=...)`` accepts in-memory PEM, so we- avoid touching the filesystem.- """- priv = ed25519.Ed25519PrivateKey.generate()- priv_pem = priv.private_bytes(- encoding=serialization.Encoding.PEM,- format=serialization.PrivateFormat.OpenSSH,- encryption_algorithm=serialization.NoEncryption(),- ).decode("utf-8")- pub = priv.public_key().public_bytes(- encoding=serialization.Encoding.OpenSSH,- format=serialization.PublicFormat.OpenSSH,- ).decode("utf-8")- return priv_pem, pub---def _sftp_listening() -> bool:- """Best-effort probe: return True if something is accepting TCP on- SFTP_PORT. Skips the whole module if the listener isn't up."""- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- s.settimeout(1.0)- try:- s.connect((ENDPOINT_HOST, SFTP_PORT))- except Exception:- return False- finally:- s.close()- return True---pytestmark = pytest.mark.skipif(- not _sftp_listening(),- reason=f"SFTP listener not reachable at {ENDPOINT_HOST}:{SFTP_PORT} — start MiniStack first",-)---def _connect(username, priv_pem, port=None):- """Return an asyncssh connection coroutine for the given creds."""- return asyncssh.connect(- host=ENDPOINT_HOST,- port=port or SFTP_PORT,- username=username,- client_keys=[asyncssh.import_private_key(priv_pem)],- known_hosts=None,- )---def _provision(transfer, s3, *, bucket=None, home_prefix="", logical_mappings=None):- """CreateServer + CreateBucket + CreateUser. Returns the dict the- individual tests need: server_id, user_name, priv_pem, bucket name.- """- suffix = uuid.uuid4().hex[:8]- server_id = transfer.create_server()["ServerId"]- user_name = f"u-{suffix}"- bucket = bucket or f"sftp-bucket-{suffix}"- s3.create_bucket(Bucket=bucket)- priv_pem, pub_ssh = _gen_keypair()-- user_kwargs = {- "ServerId": server_id,- "UserName": user_name,- "Role": f"arn:aws:iam::000000000000:role/sftp-{suffix}",- "SshPublicKeyBody": pub_ssh,- }- if logical_mappings is not None:- user_kwargs["HomeDirectoryType"] = "LOGICAL"- user_kwargs["HomeDirectoryMappings"] = logical_mappings- else:- user_kwargs["HomeDirectoryType"] = "PATH"- user_kwargs["HomeDirectory"] = f"/{bucket}/{home_prefix}".rstrip("/")-- transfer.create_user(**user_kwargs)- return {- "server_id": server_id,- "user_name": user_name,- "priv_pem": priv_pem,- "bucket": bucket,- "describe": transfer.describe_server(ServerId=server_id)["Server"],- }---# ----------------------------------------------------------------------------# Happy path-# ------------------------------------------------------------------------------def test_sftp_basic_upload_download(transfer, s3):- """Connect, upload a file via SFTP, verify it landed in S3, download- it back. End-to-end smoke test."""- ctx = _provision(transfer, s3)-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/hello.txt", "wb") as f:- await f.write(b"hello sftp\n")- # Re-list to confirm the file appears.- names = await sftp.listdir("/")- assert "hello.txt" in [n for n in names]- # Download and verify.- async with sftp.open("/hello.txt", "rb") as f:- body = await f.read()- assert body == b"hello sftp\n"-- asyncio.run(_run())-- # Verify it actually landed in S3 via the standard API.- obj = s3.get_object(Bucket=ctx["bucket"], Key="hello.txt")- assert obj["Body"].read() == b"hello sftp\n"- transfer.delete_server(ServerId=ctx["server_id"])---# ----------------------------------------------------------------------------# Auth-failure cases-# ------------------------------------------------------------------------------def test_sftp_wrong_key_rejected(transfer, s3):- """A connecting client with a public key that wasn't ImportSshPublicKey'd- for the user must be rejected — not silently allowed in."""- ctx = _provision(transfer, s3)- _other_priv, _ = _gen_keypair()- other_priv_pem, _ = _gen_keypair()-- async def _run():- with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):- await _connect(ctx["user_name"], other_priv_pem)-- asyncio.run(_run())- transfer.delete_server(ServerId=ctx["server_id"])---def test_sftp_unknown_user_rejected(transfer, s3):- """A username with no matching Transfer user must be rejected."""- ctx = _provision(transfer, s3)-- async def _run():- with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):- await _connect("nobody-" + uuid.uuid4().hex[:8], ctx["priv_pem"])-- asyncio.run(_run())- transfer.delete_server(ServerId=ctx["server_id"])---def test_sftp_offline_server_rejects_auth(transfer, s3):- """StopServer flips State=OFFLINE; the SFTP listener must refuse- auth for that server's users (matches AWS — a stopped server doesn't- serve traffic). Bringing it back ONLINE re-allows auth."""- ctx = _provision(transfer, s3)- transfer.stop_server(ServerId=ctx["server_id"])-- async def _denied():- with pytest.raises((asyncssh.PermissionDenied, asyncssh.misc.PermissionDenied)):- await _connect(ctx["user_name"], ctx["priv_pem"])-- asyncio.run(_denied())-- transfer.start_server(ServerId=ctx["server_id"])-- async def _allowed():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/probe", "wb") as f:- await f.write(b"x")-- asyncio.run(_allowed())- transfer.delete_server(ServerId=ctx["server_id"])---# ----------------------------------------------------------------------------# VFS / S3 semantics-# ------------------------------------------------------------------------------def test_sftp_rename_across_prefixes(transfer, s3):- """Rename should work across nested prefixes — implemented as S3- copy + delete since S3 has no atomic rename."""- ctx = _provision(transfer, s3)-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/a.txt", "wb") as f:- await f.write(b"alpha")- await sftp.rename("/a.txt", "/sub/b.txt")- async with sftp.open("/sub/b.txt", "rb") as f:- assert await f.read() == b"alpha"- # Source must be gone.- with pytest.raises(asyncssh.SFTPError):- await sftp.stat("/a.txt")-- asyncio.run(_run())- transfer.delete_server(ServerId=ctx["server_id"])---def test_sftp_large_file_roundtrip(transfer, s3):- """1 MiB file uploaded and read back — exercises the buffer-then-PUT- write path under non-trivial load."""- ctx = _provision(transfer, s3)- payload = (b"abcdef0123" * 1024) * 100 # ~1 MiB-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/big.bin", "wb") as f:- await f.write(payload)- async with sftp.open("/big.bin", "rb") as f:- got = await f.read()- assert got == payload-- asyncio.run(_run())- transfer.delete_server(ServerId=ctx["server_id"])---def test_sftp_mkdir_listdir_rmdir(transfer, s3):- """mkdir creates a zero-byte placeholder under the prefix; listdir- sees it as a directory; rmdir removes it (only when empty)."""- ctx = _provision(transfer, s3)-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- await sftp.mkdir("/inbox")- names = await sftp.listdir("/")- assert "inbox" in names-- # rmdir on non-empty must fail; create a file then try.- async with sftp.open("/inbox/x", "wb") as f:- await f.write(b"x")- with pytest.raises(asyncssh.SFTPError):- await sftp.rmdir("/inbox")-- # Remove the file, then rmdir succeeds.- await sftp.remove("/inbox/x")- await sftp.rmdir("/inbox")-- asyncio.run(_run())- transfer.delete_server(ServerId=ctx["server_id"])---def test_sftp_logical_home_directory_mappings(transfer, s3):- """LOGICAL home dir maps virtual `/inbox` → bucket prefix; an upload- to /inbox/foo lands at the mapped S3 key."""- suffix = uuid.uuid4().hex[:8]- bucket = f"sftp-logical-{suffix}"- s3.create_bucket(Bucket=bucket)- ctx = _provision(- transfer,- s3,- bucket=bucket,- logical_mappings=[- {"Entry": "/inbox", "Target": f"/{bucket}/incoming"},- {"Entry": "/archive", "Target": f"/{bucket}/old"},- ],- )-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/inbox/today.txt", "wb") as f:- await f.write(b"hi")-- asyncio.run(_run())-- obj = s3.get_object(Bucket=bucket, Key="incoming/today.txt")- assert obj["Body"].read() == b"hi"- transfer.delete_server(ServerId=ctx["server_id"])---# ----------------------------------------------------------------------------# Multi-user / multi-server-# ------------------------------------------------------------------------------def test_sftp_concurrent_uploads_two_users(transfer, s3):- """Two distinct users on two distinct servers each upload concurrently- — exercises the SSH key disambiguation path (single-port mode)."""- a = _provision(transfer, s3)- b = _provision(transfer, s3)-- async def _upload(ctx, body):- async with await _connect(ctx["user_name"], ctx["priv_pem"]) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/concurrent.bin", "wb") as f:- await f.write(body)-- async def _run():- await asyncio.gather(- _upload(a, b"AAAA"),- _upload(b, b"BBBB"),- )-- asyncio.run(_run())-- assert s3.get_object(Bucket=a["bucket"], Key="concurrent.bin")["Body"].read() == b"AAAA"- assert s3.get_object(Bucket=b["bucket"], Key="concurrent.bin")["Body"].read() == b"BBBB"- transfer.delete_server(ServerId=a["server_id"])- transfer.delete_server(ServerId=b["server_id"])---def test_sftp_key_disambiguates_overlapping_usernames(transfer, s3):- """Two servers, same UserName, different keys: each user's key routes- to the correct server's bucket. This is the AWS-faithful single-port- behavior — username alone isn't enough, the SSH key is the- disambiguator."""- suffix = uuid.uuid4().hex[:8]- user_name = f"shared-{suffix}"- bucket_a = f"sftp-share-a-{suffix}"- bucket_b = f"sftp-share-b-{suffix}"- s3.create_bucket(Bucket=bucket_a)- s3.create_bucket(Bucket=bucket_b)-- sid_a = transfer.create_server()["ServerId"]- sid_b = transfer.create_server()["ServerId"]- priv_a, pub_a = _gen_keypair()- priv_b, pub_b = _gen_keypair()- transfer.create_user(- ServerId=sid_a, UserName=user_name,- Role="arn:aws:iam::000000000000:role/r",- HomeDirectoryType="PATH", HomeDirectory=f"/{bucket_a}",- SshPublicKeyBody=pub_a,- )- transfer.create_user(- ServerId=sid_b, UserName=user_name,- Role="arn:aws:iam::000000000000:role/r",- HomeDirectoryType="PATH", HomeDirectory=f"/{bucket_b}",- SshPublicKeyBody=pub_b,- )-- async def _put(priv, body):- async with await _connect(user_name, priv) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/marker", "wb") as f:- await f.write(body)-- asyncio.run(_put(priv_a, b"from-a"))- asyncio.run(_put(priv_b, b"from-b"))-- assert s3.get_object(Bucket=bucket_a, Key="marker")["Body"].read() == b"from-a"- assert s3.get_object(Bucket=bucket_b, Key="marker")["Body"].read() == b"from-b"- transfer.delete_server(ServerId=sid_a)- transfer.delete_server(ServerId=sid_b)---# ----------------------------------------------------------------------------# Per-server-port mode (env-gated)-# ------------------------------------------------------------------------------def _sftp_port_state():- """Hit /_ministack/transfer/sftp-ports — returns the JSON dict, or None- on any failure (used to skip per-server-mode tests cleanly)."""- import json as _json- try:- with urllib.request.urlopen(- f"{ADMIN_BASE}/_ministack/transfer/sftp-ports", timeout=2- ) as resp:- return _json.loads(resp.read())- except Exception:- return None--- not (_sftp_port_state() or {}).get("port_per_server"),- reason="MiniStack server not started with SFTP_PORT_PER_SERVER=1",-)-def test_sftp_port_per_server_mode(transfer, s3):- """In per-server mode, the admin endpoint surfaces a unique port for- each Transfer server and connecting on that port reaches only that- server's users. Mirrors AWS Transfer's per-server endpoint model."""- ctx = _provision(transfer, s3)- state = _sftp_port_state()- port = state["per_server"].get(ctx["server_id"])- assert port and port != SFTP_PORT, "expected a unique per-server SFTP port"-- async def _run():- async with await _connect(ctx["user_name"], ctx["priv_pem"], port=port) as conn:- async with conn.start_sftp_client() as sftp:- async with sftp.open("/per-server-marker", "wb") as f:- await f.write(b"ok")-- asyncio.run(_run())- obj = s3.get_object(Bucket=ctx["bucket"], Key="per-server-marker")- assert obj["Body"].read() == b"ok"- transfer.delete_server(ServerId=ctx["server_id"])