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.5.16 (#1812)
Nahuel Nucera586e286788d8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7f17688..d1487ec8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,11 +5,26 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).-## [Unreleased]+## [1.5.16] — 2026-09-23### Added- **Organizations — member accounts, service control policies and attachments** — `CreateAccount`, `DescribeCreateAccountStatus`, `MoveAccount`, `CloseAccount`, `CreatePolicy`, `DescribePolicy`, `UpdatePolicy`, `DeletePolicy`, `ListPolicies`, `AttachPolicy`, `DetachPolicy`, `ListPoliciesForTarget`, `ListTargetsForPolicy`, `EnablePolicyType` and `DisablePolicyType`, so `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply. `CreateAccount` answers with a `CreateAccountStatus` whose id the provider reads back through `DescribeCreateAccountStatus`, as on AWS. A root carries `SERVICE_CONTROL_POLICY` enabled and the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException`, and deleting an attached policy is `PolicyInUseException`. Requested by @rv0lt.+- **SNS — direct-to-phone publishes can be read back** — a `Publish` with a `PhoneNumber` and no `TopicArn` is recorded and served at `GET /_ministack/sns/sms-messages`, filterable by `account`, `region` and `phoneNumber`. Contributed by @himangshuj.+- **Lambda MicroVMs — image lifecycle** — `ListMicrovmImages`, `GetMicrovmImage`, `GetMicrovmImageVersion` and `UpdateMicrovmImage`. Contributed by @edersonbrilhante.++### Fixed++- **S3 — a versioned object keeps its history across a restart** — with `S3_PERSIST=1` a delete marker was lost on restart, so a deleted object came back. Every version and delete marker now persists with the object on disk, each version keeps its own bytes, tags and ACL, and object tags and ACLs survive a restart for unversioned objects too. Contributed by @pauloRohling.+- **ECS — service deployments track task health and roll back** — a completed deployment drains the previous task definition's tasks, `deploymentCircuitBreaker` fails a deployment whose tasks keep stopping and, with `rollback`, restores the previous one, and replacement stays within `maximumPercent` while keeping `minimumHealthyPercent` of `desiredCount` running. Contributed by @jgrumboe.+- **CloudFormation — change sets report which property edits replace a resource** — every property edit answered `Replacement: Conditional` and `RequiresRecreation: Conditionally`. For 21 resource types a create-only property is now `Always` with `Replacement: True`, a conditionally create-only one stays `Conditionally`, and every other property is `Never`. Contributed by @iot-rocket.+- **EC2 — Elastic IP tags and IPv6 network ACL entries survive a read** — `DescribeAddresses` omitted EIP tags, so Terraform repeatedly planned `tags` and `tags_all`; network ACL entries always stored and returned an IPv4 CIDR, so an IPv6 rule was read back as a changed IPv4 rule on every plan. Tags and `Ipv6CidrBlock` now round-trip through the EC2 API, and `ReleaseAddress` drops the address's tags. Contributed by @edersonbrilhante.+- **Bedrock — a proxied tool-call turn reports its real token usage** — with `MINISTACK_BEDROCK_PROXY_URL` set, `Converse` and `ConverseStream` estimated usage from the reply text, so a turn that returned only a `toolUse` block reported `outputTokens: 0`, and `inputTokens` ignored the `toolConfig`. Usage now comes from the proxy's own `prompt_tokens` and `completion_tokens`, with the estimate kept for a proxy that sends none. Reported by @Vidminas.++### Internal++- **CI — one Docker preview comment per PR** — the preview-image workflow updates a single comment instead of posting one per push. Contributed by @jgrumboe.+- **Tests** — split test files folded into their service's file.## [1.5.15] — 2026-09-22@@ -20,7 +35,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed-- **EC2 — Elastic IP tags and IPv6 network ACL entries survive a read** — `DescribeAddresses` omitted EIP tags, so Terraform repeatedly planned `tags` and `tags_all`; network ACL entries always stored and returned an IPv4 CIDR, so an IPv6 rule was read back as a changed IPv4 rule on every plan. Tags and `Ipv6CidrBlock` now round-trip through the EC2 API. Reported by @edersonbrilhante.- **KMS — imported key material for HMAC and asymmetric keys** — `CreateKey` with `Origin=EXTERNAL` refused every spec but `SYMMETRIC_DEFAULT`, where AWS supports imported material for symmetric encryption, HMAC and asymmetric keys, ML-DSA excepted. HMAC material is the raw bytes of the spec's length and asymmetric material is the private key alone, DER-encoded PKCS#8, from which the public key is derived; material that does not match the key's `KeySpec` answers `IncorrectKeyMaterialException`, and `GetPublicKey` on a key still awaiting material answers `KMSInvalidStateException`. Reported by @guymahieu.- **RDS — the server certificate carries the endpoint AWS puts in it** — certificate generation raised `ValueError` once an endpoint passed the X.509 64-byte common-name bound, so a database with a long identifier could not start. The common name is now the advertised endpoint at its full length, the subject carries `OU=RDS, O=Amazon.com, L=Seattle, ST=Washington, C=US`, and the signing CA is named `Amazon RDS <region> Root CA RSA2048 G1`, matching a certificate captured from a real instance. Contributed by @jayjanssen.- **API Gateway — an OpenAPI body's `securityDefinitions` reach the methods** — the import discarded security outright, so a SAM API declaring a Cognito authorizer created none and every method imported as `authorizationType: NONE`, serving anonymous callers where AWS answers 401. Each scheme carrying `x-amazon-apigateway-authorizer` now becomes an authorizer, and an operation's `security` — or the document's — sets the method's `authorizationType`, `authorizerId` and `authorizationScopes`, so the enforcement added in 1.5.10 engages for body-defined APIs. Contributed by @maximoosemine.diff --git a/README.md b/README.mdindex adf05a64..fe813665 100644--- a/README.md+++ b/README.md@@ -130,15 +130,11 @@ docker run -p 4566:4566 \Or use the multi-tenancy feature — a 12-digit access key automatically becomes the account ID (see [Multi-Tenancy](#multi-tenancy) below).-Also compatible with LocalStack's health and SMS-log endpoints:+Also compatible with LocalStack's health endpoint:```bashcurl http://localhost:4566/_localstack/healthcurl http://localhost:4566/health--# Direct-to-phone SNS publishes, in LocalStack's-# {"sms_messages": {"<phone>": [...]}, "region": "<region>"} shape-curl http://localhost:4566/_ministack/sns/sms-messages```---diff --git a/ministack/app.py b/ministack/app.pyindex 97ca00a8..af913b7d 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1086,26 +1086,7 @@ _SNS_SMS_PATH = "/_ministack/sns/sms-messages"async def _handle_sns_sms_messages_request(method: str, path: str, headers: dict, query_params: dict):- """Handle the SNS SMS log endpoint.-- A `Publish` that carries a `PhoneNumber` and no `TopicArn` has nowhere to- deliver to, so sns.py records it and this serves the recording back. Same- read-only introspection as `/_ministack/ses/messages` and- `/_ministack/sqs/messages`.-- The body keeps LocalStack's shape —- `{"sms_messages": {"<phone>": [...]}, "region": "<region>"}` — so a suite- moving here changes the URL and nothing else. Only the native- `/_ministack/` path serves it: the compatibility surface stays narrow, and- a `/_aws/` alias earns its place only against a concrete migration that- would otherwise be painful.-- Filters:- ?account=<12-digit-id> restrict to one account- ?region=<aws-region> restrict to one region- ?phoneNumber=<e164> restrict to one recipient; the key is present- with an empty list when nothing was sent to it- """+ """Serve direct-to-phone SNS publishes, filtered by ?account, ?region and ?phoneNumber."""if path != _SNS_SMS_PATH or method != "GET":return None@@ -1160,9 +1141,7 @@ async def _handle_sns_sms_messages_request(method: str, path: str, headers: dictif isinstance(records, list):sms_messages.setdefault(phone, []).extend(records)- # LocalStack answers a filtered request with the key present and empty- # rather than with an absent key, and a poller that reads- # `body.sms_messages[phone]` depends on that.+ # A filtered recipient is present even with nothing sent to it.if phone_filter is not None:sms_messages.setdefault(phone_filter, [])diff --git a/ministack/services/bedrock_runtime.py b/ministack/services/bedrock_runtime.pyindex dd7086dc..d1041efc 100644--- a/ministack/services/bedrock_runtime.py+++ b/ministack/services/bedrock_runtime.py@@ -329,10 +329,10 @@ def _openai_messages(messages, system):def _proxy_openai_chat_message(model_id: str, messages, system, inference_config,tool_config=None):"""Forward to MINISTACK_BEDROCK_PROXY_URL in OpenAI chat-completions shape- and return the assistant message object, or None on any failure (the caller- falls back to the mock)."""+ and return the assistant message object with the proxy's (input, output)+ token counts, or (None, None) on any failure (the caller falls back to the mock)."""if not _PROXY_URL:- return None+ return None, Nonepayload = {"model": model_id,"messages": _openai_messages(messages, system),@@ -363,15 +363,23 @@ def _proxy_openai_chat_message(model_id: str, messages, system, inference_configdata = json.load(resp)except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:logger.debug("bedrock proxy unreachable, falling back to mock: %s", e)- return None+ return None, Noneexcept Exception:logger.exception("bedrock proxy returned malformed response, falling back to mock")- return None+ return None, Nonetry:message = data["choices"][0]["message"]except (KeyError, IndexError, TypeError):- return None- return message if isinstance(message, dict) else None+ return None, None+ if not isinstance(message, dict):+ return None, None+ usage = data.get("usage") if isinstance(data, dict) else None+ counts = None+ if isinstance(usage, dict):+ prompt, completion = usage.get("prompt_tokens"), usage.get("completion_tokens")+ if isinstance(prompt, int) and isinstance(completion, int):+ counts = (prompt, completion)+ return message, countsdef _converse_blocks_from_message(message):@@ -407,7 +415,7 @@ def _converse_blocks_from_message(message):def _proxy_to_openai_chat(model_id: str, messages, system, inference_config) -> str | None:"""The assistant text only, for the callers that do not handle tools."""- message = _proxy_openai_chat_message(model_id, messages, system, inference_config)+ message, _ = _proxy_openai_chat_message(model_id, messages, system, inference_config)if message is None:return Nonecontent = message.get("content")@@ -481,7 +489,7 @@ def _converse(model_id: str, headers, body) -> tuple:}, json.dumps(response).encode()tool_config = body_obj.get("toolConfig")- message = _proxy_openai_chat_message(+ message, counts = _proxy_openai_chat_message(model_id, messages, system, inference_config, tool_config)blocks, stop_reason = ([], "end_turn")if message is None:@@ -506,6 +514,8 @@ def _converse(model_id: str, headers, body) -> tuple:response = _build_converse_response(model_id, messages, system, started, text,+ input_tokens=counts[0] if counts else None,+ output_tokens=counts[1] if counts else None,content_blocks=blocks or None, stop_reason=stop_reason)if guardrail is not None:if output_assessment and any(@@ -563,7 +573,9 @@ def _es_event(event_type: str, payload: dict) -> bytes:def _build_converse_stream(model_id: str, messages, system, started_at_ms: int, text: str,- stop_reason: str = "end_turn", tool_uses=()) -> bytes:+ stop_reason: str = "end_turn", tool_uses=(),+ input_tokens: int | None = None,+ output_tokens: int | None = None) -> bytes:"""Emit the AWS ConverseStream event sequence:messageStart -> contentBlockDelta* -> contentBlockStop -> messageStop -> metadataAll events under :event-type, payload is application/json per AWS wire trace.@@ -602,8 +614,10 @@ def _build_converse_stream(model_id: str, messages, system, started_at_ms: int,})stream += _es_event("contentBlockStop", {"contentBlockIndex": index})stream += _es_event("messageStop", {"stopReason": stop_reason})- input_tokens = _estimate_tokens(_system_text(system) + _messages_text(messages))- output_tokens = _estimate_tokens(text)+ if input_tokens is None:+ input_tokens = _estimate_tokens(_system_text(system) + _messages_text(messages))+ if output_tokens is None:+ output_tokens = _estimate_tokens(text)latency_ms = max(1, int(time.time() * 1000) - started_at_ms)stream += _es_event("metadata", {"usage": {@@ -649,8 +663,9 @@ def _converse_stream(model_id: str, headers, body) -> tuple:guardrail = None # no output pass on a blocked inputtool_uses = []+ counts = Noneif stop_reason is None:- message = _proxy_openai_chat_message(+ message, counts = _proxy_openai_chat_message(model_id, messages, system, inference_config, body_obj.get("toolConfig"))if message is None:text = _mock_reply(model_id, messages, system)@@ -672,7 +687,9 @@ def _converse_stream(model_id: str, headers, body) -> tuple:stream_bytes = _build_converse_stream(model_id, messages, system, started, text,stop_reason=stop_reason or "end_turn",- tool_uses=tool_uses)+ tool_uses=tool_uses,+ input_tokens=counts[0] if counts else None,+ output_tokens=counts[1] if counts else None)resp_headers = {"Content-Type": "application/vnd.amazon.eventstream","x-amzn-bedrock-content-type": "application/json",diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 47b615ea..603d2067 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -3605,6 +3605,7 @@ def _release_address(p):allocation_id = _p(p, "AllocationId")if allocation_id and allocation_id in _addresses:del _addresses[allocation_id]+ _tags.pop(allocation_id, None)elif allocation_id:return _error("InvalidAllocationID.NotFound",f"The allocation ID '{allocation_id}' does not exist", 400)diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 414e989e..8cdcfad0 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -101,8 +101,7 @@ _ECS_RESTORE_RECONCILE_DELAY = float(# A container that merely reaches RUNNING is not immediately a steady service# deployment: it can exit during its process startup. Keep a short window# before completing a rollout so the lifecycle watcher can report that exit.-_ECS_DEPLOYMENT_STEADY_DELAY = float(- os.environ.get("ECS_DEPLOYMENT_STEADY_DELAY_SECONDS", "1"))+_ECS_DEPLOYMENT_STEADY_DELAY = 1.0_ecs_reaper_started = False_ecs_reaper_lock = threading.Lock()@@ -1202,31 +1201,36 @@ def _reconcile_service_tasks(cluster_name, svc_key):if svc["deployments"]:svc["deployments"][0]["runningCount"] = desiredreturn- # Preserve #1779's rolling-deployment capacity guard. New tasks may- # overlap old ones up to maximumPercent; at 100%, drain enough stale- # capacity before starting the replacement.+ # Replacements fit under maximumPercent; stale tasks are stopped for+ # room only while minimumHealthyPercent stays RUNNING.deployment_config = svc.get("deploymentConfiguration") or {}maximum_percent = int(deployment_config.get("maximumPercent", 200))+ minimum_percent = int(deployment_config.get("minimumHealthyPercent", 100))max_running = max(1, desired * maximum_percent // 100)+ min_running = -(-desired * minimum_percent // 100)+ running = sum(1 for _, t in current_tasks + stale_tasks if t.get("lastStatus") == "RUNNING")capacity = max_running - len(current_tasks) - len(stale_tasks)if capacity < to_spawn:- for task_arn, _ in stale_tasks[:to_spawn - max(0, capacity)]:+ to_stop = min(to_spawn - max(0, capacity), max(0, running - min_running), len(stale_tasks))+ for task_arn, _ in stale_tasks[:to_stop]:_stop_task({"task": task_arn,"cluster": cluster_name,"reason": "Deployment capacity limit",})- _run_task({- "cluster": cluster_name,- "taskDefinition": td_arn,- "count": to_spawn,- "group": f"service:{svc_name}",- "startedBy": svc_name,- "launchType": launch_type,- "networkConfiguration": network_cfg,- "enableExecuteCommand": svc.get("enableExecuteCommand", False),- "_deploymentId": primary.get("id") if primary else None,- })+ to_spawn = max(0, capacity) + to_stop+ if to_spawn > 0:+ _run_task({+ "cluster": cluster_name,+ "taskDefinition": td_arn,+ "count": to_spawn,+ "group": f"service:{svc_name}",+ "startedBy": svc_name,+ "launchType": launch_type,+ "networkConfiguration": network_cfg,+ "enableExecuteCommand": svc.get("enableExecuteCommand", False),+ "_deploymentId": primary.get("id") if primary else None,+ })elif to_spawn < 0:# Scale down: stop newest tasks firstexcess = -to_spawndiff --git a/ministack/services/lambda_microvms.py b/ministack/services/lambda_microvms.pyindex fd0251e6..ce4ca915 100644--- a/ministack/services/lambda_microvms.py+++ b/ministack/services/lambda_microvms.py@@ -324,8 +324,8 @@ def _list_microvm_images(query_params):max_results = int(raw_max_results)except (TypeError, ValueError):return _validation("maxResults must be an integer")- if max_results < 1:- return _validation("maxResults must be greater than zero")+ if max_results < 1 or max_results > 50:+ return _validation("maxResults must be between 1 and 50")raw_next_token = _qp("nextToken")try:@@ -404,7 +404,7 @@ def _update_microvm_image(image_identifier, body):for field in ("baseImageArn", "baseImageVersion", "buildRoleArn", "codeArtifact","cpuConfigurations", "description", "egressNetworkConnectors",- "environmentVariables", "hooks", "logging", "resources", "tags",+ "environmentVariables", "hooks", "logging", "resources", "additionalOsCapabilities",):if field in data:record[field] = data[field]@@ -414,10 +414,7 @@ def _update_microvm_image(image_identifier, body):"state": "UPDATED","updatedAt": _now(),})- return json_response({- **{k: v for k, v in record.items() if v is not None},- "imageVersion": version,- })+ return json_response({k: v for k, v in record.items() if v is not None and k != "tags"})# ---------------------------------------------------------------------------diff --git a/ministack/services/organizations.py b/ministack/services/organizations.pyindex 607e6cc9..d3a01976 100644--- a/ministack/services/organizations.py+++ b/ministack/services/organizations.py@@ -122,8 +122,7 @@ def _ensure_org():}_policies[FULL_ACCESS_POLICY_ID] = {"Id": FULL_ACCESS_POLICY_ID,- "Arn": f"arn:aws:organizations::aws:policy/{org_id}/service_control_policy/"- f"{FULL_ACCESS_POLICY_ID}",+ "Arn": f"arn:aws:organizations::aws:policy/service_control_policy/{FULL_ACCESS_POLICY_ID}","Name": "FullAWSAccess","Description": "Allows access to every operation","Type": "SERVICE_CONTROL_POLICY",@@ -446,12 +445,15 @@ def _move_account(payload):if account is None:return error_response_json("AccountNotFoundException",f"We can't find an account with the AccountId {account_id}", 400)- if _target(source)[0] is None:+ if _target(source)[1] not in ("ROOT", "ORGANIZATIONAL_UNIT"):return error_response_json("SourceParentNotFoundException",f"We can't find a parent with the ParentId {source}", 400)- if _target(destination)[0] is None:+ if _target(destination)[1] not in ("ROOT", "ORGANIZATIONAL_UNIT"):return error_response_json("DestinationParentNotFoundException",f"We can't find a parent with the ParentId {destination}", 400)+ if account.get("_ParentId") == destination:+ return error_response_json("DuplicateAccountException",+ "That account is already present in the specified destination.", 400)updated = dict(account)updated["_ParentId"] = destination_accounts[account_id] = updateddiff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 7fb283a1..d78002b1 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -750,11 +750,7 @@ def _get_object_data(bucket_name: str, key: str, version_id: str | None = None)if version_id:for v in _object_versions.get((bucket_name, key), []):if v["version_id"] == version_id:- data = v.get("data")- if data is not None:- return data- obj = bucket["objects"].get(key)- return _read_body(bucket_name, key, obj) if obj else None+ return _version_body(bucket, bucket_name, key, v)return Noneobj = bucket["objects"].get(key)if obj is None:@@ -3709,20 +3705,21 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):if version_id:resp_headers["x-amz-version-id"] = version_id- # Persist only after the versioning block: the .meta.json sidecar must- # carry the version_id assigned above (#1058).- if S3_PERSIST:- _persist_object(bucket_name, key, obj)-if pending_tags is not None:_object_tags[(bucket_name, key, obj.get("version_id"))] = pending_tagsif obj.get("_replica"):dest_name, replica_version = obj["_replica"]_object_tags[(dest_name, key, replica_version)] = dict(pending_tags)+ _persist_version_state(dest_name, key, _buckets[dest_name])if canned_acl:_object_acl[(bucket_name, key, obj.get("version_id"))] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())++ # Persist only after the versioning block: the .meta.json sidecar must+ # carry the version_id assigned above (#1058), and the tags and ACL.+ if S3_PERSIST:+ _persist_object(bucket_name, key, obj)return 200, resp_headers, b""@@ -3949,18 +3946,19 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):_maybe_replicate(bucket_name, key, obj, file_value)version_id = _record_object_version(bucket_name, key, prior_obj, obj, file_value)- # Persist only after the versioning block: the .meta.json sidecar must- # carry the version_id assigned above (#1058).- if S3_PERSIST:- _persist_object(bucket_name, key, obj)-if pending_tags is not None:_object_tags[(bucket_name, key, version_id)] = pending_tagsif obj.get("_replica"):_object_tags[(obj["_replica"][0], key, obj["_replica"][1])] = dict(pending_tags)+ _persist_version_state(obj["_replica"][0], key, _buckets[obj["_replica"][0]])if canned_acl:_object_acl[(bucket_name, key, version_id)] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())+ # Persist only after the versioning block: the .meta.json sidecar must+ # carry the version_id assigned above (#1058), and the tags and ACL.+ if S3_PERSIST:+ _persist_object(bucket_name, key, obj)+location = f"http://{bucket_name}.s3.amazonaws.com/{url_quote(key, safe='/')}"base_resp = {"ETag": etag, "Location": location}if version_id:@@ -4095,9 +4093,9 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =precondition = _check_read_preconditions(headers, vobj, resp_headers)if precondition is not None:return precondition- body = v.get("data")+ body = _version_body(bucket, bucket_name, key, v)if body is None:- body = _read_body(bucket_name, key, bucket["objects"].get(key, {}))+ breakreturn 200, resp_headers, bodyreturn _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")@@ -4497,6 +4495,7 @@ def _record_object_version(bucket_name: str, key: str, prior_obj: dict | None, oversioning = _bucket_versioning.get(bucket_name)if versioning not in ("Enabled", "Suspended"):return None+ _persist_displaced_version(bucket_name, key, prior_obj, versioning)vkey = (bucket_name, key)versions = _object_versions.setdefault(vkey, [])if versioning == "Enabled":@@ -4518,9 +4517,11 @@ def _record_delete_marker(bucket_name: str, key: str, prior_obj: dict | None) ->"""Append a delete marker per the bucket's versioning state and return itsversion id: a fresh id on Enabled, the literal "null" on Suspended — wherethe marker REPLACES any existing null version, as AWS does."""+ enabled = _bucket_versioning.get(bucket_name) == "Enabled"+ _persist_displaced_version(bucket_name, key, prior_obj, "Enabled" if enabled else "Suspended")vkey = (bucket_name, key)versions = _object_versions.setdefault(vkey, [])- if _bucket_versioning.get(bucket_name) == "Enabled":+ if enabled:_preserve_null_version(bucket_name, key, versions, prior_obj)marker_id = new_uuid()else:@@ -4539,7 +4540,7 @@ def _record_delete_marker(bucket_name: str, key: str, prior_obj: dict | None) ->versions.append(marker)# Persist the marker to the key's sidecar so a restart keeps the object# hidden instead of resurrecting it from its still-present data file.- _persist_delete_marker(bucket_name, key, marker, prior_obj)+ _persist_delete_marker(bucket_name, key, marker)return marker_id@@ -4603,6 +4604,7 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str, version_id:return False, Falseremoved = versions.pop(idx)+ _delete_version_file(bucket_name, key, version_id)was_delete_marker = bool(removed.get("is_delete_marker"))# Per-version tags and ACLs travel with the version being removed._object_tags.pop((bucket_name, key, version_id), None)@@ -4625,7 +4627,9 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str, version_id:if latest.get("is_delete_marker"):bucket["objects"].pop(key, None)else:- bucket["objects"][key] = _object_record_from_version(latest)+ record = _object_record_from_version(latest)+ record["body"] = _version_body(bucket, bucket_name, key, latest)+ bucket["objects"][key] = record# The key now resolves to a different version (or to a marker): align the# sidecar so a restart does not restore the pre-delete view._persist_version_state(bucket_name, key, bucket)@@ -4856,7 +4860,10 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):(v for v in _object_versions.get((src_bucket_name, src_key), []) if v["version_id"] == src_version_id),None,)- if ventry is None or ventry.get("is_delete_marker"):+ ventry_body = None+ if ventry is not None and not ventry.get("is_delete_marker"):+ ventry_body = _version_body(src_bucket, src_bucket_name, src_key, ventry)+ if ventry_body is None:return _error("NoSuchVersion","The specified version does not exist.",@@ -4867,7 +4874,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):# the body plus the wire metadata, so a COPY metadata-directive carries# the version's user metadata and headers like a current-object copy.src_obj = {- "body": ventry.get("data", b""),+ "body": ventry_body,"etag": ventry["etag"],"size": ventry["size"],"last_modified": ventry["last_modified"],@@ -5005,16 +5012,12 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):if version_id:resp_headers["x-amz-version-id"] = version_id- # Persist only after the versioning block: the .meta.json sidecar must- # carry the version_id assigned above (#1058).- if S3_PERSIST:- _persist_object(bucket_name, dest_key, dest_obj)-dest_version_id = dest_obj.get("version_id")if pending_dest_tags is not None:_object_tags[(bucket_name, dest_key, dest_version_id)] = pending_dest_tagsif dest_obj.get("_replica"):_object_tags[(dest_obj["_replica"][0], dest_key, dest_obj["_replica"][1])] = dict(pending_dest_tags)+ _persist_version_state(dest_obj["_replica"][0], dest_key, _buckets[dest_obj["_replica"][0]])else:_object_tags.pop((bucket_name, dest_key, dest_version_id), None)@@ -5027,6 +5030,11 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):# key it replaced was permissioned with._object_acl.pop((bucket_name, dest_key, dest_version_id), None)+ # Persist only after the versioning block: the .meta.json sidecar must+ # carry the version_id assigned above (#1058), and the tags and ACL.+ if S3_PERSIST:+ _persist_object(bucket_name, dest_key, dest_obj)+root = Element("CopyObjectResult", xmlns=S3_NS)SubElement(root, "LastModified").text = last_modifiedSubElement(root, "ETag").text = new_etag@@ -5129,6 +5137,7 @@ def _put_object_tagging(bucket_name: str, key: str, body: bytes, query_params: dreturn goneversion_id = _resolve_subresource_version(query_params, bucket, key)_object_tags[(bucket_name, key, version_id)] = tags+ _persist_version_state(bucket_name, key, bucket)resp_headers = {"Content-Type": "application/xml"}if version_id:resp_headers["x-amz-version-id"] = version_id@@ -5151,6 +5160,7 @@ def _delete_object_tagging(bucket_name: str, key: str, query_params: dict | Nonereturn goneversion_id = _resolve_subresource_version(query_params, bucket, key)_object_tags.pop((bucket_name, key, version_id), None)+ _persist_version_state(bucket_name, key, bucket)resp_headers = {}if version_id:resp_headers["x-amz-version-id"] = version_id@@ -5543,6 +5553,7 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict, querif canned not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned}", 400)_object_acl[(bucket_name, key, version_id)] = _canned_acl_policy_xml(canned, _canonical_owner_id())+ _persist_version_state(bucket_name, key, bucket)return 200, {}, b""if not body:@@ -5560,6 +5571,7 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict, quer400,)_object_acl[(bucket_name, key, version_id)] = body.decode("utf-8", errors="replace")+ _persist_version_state(bucket_name, key, bucket)return 200, {}, b""@@ -6148,14 +6160,16 @@ def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, heade(v for v in _object_versions.get((src_bucket_name, src_key), []) if v["version_id"] == src_version_id),None,)- if ventry is None or ventry.get("is_delete_marker"):+ src_body = None+ if ventry is not None and not ventry.get("is_delete_marker"):+ src_body = _version_body(src_bucket, src_bucket_name, src_key, ventry)+ if src_body is None:return _error("NoSuchVersion","The specified version does not exist.",404,f"/{src_bucket_name}/{src_key}",)- src_body = ventry.get("data") or b""else:if src_key not in src_bucket["objects"]:return _error("NoSuchKey", "The specified key does not exist.", 404)@@ -6638,7 +6652,8 @@ def _persist_object(bucket: str, key: str, obj):data = obj.get("body")if data is not None:_atomic_write(fpath, data)- _atomic_write(fpath + ".meta.json", json.dumps(_object_meta_from_record(obj)), text=True)+ meta = {**_object_meta_from_record(obj), **_key_history_meta(bucket, key)}+ _atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)# Drop body from in-memory record to save RAMobj["body"] = Noneelse:@@ -6647,15 +6662,13 @@ def _persist_object(bucket: str, key: str, obj):logger.warning("Failed to persist S3 object %s/%s: %s", bucket, key, e)-def _persist_delete_marker(bucket_name: str, key: str, marker: dict, prior_obj: dict | None):+def _persist_delete_marker(bucket_name: str, key: str, marker: dict):"""Record a delete marker in the key's .meta.json sidecar.A marker has no body, so it cannot ride the data file the way a versiondoes — the sidecar is its only on-disk record. Without it a restart findsthe hidden object's data file, reloads it as current, and the deleted- object reappears. The displaced object's metadata is kept under- ``previous`` so its version entry can be rebuilt when the marker is later- removed."""+ object reappears."""if not S3_PERSIST:returntry:@@ -6667,9 +6680,8 @@ def _persist_delete_marker(bucket_name: str, key: str, marker: dict, prior_obj:"is_delete_marker": True,"version_id": marker.get("version_id"),"last_modified": marker.get("last_modified", ""),+ **_key_history_meta(bucket_name, key),}- if prior_obj:- meta["previous"] = _object_meta_from_record(prior_obj)_atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)except Exception as e:logger.warning("Failed to persist S3 delete marker %s/%s: %s", bucket_name, key, e)@@ -6686,16 +6698,96 @@ def _persist_version_state(bucket_name: str, key: str, bucket: dict):versions = _object_versions.get((bucket_name, key)) or []latest = versions[-1] if versions else Noneif latest is not None and latest.get("is_delete_marker"):- # Keep the newest real version below the marker so its metadata is not- # lost from the sidecar's `previous` snapshot.- prior = next((v for v in reversed(versions[:-1]) if not v.get("is_delete_marker")), None)- _persist_delete_marker(bucket_name, key, latest, prior)+ _persist_delete_marker(bucket_name, key, latest)elif key in bucket["objects"]:_persist_object(bucket_name, key, bucket["objects"][key])else:_delete_persisted_object(bucket_name, key)+def _key_history_meta(bucket_name: str, key: str) -> dict:+ versions = _object_versions.get((bucket_name, key)) or []+ extra = {}+ if versions:+ extra["versions"] = [{k: v for k, v in e.items() if k != "data"} for e in versions]+ vids = [None] + [v["version_id"] for v in versions if v["version_id"] != "null" and not v.get("is_delete_marker")]+ for field, store in (("tags", _object_tags), ("acl", _object_acl)):+ found = {vid or "null": store.get((bucket_name, key, vid)) for vid in vids}+ found = {vid: value for vid, value in found.items() if value is not None}+ if found:+ extra[field] = found+ return extra+++_VERSIONS_DIR = ".versions"+++def _version_disk_path(bucket: str, key: str, version_id: str, account_id: str = None) -> str | None:+ if account_id is None:+ account_id = get_account_id()+ root = os.path.realpath(os.path.join(DATA_DIR, _VERSIONS_DIR, account_id, bucket, version_id))+ candidate = os.path.realpath(os.path.join(root, key))+ try:+ if candidate == root or os.path.commonpath([root, candidate]) != root:+ logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)+ return None+ except ValueError:+ logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)+ return None+ return candidate+++def _version_file_exists(bucket_name: str, key: str, version_id: str, account_id: str = None) -> bool:+ fpath = _version_disk_path(bucket_name, key, version_id, account_id)+ return fpath is not None and os.path.isfile(fpath)+++def _persist_displaced_version(bucket_name: str, key: str, prior_obj: dict | None, versioning: str):+ if not S3_PERSIST:+ return+ try:+ if versioning == "Suspended":+ _delete_version_file(bucket_name, key, "null")+ if prior_obj is None:+ return+ prior_vid = prior_obj.get("version_id") or "null"+ if versioning == "Suspended" and prior_vid == "null":+ return+ fpath = _version_disk_path(bucket_name, key, prior_vid)+ if fpath is None:+ return+ os.makedirs(os.path.dirname(fpath), mode=0o700, exist_ok=True)+ _atomic_write(fpath, _read_body(bucket_name, key, prior_obj))+ except Exception as e:+ logger.warning("Failed to persist S3 object version %s/%s: %s", bucket_name, key, e)+++def _delete_version_file(bucket_name: str, key: str, version_id: str):+ if not S3_PERSIST:+ return+ try:+ fpath = _version_disk_path(bucket_name, key, version_id)+ if fpath is not None and os.path.exists(fpath):+ os.remove(fpath)+ except Exception as e:+ logger.warning("Failed to delete persisted S3 object version %s/%s: %s", bucket_name, key, e)+++def _version_body(bucket: dict, bucket_name: str, key: str, v: dict) -> bytes | None:+ if v.get("data") is not None:+ return v["data"]+ if S3_PERSIST and _version_file_exists(bucket_name, key, v["version_id"]):+ try:+ with open(_version_disk_path(bucket_name, key, v["version_id"]), "rb") as f:+ return f.read()+ except Exception as e:+ logger.warning("Failed to read persisted S3 object version %s/%s: %s", bucket_name, key, e)+ current = bucket["objects"].get(key)+ if current is not None and (current.get("version_id") or "null") == v["version_id"]:+ return _read_body(bucket_name, key, current)+ return None++def _read_body(bucket_name: str, key: str, obj: dict) -> bytes:"""Return object body — from memory if available, else from disk."""body = obj.get("body")@@ -6774,6 +6866,8 @@ def _load_persisted_data():entry_path = os.path.join(DATA_DIR, entry)if not os.path.isdir(entry_path):continue+ if entry == _VERSIONS_DIR:+ continue# Detect if this entry is an account ID directory (12-digit or has bucket subdirs)if entry.isdigit() and len(entry) == 12:# New layout: entry is an account ID@@ -6853,6 +6947,9 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):}if meta.get("version_id"):bucket["objects"][key]["version_id"] = meta["version_id"]+ if "versions" in meta or "tags" in meta or "acl" in meta:+ _load_persisted_history(account_id, bucket, bucket_name, key, meta)+ elif meta.get("version_id"):vkey = (bucket_name, key)scoped_vkey = (account_id, vkey)if scoped_vkey not in _object_versions._data:@@ -6894,46 +6991,50 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):def _load_persisted_delete_marker(account_id, bucket, bucket_name, key, meta):- """Rebuild a persisted delete marker and hide the key.+ """Rebuild a persisted delete marker and hide the key."""+ bucket["objects"].pop(key, None)+ if "versions" in meta:+ _load_persisted_history(account_id, bucket, bucket_name, key, meta)+ return+ _object_versions._data[(account_id, (bucket_name, key))] = [+ {+ "version_id": meta.get("version_id") or "null",+ "last_modified": meta.get("last_modified") or now_iso(),+ "etag": "",+ "size": 0,+ "is_latest": True,+ "is_delete_marker": True,+ }+ ]+- The metadata of the version the marker displaced is kept under- ``previous`` so its version entry can be restored below the marker —- otherwise ListObjectVersions would lose it across a restart."""+def _load_persisted_history(account_id, bucket, bucket_name, key, meta):+ """Rebuild a key's version history, tags and ACLs from its sidecar. A real+ version comes back only when its bytes did."""+ current = bucket["objects"].get(key)+ current_vid = (current.get("version_id") or "null") if current is not None else None+ versions = [+ dict(v, data=None)+ for v in meta.get("versions", [])+ if v.get("is_delete_marker")+ or v["version_id"] == current_vid+ or _version_file_exists(bucket_name, key, v["version_id"], account_id)+ ]scoped_vkey = (account_id, (bucket_name, key))- versions = _object_versions._data.setdefault(scoped_vkey, [])- prev = meta.get("previous")- if prev:- prev_id = prev.get("version_id") or "null"- if not any(not v.get("is_delete_marker") and v.get("version_id") == prev_id for v in versions):- versions.append(- {- "version_id": prev_id,- "last_modified": prev.get("last_modified") or now_iso(),- "etag": prev.get("etag", ""),- "size": prev.get("size", 0),- "is_latest": False,- "data": None,- "content_type": prev.get("content_type", "application/octet-stream"),- "content_encoding": prev.get("content_encoding"),- "metadata": prev.get("metadata", {}),- "preserved_headers": prev.get("preserved_headers", {}),- "storage_class": prev.get("storage_class", "STANDARD"),- "checksums": prev.get("checksums", {}),- }- )- marker_id = meta.get("version_id") or "null"- if not any(v.get("is_delete_marker") and v.get("version_id") == marker_id for v in versions):- versions.append(- {- "version_id": marker_id,- "last_modified": meta.get("last_modified") or now_iso(),- "etag": "",- "size": 0,- "is_latest": True,- "is_delete_marker": True,- }- )- bucket["objects"].pop(key, None)+ if versions:+ for v in versions:+ v["is_latest"] = False+ versions[-1]["is_latest"] = True+ _object_versions._data[scoped_vkey] = versions+ else:+ _object_versions._data.pop(scoped_vkey, None)+ live = {v["version_id"] for v in versions if not v.get("is_delete_marker")}+ if current is not None and not current.get("version_id"):+ live.add("null")+ for field, store in (("tags", _object_tags), ("acl", _object_acl)):+ for vid, value in (meta.get(field) or {}).items():+ if vid in live:+ store._data[(account_id, (bucket_name, key, None if vid == "null" else vid))] = value_load_persisted_data()diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 496cb362..d27dfcbc 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -128,12 +128,7 @@ _sub_arn_to_topic = AccountRegionScopedDict()_platform_applications = AccountRegionScopedDict()_platform_endpoints = AccountRegionScopedDict()-# Direct-to-phone publishes, keyed by recipient phone number. SES and SQS both-# keep what they were sent so a test can read it back-# (/_ministack/ses/messages, /_ministack/sqs/messages); SNS was the one-# messaging service that logged a line and stored nothing, so an SMS was the-# only thing you could send and not observe. Served by app.py at-# /_ministack/sns/sms-messages.+# Direct-to-phone publishes by recipient, served at /_ministack/sns/sms-messages._sms_messages = AccountRegionScopedDict()@@ -749,10 +744,6 @@ def _publish(params):if phone_number and not topic_arn:msg_id = new_uuid()- # There is nowhere for an SMS to go, so record it instead of dropping- # it. Field names and nulls match what the endpoint serves, so the- # record needs no reshaping on the way out. `_p` defaults an absent- # parameter to "", and an absent Subject reads as null, not ""._sms_log_for(phone_number).append({"PhoneNumber": phone_number,"TopicArn": None,diff --git a/pyproject.toml b/pyproject.tomlindex 51044256..884a7484 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.5.15"+version = "1.5.16"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 ae4a0610..fa347bac 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -194,7 +194,7 @@ _SERIAL_TESTS = {# IoT Jobs data-plane routing test: a raw urllib GET with the advertised# `{prefix}.jobs.iot.{region}` Host and a tight 5s timeout, so cross-file# xdist pressure on the shared event loop makes it time out at random.- "tests/test_iot_jobs.py::test_iot_jobs_endpoint_host_reaches_the_data_plane",+ "tests/test_iot_jobs_data.py::test_iot_jobs_endpoint_host_reaches_the_data_plane",# ECS service task-spawn: with a Docker daemon present (CI has one) a task# whose container fails to start/exits under parallel container churn is set# STOPPED, so list_tasks (RUNNING-only) sees fewer than desiredCount. Passesdiff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 0cdaf33b..8275285a 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -1,5 +1,6 @@"""API Gateway v2 tests — HTTP API + WebSocket + common lifecycle."""+import asyncioimport base64import ioimport json@@ -7,6 +8,7 @@ import osimport threadingimport timeimport urllib.error+import urllib.parseimport urllib.requestimport uuid as _uuid_modimport zipfile@@ -23,6 +25,9 @@ from conftest import (make_probe_lambda,)+from ministack.core.responses import get_account_id, get_region, set_request_account_id, set_request_region+from ministack.services import apigateway as _apigw+_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")_EXECUTE_PORT = urlparse(_endpoint).port or 4566@@ -4321,3 +4326,144 @@ def test_apigwv2_aws_iam_route_fills_authorizer_iam(apigw, lam, cognito_identityfinally:apigw.delete_api(ApiId=api_id)lam.delete_function(FunctionName=fname)+++def _reset_apigateway_state():+ original_account = get_account_id()+ original_region = get_region()+ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ _apigw.reset()+ try:+ yield+ finally:+ _apigw.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def _payload(response):+ status, _headers, body = response+ return status, json.loads(body or b"{}")+++def _post_tags_path(resource_arn, tags):+ encoded_arn = urllib.parse.quote(resource_arn, safe="")+ body = json.dumps({"tags": tags}).encode("utf-8")+ return asyncio.run(_apigw.handle_request("POST", f"/v2/tags/{encoded_arn}", {}, body, {}))+++def _create_api(name="tag-arn-api"):+ status, body = _payload(_apigw._create_api({"name": name, "protocolType": "HTTP"}))+ assert status == 201+ return body["apiId"]++[email protected]("_reset_apigateway_state")+def test_apigwv2_tag_api_arn_decodes_and_uses_canonical_key():+ api_id = _create_api()+ api_arn = _apigw._api_arn(api_id)++ status, _headers, _body = _post_tags_path(api_arn, {"env": "test"})++ assert status == 201+ assert _apigw._api_tags.get(api_arn) == {"env": "test"}++ status, body = _payload(_apigw._get_tags(api_arn))+ assert status == 200+ assert body["tags"] == {"env": "test"}++[email protected]("_reset_apigateway_state")+def test_apigwv2_tag_arns_accept_existing_local_api_and_stage_resources():+ api_id = _create_api("tag-stage-api")++ stage_status, _stage_body = _payload(+ _apigw._create_stage(api_id, {"stageName": "$default", "tags": {"created": "stage"}})+ )+ assert stage_status == 201++ stage_arn = _apigw._api_resource_arn(api_id, "stages", "$default")+ status, _headers, _body = _apigw._tag_resource(stage_arn, {"tags": {"owner": "team-a"}})+ assert status == 201++ stage_status, stage_body = _payload(_apigw._get_tags(stage_arn))+ assert stage_status == 200+ assert stage_body["tags"] == {"created": "stage", "owner": "team-a"}++[email protected]("_reset_apigateway_state")+def test_apigwv2_tag_arns_reject_invalid_or_nonlocal_resources_before_touching_tags():+ api_id = _create_api("tag-reject-api")+ route_status, route = _payload(_apigw._create_route(api_id, {"routeKey": "GET /items"}))+ assert route_status == 201+ integration_status, integration = _payload(+ _apigw._create_integration(+ api_id,+ {+ "integrationType": "HTTP_PROXY",+ "integrationUri": "https://example.com",+ "integrationMethod": "GET",+ },+ )+ )+ assert integration_status == 201+ deployment_status, deployment = _payload(_apigw._create_deployment(api_id, {}))+ assert deployment_status == 201+ authorizer_status, authorizer = _payload(+ _apigw._create_authorizer(+ api_id,+ {+ "name": "request-auth",+ "authorizerType": "REQUEST",+ "authorizerUri": "not-an-arn",+ "authorizerCredentialsArn": "also-not-an-arn",+ },+ )+ )+ assert authorizer_status == 201++ bad_arns = [+ ("not-an-arn", "BadRequestException"),+ (f"arn:aws-us-gov:apigateway:us-east-1::/apis/{api_id}", "BadRequestException"),+ (f"arn:aws:execute-api:us-east-1::/apis/{api_id}", "BadRequestException"),+ (f"arn:aws:apigateway:us-west-2::/apis/{api_id}", "BadRequestException"),+ (f"arn:aws:apigateway:us-east-1:000000000000:/apis/{api_id}", "BadRequestException"),+ ("arn:aws:apigateway:us-east-1::/domainnames/example.com", "BadRequestException"),+ (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes", "BadRequestException"),+ (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes/{route['routeId']}", "BadRequestException"),+ (+ f"arn:aws:apigateway:us-east-1::/apis/{api_id}/integrations/{integration['integrationId']}",+ "BadRequestException",+ ),+ (+ f"arn:aws:apigateway:us-east-1::/apis/{api_id}/deployments/{deployment['deploymentId']}",+ "BadRequestException",+ ),+ (+ f"arn:aws:apigateway:us-east-1::/apis/{api_id}/authorizers/{authorizer['authorizerId']}",+ "BadRequestException",+ ),+ ("arn:aws:apigateway:us-east-1::/apis/missing", "NotFoundException"),+ (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/stages/missing", "NotFoundException"),+ ]++ for resource_arn, expected_code in bad_arns:+ before = dict(_apigw._api_tags.items())+ status, body = _payload(_apigw._tag_resource(resource_arn, {"tags": {"bad": "tag"}}))+ assert status in (400, 404)+ assert body["__type"] == expected_code+ assert dict(_apigw._api_tags.items()) == before+ assert _apigw._api_tags.get(resource_arn) is None++ stage_status, _stage = _payload(_apigw._create_stage(api_id, {"stageName": "prod"}))+ assert stage_status == 201+ stage_arn = _apigw._api_resource_arn(api_id, "stages", "prod")+ assert _apigw._tag_resource(stage_arn, {"tags": {"ok": "yes"}})[0] == 201+ assert _apigw._api_tags.get(stage_arn) == {"ok": "yes"}+ assert _apigw._delete_stage(api_id, "prod")[0] == 204+ status, body = _payload(_apigw._get_tags(stage_arn))+ assert status == 404+ assert body["__type"] == "NotFoundException"+ assert _apigw._api_tags.get(stage_arn) is Nonediff --git a/tests/test_apigatewayv2_tag_arns.py b/tests/test_apigatewayv2_tag_arns.pydeleted file mode 100644index f50e454e..00000000--- a/tests/test_apigatewayv2_tag_arns.py+++ /dev/null@@ -1,146 +0,0 @@-import asyncio-import json-import urllib.parse--import pytest--from ministack.core.responses import get_account_id, get_region, set_request_account_id, set_request_region-from ministack.services import apigateway as _apigw--[email protected](autouse=True)-def _reset_apigateway_state():- original_account = get_account_id()- original_region = get_region()- set_request_account_id("000000000000")- set_request_region("us-east-1")- _apigw.reset()- try:- yield- finally:- _apigw.reset()- set_request_account_id(original_account)- set_request_region(original_region)---def _payload(response):- status, _headers, body = response- return status, json.loads(body or b"{}")---def _post_tags_path(resource_arn, tags):- encoded_arn = urllib.parse.quote(resource_arn, safe="")- body = json.dumps({"tags": tags}).encode("utf-8")- return asyncio.run(_apigw.handle_request("POST", f"/v2/tags/{encoded_arn}", {}, body, {}))---def _create_api(name="tag-arn-api"):- status, body = _payload(_apigw._create_api({"name": name, "protocolType": "HTTP"}))- assert status == 201- return body["apiId"]---def test_apigwv2_tag_api_arn_decodes_and_uses_canonical_key():- api_id = _create_api()- api_arn = _apigw._api_arn(api_id)-- status, _headers, _body = _post_tags_path(api_arn, {"env": "test"})-- assert status == 201- assert _apigw._api_tags.get(api_arn) == {"env": "test"}-- status, body = _payload(_apigw._get_tags(api_arn))- assert status == 200- assert body["tags"] == {"env": "test"}---def test_apigwv2_tag_arns_accept_existing_local_api_and_stage_resources():- api_id = _create_api("tag-stage-api")-- stage_status, _stage_body = _payload(- _apigw._create_stage(api_id, {"stageName": "$default", "tags": {"created": "stage"}})- )- assert stage_status == 201-- stage_arn = _apigw._api_resource_arn(api_id, "stages", "$default")- status, _headers, _body = _apigw._tag_resource(stage_arn, {"tags": {"owner": "team-a"}})- assert status == 201-- stage_status, stage_body = _payload(_apigw._get_tags(stage_arn))- assert stage_status == 200- assert stage_body["tags"] == {"created": "stage", "owner": "team-a"}---def test_apigwv2_tag_arns_reject_invalid_or_nonlocal_resources_before_touching_tags():- api_id = _create_api("tag-reject-api")- route_status, route = _payload(_apigw._create_route(api_id, {"routeKey": "GET /items"}))- assert route_status == 201- integration_status, integration = _payload(- _apigw._create_integration(- api_id,- {- "integrationType": "HTTP_PROXY",- "integrationUri": "https://example.com",- "integrationMethod": "GET",- },- )- )- assert integration_status == 201- deployment_status, deployment = _payload(_apigw._create_deployment(api_id, {}))- assert deployment_status == 201- authorizer_status, authorizer = _payload(- _apigw._create_authorizer(- api_id,- {- "name": "request-auth",- "authorizerType": "REQUEST",- "authorizerUri": "not-an-arn",- "authorizerCredentialsArn": "also-not-an-arn",- },- )- )- assert authorizer_status == 201-- bad_arns = [- ("not-an-arn", "BadRequestException"),- (f"arn:aws-us-gov:apigateway:us-east-1::/apis/{api_id}", "BadRequestException"),- (f"arn:aws:execute-api:us-east-1::/apis/{api_id}", "BadRequestException"),- (f"arn:aws:apigateway:us-west-2::/apis/{api_id}", "BadRequestException"),- (f"arn:aws:apigateway:us-east-1:000000000000:/apis/{api_id}", "BadRequestException"),- ("arn:aws:apigateway:us-east-1::/domainnames/example.com", "BadRequestException"),- (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes", "BadRequestException"),- (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/routes/{route['routeId']}", "BadRequestException"),- (- f"arn:aws:apigateway:us-east-1::/apis/{api_id}/integrations/{integration['integrationId']}",- "BadRequestException",- ),- (- f"arn:aws:apigateway:us-east-1::/apis/{api_id}/deployments/{deployment['deploymentId']}",- "BadRequestException",- ),- (- f"arn:aws:apigateway:us-east-1::/apis/{api_id}/authorizers/{authorizer['authorizerId']}",- "BadRequestException",- ),- ("arn:aws:apigateway:us-east-1::/apis/missing", "NotFoundException"),- (f"arn:aws:apigateway:us-east-1::/apis/{api_id}/stages/missing", "NotFoundException"),- ]-- for resource_arn, expected_code in bad_arns:- before = dict(_apigw._api_tags.items())- status, body = _payload(_apigw._tag_resource(resource_arn, {"tags": {"bad": "tag"}}))- assert status in (400, 404)- assert body["__type"] == expected_code- assert dict(_apigw._api_tags.items()) == before- assert _apigw._api_tags.get(resource_arn) is None-- stage_status, _stage = _payload(_apigw._create_stage(api_id, {"stageName": "prod"}))- assert stage_status == 201- stage_arn = _apigw._api_resource_arn(api_id, "stages", "prod")- assert _apigw._tag_resource(stage_arn, {"tags": {"ok": "yes"}})[0] == 201- assert _apigw._api_tags.get(stage_arn) == {"ok": "yes"}- assert _apigw._delete_stage(api_id, "prod")[0] == 204- status, body = _payload(_apigw._get_tags(stage_arn))- assert status == 404- assert body["__type"] == "NotFoundException"- assert _apigw._api_tags.get(stage_arn) is Nonediff --git a/tests/test_bedrock.py b/tests/test_bedrock.pyindex 61d40f3a..4441d9cd 100644--- a/tests/test_bedrock.py+++ b/tests/test_bedrock.py@@ -1960,6 +1960,37 @@ def test_bedrock_converse_stream_emits_the_tool_use_event_sequence():assert dict(events)["messageStop"] == {"stopReason": "tool_use"}+def test_bedrock_converse_tool_call_reports_the_proxy_token_usage(monkeypatch):+ """A tool-call turn has no text to estimate from; the proxy's own usage is+ the model's token count, tool schema and tool call included."""+ import io++ from botocore.eventstream import EventStreamBuffer++ from ministack.services import bedrock_runtime as br++ reply = {"choices": [{"message": {"role": "assistant", "content": "", "tool_calls": [+ {"id": "call_abc", "type": "function",+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}]}}],+ "usage": {"prompt_tokens": 158, "completion_tokens": 20, "total_tokens": 178}}+ monkeypatch.setattr(br, "_PROXY_URL", "http://proxy.invalid")+ monkeypatch.setattr(br.urllib.request, "urlopen",+ lambda *a, **k: io.BytesIO(json.dumps(reply).encode()))++ message, counts = br._proxy_openai_chat_message(+ "m", [{"role": "user", "content": [{"text": "weather?"}]}], [], None)+ assert message["tool_calls"][0]["id"] == "call_abc"+ assert counts == (158, 20)++ raw = br._build_converse_stream(+ "m", [{"role": "user", "content": [{"text": "weather?"}]}], [], 0, "",+ stop_reason="tool_use", input_tokens=158, output_tokens=20)+ buffer = EventStreamBuffer()+ buffer.add_data(raw)+ metadata = [json.loads(e.payload) for e in buffer if e.headers.get(":event-type") == "metadata"][0]+ assert metadata["usage"] == {"inputTokens": 158, "outputTokens": 20, "totalTokens": 178}++def test_bedrock_converse_stream_without_tools_is_unchanged():from botocore.eventstream import EventStreamBufferdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 8571f1c4..e0ec91a2 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -16,6 +16,12 @@ from botocore.config import Configfrom botocore.exceptions import ClientErrorfrom ministack.services import pipes as _pipes+from ministack.services.cloudformation.provisioners import (+ _CONDITIONALLY_REPLACING_PROPERTIES,+ _REPLACING_PROPERTIES,+ _RESOURCE_HANDLERS,+)+from ministack.services.cloudformation.stacks import _diff_resourcesdef _cfn_iceberg_json(path):@@ -24492,3 +24498,220 @@ def test_cfn_rds_instance_in_a_cluster_defaults_to_delete(cfn, rds):assert exc.value.response["Error"]["Code"] == "DBSnapshotNotFound"finally:_delete_cfn_test_stack(cfn, stack_name)+++def _template(resource_type, properties):+ return {"Resources": {"R": {"Type": resource_type, "Properties": properties}}}+++def stack(cfn):+ names = []++ def create(template):+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ names.append(name)+ cfn.get_waiter("stack_create_complete").wait(+ StackName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})+ return name++ yield create+ for name in names:+ cfn.delete_stack(StackName=name)+ cfn.get_waiter("stack_delete_complete").wait(+ StackName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})+++def _change(cfn, name, template):+ cfn.create_change_set(StackName=name, ChangeSetName="cs", ChangeSetType="UPDATE",+ TemplateBody=json.dumps(template))+ cfn.get_waiter("change_set_create_complete").wait(+ StackName=name, ChangeSetName="cs", WaiterConfig={"Delay": 1, "MaxAttempts": 30})+ return cfn.describe_change_set(StackName=name, ChangeSetName="cs")["Changes"][0]["ResourceChange"]+++def _requirements(change):+ return {d["Target"]["Name"]: d["Target"]["RequiresRecreation"]+ for d in change.get("Details", []) if d["Target"].get("Name")}+++# These are independent AWS observations, including negative cases where+# service API immutability must not be turned into an Always result.[email protected]("rtype,old,new,expected", [+ ("AWS::Cognito::UserPool", {"UserPoolName": "before"}, {"UserPoolName": "after"}, "Never"),+ ("AWS::Cognito::UserPool", {}, {"Schema": [{"Name": "review", "AttributeDataType": "String"}]}, "Never"),+ ("AWS::IoT::ThingType",+ {"ThingTypeProperties": {"Mqtt5Configuration": {"PropagatingAttributes": []}}},+ {"ThingTypeProperties": {"Mqtt5Configuration": {"PropagatingAttributes": [{"UserPropertyKey": "k", "ThingAttribute": "v"}]}}}, "Never"),+ ("AWS::DynamoDB::Table",+ {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]},+ {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "N"}]}, "Never"),+ ("AWS::DynamoDB::Table", {}, {"ImportSourceSpecification": {"InputFormat": "CSV"}}, "Always"),+ ("AWS::DynamoDB::Table", {"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}]},+ {"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}]},+ "Conditionally"),+ ("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}},+ {"DurableConfig": {"ExecutionTimeout": 120}}, "Conditionally"),+ ("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}}, {}, "Conditionally"),+ ("AWS::SQS::Queue", {"QueueName": "before"}, {"QueueName": "after"}, "Always"),+ ("AWS::SQS::Queue", {"FifoQueue": False}, {"FifoQueue": True}, "Always"),+ ("AWS::SQS::Queue", {"DelaySeconds": 0}, {"DelaySeconds": 5}, "Never"),+ ("AWS::SSM::Parameter", {"Value": "before"}, {"Value": "after"}, "Never"),+ ("AWS::SNS::Topic", {"FifoTopic": False}, {"FifoTopic": True}, "Always"),+ # Fixed at CreateUserPool by the service API, yet reported in place.+ ("AWS::Cognito::UserPool", {}, {"AliasAttributes": ["email"]}, "Never"),+ ("AWS::Lambda::LayerVersion", {"Content": {"S3Bucket": "layers", "S3Key": "a.zip"}},+ {"Content": {"S3Bucket": "layers", "S3Key": "b.zip"}}, "Always"),+])+def test_property_reporting(rtype, old, new, expected):+ change = _diff_resources(_template(rtype, old), _template(rtype, new))[0]["ResourceChange"]+ assert set(_requirements(change).values()) == {expected}+ assert change["Replacement"] == {"Never": "False", "Always": "True", "Conditionally": "Conditional"}[expected]+++def test_adding_a_dynamodb_index_does_not_report_replacement():+ old = {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]}+ new = {+ "AttributeDefinitions": [*old["AttributeDefinitions"], {"AttributeName": "gpk", "AttributeType": "S"}],+ "GlobalSecondaryIndexes": [{"IndexName": "review", "KeySchema": [{"AttributeName": "gpk", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "KEYS_ONLY"}}],+ }+ change = _diff_resources(_template("AWS::DynamoDB::Table", old), _template("AWS::DynamoDB::Table", new))[0]["ResourceChange"]+ assert change["Replacement"] == "False"+ assert _requirements(change) == {"AttributeDefinitions": "Never", "GlobalSecondaryIndexes": "Never"}+++# Measured AWS change sets: a listed type reports every property its schema+# does not mark create-only or conditionally create-only as Never.[email protected]("rtype,old,new", [+ ("AWS::DynamoDB::Table", {}, {"TimeToLiveSpecification": {"AttributeName": "ttl", "Enabled": True}}),+ ("AWS::DynamoDB::Table", {}, {"Tags": [{"Key": "review", "Value": "1"}]}),+ ("AWS::Lambda::Function", {"Timeout": 30}, {"Timeout": 45}),+ ("AWS::StepFunctions::StateMachine", {"DefinitionString": "a"}, {"DefinitionString": "b"}),+ ("AWS::Cognito::UserPoolGroup", {"Description": "a"}, {"Description": "b"}),+ ("AWS::Cognito::UserPoolResourceServer", {"Name": "a"}, {"Name": "b"}),+ ("AWS::IoT::ThingGroup", {"ThingGroupProperties": {"ThingGroupDescription": "a"}},+ {"ThingGroupProperties": {"ThingGroupDescription": "b"}}),+ ("AWS::IoT::ProvisioningTemplate", {"Description": "a"}, {"Description": "b"}),+ ("AWS::IAM::InstanceProfile", {"Roles": ["a"]}, {"Roles": ["b"]}),+ ("AWS::CloudFront::Function", {"FunctionCode": "a"}, {"FunctionCode": "b"}),+ ("AWS::Backup::BackupVault", {}, {"AccessPolicy": {"Version": "2012-10-17", "Statement": []}}),+ ("AWS::Location::Tracker", {"Description": "a"}, {"Description": "b"}),+ ("AWS::ElasticLoadBalancingV2::TargetGroup", {},+ {"TargetGroupAttributes": [{"Key": "lambda.multi_value_headers.enabled", "Value": "true"}]}),+])+def test_listed_types_report_other_properties_in_place(rtype, old, new):+ change = _diff_resources(_template(rtype, old), _template(rtype, new))[0]["ResourceChange"]+ assert set(_requirements(change).values()) == {"Never"}+ assert change["Replacement"] == "False"+++def test_conditional_and_in_place_properties_report_together():+ # KeySchema is conditionally create-only in the DynamoDB schema, so the+ # change stays Conditional next to an in-place AttributeDefinitions edit.+ rtype = "AWS::DynamoDB::Table"+ attributes = [{"AttributeName": "pk", "AttributeType": "S"}]+ keys = [{"AttributeName": "pk", "KeyType": "HASH"}]+ old = _template(rtype, {"AttributeDefinitions": attributes, "KeySchema": keys})+ new = _template(rtype, {+ "AttributeDefinitions": [*attributes, {"AttributeName": "sk", "AttributeType": "S"}],+ "KeySchema": [*keys, {"AttributeName": "sk", "KeyType": "RANGE"}],+ })+ change = _diff_resources(old, new)[0]["ResourceChange"]+ assert change["Replacement"] == "Conditional"+ assert _requirements(change) == {"AttributeDefinitions": "Never", "KeySchema": "Conditionally"}+++def test_unknown_resource_type_keeps_conditional():+ change = _diff_resources(_template("Custom::Example", {"Value": "a"}),+ _template("Custom::Example", {"Value": "b"}))[0]["ResourceChange"]+ assert change["Replacement"] == "Conditional"+++def test_policy_only_edit_does_not_replace():+ old = _template("AWS::SSM::Parameter", {"Type": "String", "Value": "value"})+ new = _template("AWS::SSM::Parameter", {"Type": "String", "Value": "value"})+ new["Resources"]["R"]["UpdateReplacePolicy"] = "Retain"+ change = _diff_resources(old, new)[0]["ResourceChange"]+ assert change["Replacement"] == "False"+ assert change["Scope"] == ["UpdateReplacePolicy"]+++def test_reporting_tables_are_consistent():+ assert _REPLACING_PROPERTIES.keys() <= _RESOURCE_HANDLERS.keys()+ # A conditional row for an unlisted type would never be read.+ assert _CONDITIONALLY_REPLACING_PROPERTIES.keys() <= _REPLACING_PROPERTIES.keys()+ for rtype, names in _CONDITIONALLY_REPLACING_PROPERTIES.items():+ assert names+ assert not set(names).intersection(_REPLACING_PROPERTIES[rtype])++[email protected]("rename,value", [(True, "a"), (False, "b"), (True, "b")])+def test_ssm_change_set_reports_each_property(cfn, stack, rename, value):+ pname = f"/repl/{_uuid_mod.uuid4().hex[:10]}"+ old = _template("AWS::SSM::Parameter", {"Name": pname, "Type": "String", "Value": "a"})+ new = _template("AWS::SSM::Parameter", {"Name": pname + "-new" if rename else pname, "Type": "String", "Value": value})+ change = _change(cfn, stack(old), new)+ expected = {}+ if rename:+ expected["Name"] = "Always"+ if value != "a":+ expected["Value"] = "Never"+ assert _requirements(change) == expected+ assert change["Replacement"] == ("True" if rename else "False")++[email protected]("prop,value,recreation,replacement", [+ ("TopicName", None, "Always", "True"),+ ("DisplayName", "review", "Never", "False"),+])+def test_sns_change_set_reports_name_and_display_name(cfn, stack, prop, value,+ recreation, replacement):+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"+ old = _template("AWS::SNS::Topic", {"TopicName": name})+ new = _template("AWS::SNS::Topic", {"TopicName": name, prop: value or name + "-new"})+ change = _change(cfn, stack(old), new)+ assert _requirements(change) == {prop: recreation}+ assert change["Replacement"] == replacement+++def test_cognito_change_set_reports_mfa_configuration_in_place(cfn, stack):+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"+ old = _template("AWS::Cognito::UserPool", {"UserPoolName": name})+ new = _template("AWS::Cognito::UserPool", {"UserPoolName": name, "MfaConfiguration": "OFF"})+ change = _change(cfn, stack(old), new)+ assert _requirements(change) == {"MfaConfiguration": "Never"}+ assert change["Replacement"] == "False"+++_PASS = json.dumps({"StartAt": "A", "States": {"A": {"Type": "Pass", "End": True}}})+_ROLE = "arn:aws:iam::000000000000:role/review"++[email protected]("rtype,props,prop,value", [+ ("AWS::DynamoDB::Table", {"BillingMode": "PAY_PER_REQUEST",+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}]},+ "Tags", [{"Key": "review", "Value": "1"}]),+ ("AWS::Lambda::Function", {"Runtime": "python3.13", "Handler": "index.handler", "Timeout": 30,+ "Role": _ROLE, "Code": {"ZipFile": "def handler(event, context):\n return {}\n"}},+ "Timeout", 45),+ ("AWS::StepFunctions::StateMachine", {"RoleArn": _ROLE, "DefinitionString": _PASS},+ "DefinitionString", _PASS.replace('"A"', '"B"')),+], ids=["dynamodb-tags", "lambda-timeout", "sfn-definition"])+def test_change_set_reports_other_properties_in_place(cfn, stack, rtype, props, prop, value):+ old = _template(rtype, props)+ new = _template(rtype, {**props, prop: value})+ change = _change(cfn, stack(old), new)+ assert _requirements(change) == {prop: "Never"}+ assert change["Replacement"] == "False"+++def test_sqs_change_set_reports_the_issue_reproduction(cfn, stack):+ name = f"repl-{_uuid_mod.uuid4().hex[:10]}"+ old = _template("AWS::SQS::Queue", {"QueueName": name})+ new = _template("AWS::SQS::Queue", {"QueueName": name + "-new", "DelaySeconds": 5})+ change = _change(cfn, stack(old), new)+ assert change["Replacement"] == "True"+ assert _requirements(change) == {"QueueName": "Always", "DelaySeconds": "Never"}diff --git a/tests/test_cfn_replacement_reporting.py b/tests/test_cfn_replacement_reporting.pydeleted file mode 100644index a82b1690..00000000--- a/tests/test_cfn_replacement_reporting.py+++ /dev/null@@ -1,230 +0,0 @@-"""Replacement reporting checked against AWS change sets and resource schemas."""--import json-import uuid--import pytest--from ministack.services.cloudformation.provisioners import (- _CONDITIONALLY_REPLACING_PROPERTIES,- _REPLACING_PROPERTIES,- _RESOURCE_HANDLERS,-)-from ministack.services.cloudformation.stacks import _diff_resources---def _template(resource_type, properties):- return {"Resources": {"R": {"Type": resource_type, "Properties": properties}}}---def stack(cfn):- names = []-- def create(template):- name = f"repl-{uuid.uuid4().hex[:10]}"- cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))- names.append(name)- cfn.get_waiter("stack_create_complete").wait(- StackName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})- return name-- yield create- for name in names:- cfn.delete_stack(StackName=name)- cfn.get_waiter("stack_delete_complete").wait(- StackName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})---def _change(cfn, name, template):- cfn.create_change_set(StackName=name, ChangeSetName="cs", ChangeSetType="UPDATE",- TemplateBody=json.dumps(template))- cfn.get_waiter("change_set_create_complete").wait(- StackName=name, ChangeSetName="cs", WaiterConfig={"Delay": 1, "MaxAttempts": 30})- return cfn.describe_change_set(StackName=name, ChangeSetName="cs")["Changes"][0]["ResourceChange"]---def _requirements(change):- return {d["Target"]["Name"]: d["Target"]["RequiresRecreation"]- for d in change.get("Details", []) if d["Target"].get("Name")}---# These are independent AWS observations, including negative cases where-# service API immutability must not be turned into an Always result.[email protected]("rtype,old,new,expected", [- ("AWS::Cognito::UserPool", {"UserPoolName": "before"}, {"UserPoolName": "after"}, "Never"),- ("AWS::Cognito::UserPool", {}, {"Schema": [{"Name": "review", "AttributeDataType": "String"}]}, "Never"),- ("AWS::IoT::ThingType",- {"ThingTypeProperties": {"Mqtt5Configuration": {"PropagatingAttributes": []}}},- {"ThingTypeProperties": {"Mqtt5Configuration": {"PropagatingAttributes": [{"UserPropertyKey": "k", "ThingAttribute": "v"}]}}}, "Never"),- ("AWS::DynamoDB::Table",- {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]},- {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "N"}]}, "Never"),- ("AWS::DynamoDB::Table", {}, {"ImportSourceSpecification": {"InputFormat": "CSV"}}, "Always"),- ("AWS::DynamoDB::Table", {"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}]},- {"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}]},- "Conditionally"),- ("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}},- {"DurableConfig": {"ExecutionTimeout": 120}}, "Conditionally"),- ("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}}, {}, "Conditionally"),- ("AWS::SQS::Queue", {"QueueName": "before"}, {"QueueName": "after"}, "Always"),- ("AWS::SQS::Queue", {"FifoQueue": False}, {"FifoQueue": True}, "Always"),- ("AWS::SQS::Queue", {"DelaySeconds": 0}, {"DelaySeconds": 5}, "Never"),- ("AWS::SSM::Parameter", {"Value": "before"}, {"Value": "after"}, "Never"),- ("AWS::SNS::Topic", {"FifoTopic": False}, {"FifoTopic": True}, "Always"),- # Fixed at CreateUserPool by the service API, yet reported in place.- ("AWS::Cognito::UserPool", {}, {"AliasAttributes": ["email"]}, "Never"),- ("AWS::Lambda::LayerVersion", {"Content": {"S3Bucket": "layers", "S3Key": "a.zip"}},- {"Content": {"S3Bucket": "layers", "S3Key": "b.zip"}}, "Always"),-])-def test_property_reporting(rtype, old, new, expected):- change = _diff_resources(_template(rtype, old), _template(rtype, new))[0]["ResourceChange"]- assert set(_requirements(change).values()) == {expected}- assert change["Replacement"] == {"Never": "False", "Always": "True", "Conditionally": "Conditional"}[expected]---def test_adding_a_dynamodb_index_does_not_report_replacement():- old = {"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]}- new = {- "AttributeDefinitions": [*old["AttributeDefinitions"], {"AttributeName": "gpk", "AttributeType": "S"}],- "GlobalSecondaryIndexes": [{"IndexName": "review", "KeySchema": [{"AttributeName": "gpk", "KeyType": "HASH"}],- "Projection": {"ProjectionType": "KEYS_ONLY"}}],- }- change = _diff_resources(_template("AWS::DynamoDB::Table", old), _template("AWS::DynamoDB::Table", new))[0]["ResourceChange"]- assert change["Replacement"] == "False"- assert _requirements(change) == {"AttributeDefinitions": "Never", "GlobalSecondaryIndexes": "Never"}---# Measured AWS change sets: a listed type reports every property its schema-# does not mark create-only or conditionally create-only as Never.[email protected]("rtype,old,new", [- ("AWS::DynamoDB::Table", {}, {"TimeToLiveSpecification": {"AttributeName": "ttl", "Enabled": True}}),- ("AWS::DynamoDB::Table", {}, {"Tags": [{"Key": "review", "Value": "1"}]}),- ("AWS::Lambda::Function", {"Timeout": 30}, {"Timeout": 45}),- ("AWS::StepFunctions::StateMachine", {"DefinitionString": "a"}, {"DefinitionString": "b"}),- ("AWS::Cognito::UserPoolGroup", {"Description": "a"}, {"Description": "b"}),- ("AWS::Cognito::UserPoolResourceServer", {"Name": "a"}, {"Name": "b"}),- ("AWS::IoT::ThingGroup", {"ThingGroupProperties": {"ThingGroupDescription": "a"}},- {"ThingGroupProperties": {"ThingGroupDescription": "b"}}),- ("AWS::IoT::ProvisioningTemplate", {"Description": "a"}, {"Description": "b"}),- ("AWS::IAM::InstanceProfile", {"Roles": ["a"]}, {"Roles": ["b"]}),- ("AWS::CloudFront::Function", {"FunctionCode": "a"}, {"FunctionCode": "b"}),- ("AWS::Backup::BackupVault", {}, {"AccessPolicy": {"Version": "2012-10-17", "Statement": []}}),- ("AWS::Location::Tracker", {"Description": "a"}, {"Description": "b"}),- ("AWS::ElasticLoadBalancingV2::TargetGroup", {},- {"TargetGroupAttributes": [{"Key": "lambda.multi_value_headers.enabled", "Value": "true"}]}),-])-def test_listed_types_report_other_properties_in_place(rtype, old, new):- change = _diff_resources(_template(rtype, old), _template(rtype, new))[0]["ResourceChange"]- assert set(_requirements(change).values()) == {"Never"}- assert change["Replacement"] == "False"---def test_conditional_and_in_place_properties_report_together():- # KeySchema is conditionally create-only in the DynamoDB schema, so the- # change stays Conditional next to an in-place AttributeDefinitions edit.- rtype = "AWS::DynamoDB::Table"- attributes = [{"AttributeName": "pk", "AttributeType": "S"}]- keys = [{"AttributeName": "pk", "KeyType": "HASH"}]- old = _template(rtype, {"AttributeDefinitions": attributes, "KeySchema": keys})- new = _template(rtype, {- "AttributeDefinitions": [*attributes, {"AttributeName": "sk", "AttributeType": "S"}],- "KeySchema": [*keys, {"AttributeName": "sk", "KeyType": "RANGE"}],- })- change = _diff_resources(old, new)[0]["ResourceChange"]- assert change["Replacement"] == "Conditional"- assert _requirements(change) == {"AttributeDefinitions": "Never", "KeySchema": "Conditionally"}---def test_unknown_resource_type_keeps_conditional():- change = _diff_resources(_template("Custom::Example", {"Value": "a"}),- _template("Custom::Example", {"Value": "b"}))[0]["ResourceChange"]- assert change["Replacement"] == "Conditional"---def test_policy_only_edit_does_not_replace():- old = _template("AWS::SSM::Parameter", {"Type": "String", "Value": "value"})- new = _template("AWS::SSM::Parameter", {"Type": "String", "Value": "value"})- new["Resources"]["R"]["UpdateReplacePolicy"] = "Retain"- change = _diff_resources(old, new)[0]["ResourceChange"]- assert change["Replacement"] == "False"- assert change["Scope"] == ["UpdateReplacePolicy"]---def test_reporting_tables_are_consistent():- assert _REPLACING_PROPERTIES.keys() <= _RESOURCE_HANDLERS.keys()- # A conditional row for an unlisted type would never be read.- assert _CONDITIONALLY_REPLACING_PROPERTIES.keys() <= _REPLACING_PROPERTIES.keys()- for rtype, names in _CONDITIONALLY_REPLACING_PROPERTIES.items():- assert names- assert not set(names).intersection(_REPLACING_PROPERTIES[rtype])--[email protected]("rename,value", [(True, "a"), (False, "b"), (True, "b")])-def test_ssm_change_set_reports_each_property(cfn, stack, rename, value):- pname = f"/repl/{uuid.uuid4().hex[:10]}"- old = _template("AWS::SSM::Parameter", {"Name": pname, "Type": "String", "Value": "a"})- new = _template("AWS::SSM::Parameter", {"Name": pname + "-new" if rename else pname, "Type": "String", "Value": value})- change = _change(cfn, stack(old), new)- expected = {}- if rename:- expected["Name"] = "Always"- if value != "a":- expected["Value"] = "Never"- assert _requirements(change) == expected- assert change["Replacement"] == ("True" if rename else "False")--[email protected]("prop,value,recreation,replacement", [- ("TopicName", None, "Always", "True"),- ("DisplayName", "review", "Never", "False"),-])-def test_sns_change_set_reports_name_and_display_name(cfn, stack, prop, value,- recreation, replacement):- name = f"repl-{uuid.uuid4().hex[:10]}"- old = _template("AWS::SNS::Topic", {"TopicName": name})- new = _template("AWS::SNS::Topic", {"TopicName": name, prop: value or name + "-new"})- change = _change(cfn, stack(old), new)- assert _requirements(change) == {prop: recreation}- assert change["Replacement"] == replacement---def test_cognito_change_set_reports_mfa_configuration_in_place(cfn, stack):- name = f"repl-{uuid.uuid4().hex[:10]}"- old = _template("AWS::Cognito::UserPool", {"UserPoolName": name})- new = _template("AWS::Cognito::UserPool", {"UserPoolName": name, "MfaConfiguration": "OFF"})- change = _change(cfn, stack(old), new)- assert _requirements(change) == {"MfaConfiguration": "Never"}- assert change["Replacement"] == "False"---_PASS = json.dumps({"StartAt": "A", "States": {"A": {"Type": "Pass", "End": True}}})-_ROLE = "arn:aws:iam::000000000000:role/review"--[email protected]("rtype,props,prop,value", [- ("AWS::DynamoDB::Table", {"BillingMode": "PAY_PER_REQUEST",- "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],- "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}]},- "Tags", [{"Key": "review", "Value": "1"}]),- ("AWS::Lambda::Function", {"Runtime": "python3.13", "Handler": "index.handler", "Timeout": 30,- "Role": _ROLE, "Code": {"ZipFile": "def handler(event, context):\n return {}\n"}},- "Timeout", 45),- ("AWS::StepFunctions::StateMachine", {"RoleArn": _ROLE, "DefinitionString": _PASS},- "DefinitionString", _PASS.replace('"A"', '"B"')),-], ids=["dynamodb-tags", "lambda-timeout", "sfn-definition"])-def test_change_set_reports_other_properties_in_place(cfn, stack, rtype, props, prop, value):- old = _template(rtype, props)- new = _template(rtype, {**props, prop: value})- change = _change(cfn, stack(old), new)- assert _requirements(change) == {prop: "Never"}- assert change["Replacement"] == "False"---def test_sqs_change_set_reports_the_issue_reproduction(cfn, stack):- name = f"repl-{uuid.uuid4().hex[:10]}"- old = _template("AWS::SQS::Queue", {"QueueName": name})- new = _template("AWS::SQS::Queue", {"QueueName": name + "-new", "DelaySeconds": 5})- change = _change(cfn, stack(old), new)- assert change["Replacement"] == "True"- assert _requirements(change) == {"QueueName": "Always", "DelaySeconds": "Never"}diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 9101bd7b..fe9711d0 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1274,6 +1274,7 @@ def test_ecs_service_td_update_replaces_tasks(ecs):@requires_ecs_docker[email protected]_plane@pytest.mark.serialdef test_ecs_service_circuit_breaker_rolls_back_crashing_revision(ecs):"""A real container exit fails the new deployment and restores the old one.@@ -1637,16 +1638,6 @@ def test_ecs_cfn_service_deployment_circuit_breaker_create_and_update(ecs, cfn):taskDefinition=second_family)["taskDefinition"]["taskDefinitionArn"]assert service["taskDefinition"] == second_arn- assert service["deploymentConfiguration"] == {- "deploymentCircuitBreaker": {- "enable": True,- "rollback": False,- "resetOnHealthyTask": True,- "thresholdConfiguration": {- "type": "UNBOUNDED_PERCENT", "value": 25,- },- },- }cfn.delete_stack(StackName=stack_name)diff --git a/tests/test_iot_jobs.py b/tests/test_iot_jobs_data.pysimilarity index 100%rename from tests/test_iot_jobs.pyrename to tests/test_iot_jobs_data.pydiff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex f164a90c..5785d308 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -12,6 +12,7 @@ import urllib.error as _urlerrimport urllib.request as _urlreqimport uuid as _uuid_modimport zipfile+from http.server import BaseHTTPRequestHandler, HTTPServerfrom unittest.mock import Mock, patchfrom urllib.parse import urlparse@@ -13630,3 +13631,181 @@ def test_function_changes_invalidate_provided_workers(monkeypatch, isolated_poolresult = lambda_svc._delete_function(name, {})assert result[0] in (200, 204)assert not lambda_runtime._workers+++class _ProxyHandler(BaseHTTPRequestHandler):+ received: list[dict] = []+ response: tuple[int, bytes, dict] = (200, b'{"ok":true}', {"Content-Type": "application/json"})+ sleep_seconds: float = 0.0++ def do_POST(self): # noqa: N802+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length) if length else b""+ type(self).received.append({+ "path": self.path,+ "headers": {k: v for k, v in self.headers.items()},+ "body": body,+ })+ if type(self).sleep_seconds:+ time.sleep(type(self).sleep_seconds)+ status, payload, headers = type(self).response+ self.send_response(status)+ for k, v in headers.items():+ self.send_header(k, v)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, *_args, **_kwargs):+ pass+++def proxy_server():+ server = HTTPServer(("127.0.0.1", 0), _ProxyHandler)+ port = server.server_address[1]+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ _ProxyHandler.received = []+ _ProxyHandler.response = (200, b'{"ok":true}', {"Content-Type": "application/json"})+ _ProxyHandler.sleep_seconds = 0.0+ try:+ yield port+ finally:+ server.shutdown()+++def _make_client():+ return boto3.client(+ "lambda",+ endpoint_url=_endpoint,+ region_name="us-east-1",+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+++def _create_proxy_function(client, name: str, url: str | None):+ env = {"Variables": {"MINISTACK_LAMBDA_PROXY_URL": url}} if url else None+ kwargs = dict(+ FunctionName=name,+ Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/x",+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event,context):\n return event\n")},+ )+ if env is not None:+ kwargs["Environment"] = env+ client.create_function(**kwargs)+++def test_proxy_invoke_forwards_event_and_returns_response(proxy_server):+ name = "proxy_echo"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")++ event = {"hello": "world", "n": 42}+ resp = client.invoke(FunctionName=name, Payload=json.dumps(event).encode())+ body = json.loads(resp["Payload"].read())++ assert body == {"ok": True}+ assert _ProxyHandler.received, "container never received the invocation"+ forwarded = _ProxyHandler.received[-1]+ assert forwarded["path"] == "/invoke"+ assert json.loads(forwarded["body"]) == event+ h = forwarded["headers"]+ assert h.get("X-Amzn-Lambda-Function-Name") == name+ assert h.get("X-Amzn-Lambda-Request-Id")+ assert h.get("X-Amzn-Lambda-Function-Arn", "").endswith(f":function:{name}")+++def test_proxy_invoke_passes_through_response_payload(proxy_server):+ name = "proxy_payload"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")+ _ProxyHandler.response = (200, b'{"statusCode":201,"body":"created"}', {"Content-Type": "application/json"})++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ body = json.loads(resp["Payload"].read())+ assert body == {"statusCode": 201, "body": "created"}+++def test_proxy_invoke_non_2xx_returns_lambda_error_shape(proxy_server):+ name = "proxy_500"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")+ _ProxyHandler.response = (500, b"boom", {"Content-Type": "text/plain"})++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ assert resp.get("FunctionError") == "Unhandled"+ body = json.loads(resp["Payload"].read())+ assert body.get("errorType") == "Runtime.HandlerError"+ assert "HTTP 500" in body.get("errorMessage", "")+++def test_proxy_invoke_unreachable_returns_lambda_error_shape():+ name = "proxy_unreachable"+ client = _make_client()+ _create_proxy_function(client, name, "http://127.0.0.1:1/invoke")++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ assert resp.get("FunctionError") == "Unhandled"+ body = json.loads(resp["Payload"].read())+ assert body.get("errorType") in ("Runtime.HandlerError", "Sandbox.Timedout")+ assert "errorMessage" in body+++def test_proxy_unset_falls_back_to_normal_executor():+ name = "proxy_unset"+ client = _make_client()+ _create_proxy_function(client, name, None)+ resp = client.invoke(FunctionName=name, Payload=b'{"a":1}')+ body = json.loads(resp["Payload"].read())+ assert body == {"a": 1}+++def test_proxy_via_apigw_aws_proxy_integration(proxy_server):+ """API Gateway HTTP API routes through to a proxy Lambda's container and returns its response."""+ import urllib.request as _urlreq+ from urllib.parse import urlparse++ name = "proxy_apigw_fn"+ lam = _make_client()+ _create_proxy_function(lam, name, f"http://127.0.0.1:{proxy_server}/invoke")++ # Container replies with a Lambda Proxy response shape, which APIGW unwraps.+ _ProxyHandler.response = (+ 200,+ b'{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\\"hi\\":\\"from-php\\"}"}',+ {"Content-Type": "application/json"},+ )++ apigw = boto3.client(+ "apigatewayv2",+ endpoint_url=_endpoint,+ region_name="us-east-1",+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+ api_id = apigw.create_api(Name=f"proxy-api-{name}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{name}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /hello", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ port = urlparse(_endpoint).port or 4566+ url = f"http://{api_id}.execute-api.localhost:{port}/$default/hello"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:{port}")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ assert json.loads(resp.read()) == {"hi": "from-php"}++ # The container should have received an APIGW v2 event JSON, not a raw HTTP request.+ forwarded = json.loads(_ProxyHandler.received[-1]["body"])+ assert forwarded.get("rawPath") == "/hello"+ assert forwarded.get("requestContext", {}).get("http", {}).get("method") == "GET"diff --git a/tests/test_lambda_proxy.py b/tests/test_lambda_proxy.pydeleted file mode 100644index d2df2d10..00000000--- a/tests/test_lambda_proxy.py+++ /dev/null@@ -1,203 +0,0 @@-"""BYO-container Lambda proxy: forward Invoke to a user-managed HTTP server.--The proxy URL is configured per-function via Environment.Variables.MINISTACK_LAMBDA_PROXY_URL,-which means tests don't need to restart the server — they create a function with-the proxy URL in its environment and invoke it.-"""-import io-import json-import os-import threading-import time-import zipfile-from http.server import BaseHTTPRequestHandler, HTTPServer--import boto3-import pytest--_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")---def _make_zip(code: str = "def handler(event,context):\n return event\n") -> bytes:- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("index.py", code)- return buf.getvalue()---class _ProxyHandler(BaseHTTPRequestHandler):- received: list[dict] = []- response: tuple[int, bytes, dict] = (200, b'{"ok":true}', {"Content-Type": "application/json"})- sleep_seconds: float = 0.0-- def do_POST(self): # noqa: N802- length = int(self.headers.get("Content-Length", "0"))- body = self.rfile.read(length) if length else b""- type(self).received.append({- "path": self.path,- "headers": {k: v for k, v in self.headers.items()},- "body": body,- })- if type(self).sleep_seconds:- time.sleep(type(self).sleep_seconds)- status, payload, headers = type(self).response- self.send_response(status)- for k, v in headers.items():- self.send_header(k, v)- self.send_header("Content-Length", str(len(payload)))- self.end_headers()- self.wfile.write(payload)-- def log_message(self, *_args, **_kwargs):- pass---def proxy_server():- server = HTTPServer(("127.0.0.1", 0), _ProxyHandler)- port = server.server_address[1]- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- _ProxyHandler.received = []- _ProxyHandler.response = (200, b'{"ok":true}', {"Content-Type": "application/json"})- _ProxyHandler.sleep_seconds = 0.0- try:- yield port- finally:- server.shutdown()---def _make_client():- return boto3.client(- "lambda",- endpoint_url=_endpoint,- region_name="us-east-1",- aws_access_key_id="test",- aws_secret_access_key="test",- )---def _create_proxy_function(client, name: str, url: str | None):- env = {"Variables": {"MINISTACK_LAMBDA_PROXY_URL": url}} if url else None- kwargs = dict(- FunctionName=name,- Runtime="python3.12",- Role="arn:aws:iam::000000000000:role/x",- Handler="index.handler",- Code={"ZipFile": _make_zip()},- )- if env is not None:- kwargs["Environment"] = env- client.create_function(**kwargs)---def test_proxy_invoke_forwards_event_and_returns_response(proxy_server):- name = "proxy_echo"- client = _make_client()- _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")-- event = {"hello": "world", "n": 42}- resp = client.invoke(FunctionName=name, Payload=json.dumps(event).encode())- body = json.loads(resp["Payload"].read())-- assert body == {"ok": True}- assert _ProxyHandler.received, "container never received the invocation"- forwarded = _ProxyHandler.received[-1]- assert forwarded["path"] == "/invoke"- assert json.loads(forwarded["body"]) == event- h = forwarded["headers"]- assert h.get("X-Amzn-Lambda-Function-Name") == name- assert h.get("X-Amzn-Lambda-Request-Id")- assert h.get("X-Amzn-Lambda-Function-Arn", "").endswith(f":function:{name}")---def test_proxy_invoke_passes_through_response_payload(proxy_server):- name = "proxy_payload"- client = _make_client()- _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")- _ProxyHandler.response = (200, b'{"statusCode":201,"body":"created"}', {"Content-Type": "application/json"})-- resp = client.invoke(FunctionName=name, Payload=b"{}")- body = json.loads(resp["Payload"].read())- assert body == {"statusCode": 201, "body": "created"}---def test_proxy_invoke_non_2xx_returns_lambda_error_shape(proxy_server):- name = "proxy_500"- client = _make_client()- _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")- _ProxyHandler.response = (500, b"boom", {"Content-Type": "text/plain"})-- resp = client.invoke(FunctionName=name, Payload=b"{}")- assert resp.get("FunctionError") == "Unhandled"- body = json.loads(resp["Payload"].read())- assert body.get("errorType") == "Runtime.HandlerError"- assert "HTTP 500" in body.get("errorMessage", "")---def test_proxy_invoke_unreachable_returns_lambda_error_shape():- name = "proxy_unreachable"- client = _make_client()- _create_proxy_function(client, name, "http://127.0.0.1:1/invoke")-- resp = client.invoke(FunctionName=name, Payload=b"{}")- assert resp.get("FunctionError") == "Unhandled"- body = json.loads(resp["Payload"].read())- assert body.get("errorType") in ("Runtime.HandlerError", "Sandbox.Timedout")- assert "errorMessage" in body---def test_proxy_unset_falls_back_to_normal_executor():- name = "proxy_unset"- client = _make_client()- _create_proxy_function(client, name, None)- resp = client.invoke(FunctionName=name, Payload=b'{"a":1}')- body = json.loads(resp["Payload"].read())- assert body == {"a": 1}---def test_proxy_via_apigw_aws_proxy_integration(proxy_server):- """API Gateway HTTP API routes through to a proxy Lambda's container and returns its response."""- import urllib.request as _urlreq- from urllib.parse import urlparse-- name = "proxy_apigw_fn"- lam = _make_client()- _create_proxy_function(lam, name, f"http://127.0.0.1:{proxy_server}/invoke")-- # Container replies with a Lambda Proxy response shape, which APIGW unwraps.- _ProxyHandler.response = (- 200,- b'{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\\"hi\\":\\"from-php\\"}"}',- {"Content-Type": "application/json"},- )-- apigw = boto3.client(- "apigatewayv2",- endpoint_url=_endpoint,- region_name="us-east-1",- aws_access_key_id="test",- aws_secret_access_key="test",- )- api_id = apigw.create_api(Name=f"proxy-api-{name}", ProtocolType="HTTP")["ApiId"]- int_id = apigw.create_integration(- ApiId=api_id,- IntegrationType="AWS_PROXY",- IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{name}",- PayloadFormatVersion="2.0",- )["IntegrationId"]- apigw.create_route(ApiId=api_id, RouteKey="GET /hello", Target=f"integrations/{int_id}")- apigw.create_stage(ApiId=api_id, StageName="$default")-- port = urlparse(_endpoint).port or 4566- url = f"http://{api_id}.execute-api.localhost:{port}/$default/hello"- req = _urlreq.Request(url, method="GET")- req.add_header("Host", f"{api_id}.execute-api.localhost:{port}")- resp = _urlreq.urlopen(req)- assert resp.status == 200- assert json.loads(resp.read()) == {"hi": "from-php"}-- # The container should have received an APIGW v2 event JSON, not a raw HTTP request.- forwarded = json.loads(_ProxyHandler.received[-1]["body"])- assert forwarded.get("rawPath") == "/hello"- assert forwarded.get("requestContext", {}).get("http", {}).get("method") == "GET"diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 0bb546d0..3cbca048 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -3632,7 +3632,7 @@ def test_s3_delete_marker_survives_restart(s3_persist, tmp_path):meta = json.load(mf)assert meta["is_delete_marker"] is Trueassert meta["version_id"] == del_headers["x-amz-version-id"]- assert meta["previous"]["etag"]+ assert meta["versions"][0]["etag"]_reload_bucket(s3mod, tmp_path, bucket)@@ -3649,7 +3649,7 @@ def test_s3_delete_marker_survives_restart(s3_persist, tmp_path):def test_s3_delete_marker_restores_previous_version_metadata(s3_persist, tmp_path):- """The version a marker displaced is rebuilt below it from `previous`, so+ """The version a marker displaced is rebuilt below it, soListObjectVersions does not lose it across a restart."""s3mod = s3_persistbucket = "qa-s3-persist-dm-prev"@@ -3754,6 +3754,29 @@ def test_s3_batch_delete_objects_persists_delete_marker(s3_persist, tmp_path):assert versions[-1]["is_delete_marker"] is True+def test_s3_noncurrent_versions_keep_bytes_tags_and_acls_across_restart(s3_persist, tmp_path):+ """Every version comes back with its own bytes, tags and ACL, including+ after a noncurrent version is purged under a delete marker."""+ s3mod = s3_persist+ bucket = "qa-s3-persist-history"+ s3mod._create_bucket(bucket, b"")+ s3mod._bucket_versioning[bucket] = "Enabled"+ vids = [s3mod._put_object(bucket, "k", body, {"x-amz-tagging": f"n={body.decode()}"})[1]["x-amz-version-id"]+ for body in (b"one", b"two", b"three")]+ s3mod._put_object_acl(bucket, "k", b"", {"x-amz-acl": "public-read"}, {"versionId": [vids[0]]})+ s3mod._delete_object(bucket, "k")+ s3mod._delete_object(bucket, "k", query_params={"versionId": vids[2]})++ _reload_bucket(s3mod, tmp_path, bucket)++ versions = s3mod._object_versions._data[("000000000000", (bucket, "k"))]+ assert [v["version_id"] for v in versions[:-1]] == vids[:2]+ assert versions[-1]["is_delete_marker"] and versions[-1]["is_latest"]+ assert [s3mod._get_object_data(bucket, "k", version_id=v) for v in vids[:2]] == [b"one", b"two"]+ assert [s3mod._object_tags[(bucket, "k", v)] for v in vids[:2]] == [{"n": "one"}, {"n": "two"}]+ assert "AllUsers" in s3mod._object_acl[(bucket, "k", vids[0])]++def test_s3_unversioned_delete_removes_persisted_files(s3_persist, tmp_path):"""Regression guard: a plain delete on an unversioned bucket still removesboth the data file and its sidecar."""diff --git a/tests/test_sns.py b/tests/test_sns.pyindex b1dee471..2018f00a 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -2230,32 +2230,6 @@ def test_sns_sms_publish_is_recorded(sns):}-def test_sns_sms_log_is_served_only_at_the_ministack_path(sns):- """There is no `/_aws/` alias — the native path is the only one.-- This asserted the opposite until review: the endpoint also answered at- LocalStack's `/_aws/sns/sms-messages`. The compatibility surface is kept- narrow on purpose — `/_ministack/ses/messages` and- `/_ministack/sqs/messages` carry no alias either — and one is added only- against a concrete migration that would otherwise be painful. None was- named, so the alias went and this guards its absence.-- The BODY still keeps LocalStack's shape, which is where the real- compatibility lives: a suite moving here changes the URL and nothing else.- """- phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"- sns.publish(PhoneNumber=phone, Message="compat path")-- body = _sms_log(phoneNumber=phone)- assert body["region"] == "us-east-1"- assert [r["Message"] for r in body["sms_messages"][phone]] == ["compat path"]-- url = f"{ENDPOINT.rstrip('/')}/_aws/sns/sms-messages"- with pytest.raises(urllib.error.HTTPError) as excinfo:- urllib.request.urlopen(url)- assert excinfo.value.code == 404--def test_sns_sms_unknown_phone_returns_an_empty_list(sns):"""A filtered read names the recipient even when nothing was sent to it."""phone = f"+1555{_uuid_mod.uuid4().int % 10_000_000:07d}"diff --git a/tests/test_transfer.py b/tests/test_transfer.pyindex d62979cf..ccf8e68d 100644--- a/tests/test_transfer.py+++ b/tests/test_transfer.py@@ -860,3 +860,126 @@ def test_sftp_port_per_server_mode(transfer, s3):obj = s3.get_object(Bucket=ctx["bucket"], Key="per-server-marker")assert obj["Body"].read() == b"ok"transfer.delete_server(ServerId=ctx["server_id"])+++def test_transfer_servers_and_users_are_region_scoped():+ import os++ import boto3+ from botocore.config import Config++ def _client(region):+ return boto3.client(+ "transfer",+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=region,+ config=Config(region_name=region, retries={"mode": "standard"}),+ )++ east = _client("us-east-1")+ west = _client("us-west-2")+ east_server = east.create_server()["ServerId"]+ west_server = west.create_server()["ServerId"]+ user_name = "same-name-regional-user"++ try:+ east.create_user(+ ServerId=east_server,+ UserName=user_name,+ Role="arn:aws:iam::000000000000:role/transfer-role",+ )+ west.create_user(+ ServerId=west_server,+ UserName=user_name,+ Role="arn:aws:iam::000000000000:role/transfer-role",+ )++ east_ids = {server["ServerId"] for server in east.list_servers()["Servers"]}+ west_ids = {server["ServerId"] for server in west.list_servers()["Servers"]}+ assert east_server in east_ids+ assert east_server not in west_ids+ assert west_server in west_ids+ assert west_server not in east_ids+ assert east.list_users(ServerId=east_server)["Users"][0]["UserName"] == user_name+ assert west.list_users(ServerId=west_server)["Users"][0]["UserName"] == user_name+ with pytest.raises(ClientError) as exc:+ west.describe_server(ServerId=east_server)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ east.delete_server(ServerId=east_server)+ west.delete_server(ServerId=west_server)+++def test_transfer_legacy_state_restores_resources_to_arn_region():+ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import transfer as service++ account_id = "111111111111"+ boot_region = "us-east-1"+ resource_region = "us-west-2"+ server_id = "s-legacyregional01"+ user_name = "legacy-user"+ user_key = f"{server_id}/{user_name}"+ original_account = get_account_id()+ original_region = get_region()+ servers = AccountScopedDict()+ users = AccountScopedDict()++ set_request_account_id(account_id)+ set_request_region(boot_region)+ servers[server_id] = {+ "ServerId": server_id,+ "Arn": f"arn:aws:transfer:{resource_region}:{account_id}:server/{server_id}",+ "State": "ONLINE",+ }+ users[user_key] = {+ "ServerId": server_id,+ "UserName": user_name,+ "Arn": (+ f"arn:aws:transfer:{resource_region}:{account_id}:"+ f"user/{server_id}/{user_name}"+ ),+ }++ service.reset()+ try:+ service.load_persisted_state({"servers": servers, "users": users})+ assert service._servers.get_scoped(+ account_id, resource_region, server_id+ )["ServerId"] == server_id+ assert service._users.get_scoped(+ account_id, resource_region, user_key+ )["UserName"] == user_name+ assert service._servers.get_scoped(account_id, boot_region, server_id) is None+ assert service._users.get_scoped(account_id, boot_region, user_key) is None+ finally:+ service.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_transfer_reset_clears_state_across_regions():+ from ministack.core.responses import get_region, set_request_region+ from ministack.services import transfer as service++ original_region = get_region()+ service.reset()+ try:+ for region in ("us-east-1", "us-west-2"):+ set_request_region(region)+ service._servers[f"server-{region}"] = {"State": "ONLINE"}+ service._users[f"server-{region}/user"] = {"UserName": "user"}+ service.reset()+ assert not service._servers.has_any()+ assert not service._users.has_any()+ finally:+ service.reset()+ set_request_region(original_region)diff --git a/tests/test_transfer_region_state.py b/tests/test_transfer_region_state.pydeleted file mode 100644index 44918771..00000000--- a/tests/test_transfer_region_state.py+++ /dev/null@@ -1,125 +0,0 @@-import pytest-from botocore.exceptions import ClientError---def test_transfer_servers_and_users_are_region_scoped():- import os-- import boto3- from botocore.config import Config-- def _client(region):- return boto3.client(- "transfer",- endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),- aws_access_key_id="test",- aws_secret_access_key="test",- region_name=region,- config=Config(region_name=region, retries={"mode": "standard"}),- )-- east = _client("us-east-1")- west = _client("us-west-2")- east_server = east.create_server()["ServerId"]- west_server = west.create_server()["ServerId"]- user_name = "same-name-regional-user"-- try:- east.create_user(- ServerId=east_server,- UserName=user_name,- Role="arn:aws:iam::000000000000:role/transfer-role",- )- west.create_user(- ServerId=west_server,- UserName=user_name,- Role="arn:aws:iam::000000000000:role/transfer-role",- )-- east_ids = {server["ServerId"] for server in east.list_servers()["Servers"]}- west_ids = {server["ServerId"] for server in west.list_servers()["Servers"]}- assert east_server in east_ids- assert east_server not in west_ids- assert west_server in west_ids- assert west_server not in east_ids- assert east.list_users(ServerId=east_server)["Users"][0]["UserName"] == user_name- assert west.list_users(ServerId=west_server)["Users"][0]["UserName"] == user_name- with pytest.raises(ClientError) as exc:- west.describe_server(ServerId=east_server)- assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"- finally:- east.delete_server(ServerId=east_server)- west.delete_server(ServerId=west_server)---def test_transfer_legacy_state_restores_resources_to_arn_region():- from ministack.core.responses import (- AccountScopedDict,- get_account_id,- get_region,- set_request_account_id,- set_request_region,- )- from ministack.services import transfer as service-- account_id = "111111111111"- boot_region = "us-east-1"- resource_region = "us-west-2"- server_id = "s-legacyregional01"- user_name = "legacy-user"- user_key = f"{server_id}/{user_name}"- original_account = get_account_id()- original_region = get_region()- servers = AccountScopedDict()- users = AccountScopedDict()-- set_request_account_id(account_id)- set_request_region(boot_region)- servers[server_id] = {- "ServerId": server_id,- "Arn": f"arn:aws:transfer:{resource_region}:{account_id}:server/{server_id}",- "State": "ONLINE",- }- users[user_key] = {- "ServerId": server_id,- "UserName": user_name,- "Arn": (- f"arn:aws:transfer:{resource_region}:{account_id}:"- f"user/{server_id}/{user_name}"- ),- }-- service.reset()- try:- service.load_persisted_state({"servers": servers, "users": users})- assert service._servers.get_scoped(- account_id, resource_region, server_id- )["ServerId"] == server_id- assert service._users.get_scoped(- account_id, resource_region, user_key- )["UserName"] == user_name- assert service._servers.get_scoped(account_id, boot_region, server_id) is None- assert service._users.get_scoped(account_id, boot_region, user_key) is None- finally:- service.reset()- set_request_account_id(original_account)- set_request_region(original_region)---def test_transfer_reset_clears_state_across_regions():- from ministack.core.responses import get_region, set_request_region- from ministack.services import transfer as service-- original_region = get_region()- service.reset()- try:- for region in ("us-east-1", "us-west-2"):- set_request_region(region)- service._servers[f"server-{region}"] = {"State": "ONLINE"}- service._users[f"server-{region}/user"] = {"UserName": "user"}- service.reset()- assert not service._servers.has_any()- assert not service._users.has_any()- finally:- service.reset()- set_request_region(original_region)