Skip to content

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

release v1.3.16 (#501)

Nahuel Nucera2be34c9348fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96f28b1d..b9d79b0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,30 @@ 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.3.16] — 2026-04-27
### Added
-- **`BIND_HOST` env var to configure the listen interface** — the bind interface was previously hard-coded to `0.0.0.0` (no env var, no CLI flag). Setting `BIND_HOST=127.0.0.1 ministack` now restricts MiniStack to loopback (useful on shared dev machines or when a `pip install` user wants tighter network exposure). Defaults to `0.0.0.0`, so existing setups behave identically. Distinct from `MINISTACK_HOST` (the *virtual* hostname used for S3 virtual-host / execute-api URL matching) — `BIND_HOST` is the TCP listen interface only. Docker users can keep using `docker run -p 127.0.0.1:4566:4566 …` as before; this is for the `pip install ministack` path.
+- **`BIND_HOST` env var to configure the listen interface** — `BIND_HOST=127.0.0.1 ministack` now restricts the listener to loopback for `pip install` users on shared dev machines. Defaults to `0.0.0.0`, so existing setups are unchanged. Distinct from `MINISTACK_HOST` (the virtual hostname used for S3 virtual-host / execute-api URL matching). Contributed by @mattwang44.
+- **Lambda `Code.S3ObjectVersion` honoured end-to-end** — `CreateFunction`, `UpdateFunctionCode`, `PublishLayerVersion`, and the CloudFormation `AWS::Lambda::Function` provisioner all thread the version through to S3, so Terraform `aws_lambda_function.s3_object_version` and CDK `Code.fromBucket(..., objectVersion=...)` deploy the pinned bytes instead of silently picking up the latest.
+
+### Fixed
+- **Lambda 250 MB unzipped-size limit was not enforced** — `CreateFunction` / `UpdateFunctionCode` / `PublishLayerVersion` accepted oversize zips and failed only at invocation time. All three now reject up-front with `InvalidParameterValueException`, matching AWS.
+- **S3 with `S3_PERSIST=1`: versioned object bodies capped at 10 MB and `GetObject(VersionId)` returned 500 for larger multipart uploads** — bodies now persist to disk (in-memory record drops the body, on-demand reads stream back), versioned reads return the persisted bytes, and disk writes go through atomic `tmp+rename` with mode `0o600` / dir `0o700` plus a path-traversal guard that rejects keys resolving outside `S3_DATA_DIR`.
+- **CloudFormation `AWS::Lambda::Function` never fetched S3 code** — `_lambda_create` stored `Code.S3Bucket` / `Code.S3Key` as metadata but never resolved them against the in-memory S3 service, so every CFN-deployed S3-backed Lambda had `code_zip = None` and failed to invoke. Inline `ZipFile` was unaffected; everything else broken. Provisioner now fetches the bytes via the standard Lambda S3 helper.
+- **Persisted Cognito hosted-UI / federation `_auth_codes` lost across warm-boot** — `_auth_codes` had a 5-minute TTL but was declared "ephemeral, not persisted", so any in-flight hosted-UI sign-in straddling a warm-boot was silently invalidated. Now wired into `get_state` / `restore_state` so codes survive a restart up to their normal TTL. Plain-dict choice (no `AccountScopedDict`) preserved with a corrected rationale: none of the OAuth2 endpoints carry SigV4, so wrapping in `AccountScopedDict` would be functionally equivalent. Contributed by @bognari.
+- **`PERSIST_STATE=1`: twelve mutated state dicts were silently dropped on warm-boot.** Five wired in by @bognari (`secretsmanager._resource_policies`, `kinesis._consumers`, `ecs._attributes`, `sns._platform_applications`, `sns._platform_endpoints`) — without these, `aws_secretsmanager_secret_policy`, `aws_kinesis_stream_consumer`, ECS PutAttributes, and mobile-push topology silently disappeared on restart. Plus `cloudwatch_logs._destinations` / `_metric_filters` / `_queries` (also @bognari) — log-destinations and metric filters wiped on restart. Plus the seven follow-ups for the same bug family: `sqs._queue_name_to_url` (snapshotted via `dict(asd)` instead of `copy.deepcopy`, dropping every non-current-tenant mapping), `eventbridge._event_bus_policies` / `_connections` / `_api_destinations` (every `aws_cloudwatch_event_connection` and `aws_cloudwatch_event_api_destination` lost), `ssm._parameter_history` and `_tags` (`GetParameterHistory` returned empty after warm-boot), and `lambda_svc._kinesis_positions` / `_dynamodb_stream_positions` (every restart replayed event-source-mapping streams from `StartingPosition`, a real at-least-once-delivery violation).
+- **Persisted services failed to restore on startup for autoscaling / backup / eks / scheduler / pipes** — these five services declared `restore_state` but never invoked it on import, so warm-boots came up with empty state regardless of `PERSIST_STATE=1`. Wired in. Contributed by @bognari.
+- **Eager-imported non-routable persisted services on startup** — services without an HTTP route never imported, so their `load_state` block never fired and persisted state evaporated. Eager-import now triggers restore. Contributed by @bognari.
+- **`NameError` at import on warm-boot for any persisted service whose `restore_state` referenced a forward-declared symbol** — parametrized regression test added across every persisted service to catch the import-order shape that previously hit `lambda_svc._ensure_poller`, `ecs._attributes`, and `acm._synthetic_pem`. Contributed by @bognari.
+- **ACM `GetCertificate` returned a placeholder PEM and leaked private-key bytes to disk on `RequestCertificate` issuance** — body / chain fidelity now matches real AWS shape, and the private-key disk-leak path is scrubbed. Contributed by @bognari.
+- **API Gateway v2 integration `physicalId` returned `{apiId}/{integrationId}` instead of just `{integrationId}`** — broke `Ref` resolution against `aws_apigatewayv2_integration`, so route → integration lookup failed at request time and CFN-deployed HTTP APIs returned `500 No integration configured` for every request. `Ref` now matches AWS; `handle_execute` and `_invoke_ws_lambda` defensively strip a legacy `{apiId}/` prefix so existing stacks continue to work. Contributed by @hiddengearz.
+- **API Gateway v1 `PutIntegration` dropped `contentHandling`** — the field was accepted on create but never persisted, so `CONVERT_TO_TEXT` / `CONVERT_TO_BINARY` payload translation silently no-op'd. Contributed by @bognari.
+- **SNS → SQS raw delivery did not forward message attributes** — raw subscriptions delivered the message body but stripped `MessageAttributes`, so SQS receivers never saw them. Forwarded now, plus the follow-up that adds the matching `MD5OfMessageAttributes` header so Java / Go SDK receivers (which verify the digest) match real AWS. Contributed by @arischow.
+- **Three medium / low correctness bugs.** `apigateway` and `apigateway_v1` `get_state()` returned live `AccountScopedDict` references instead of deep copies, so a concurrent write during shutdown serialisation could corrupt the persisted snapshot. `secretsmanager._delete_secret(force=True)` deleted the secret but left orphan entries in `_resource_policies` keyed by ARN — invisible to the API but accumulating in memory and surviving warm-boot. `acm._list_certificates` returned `{"NextToken": null}` unconditionally — boto3 strips it client-side, but Java / Go / raw-HTTP pagination clients that loop on `if NextToken in response` looped forever. Contributed by @bognari. Pattern extended in this release with a sweep across `ses_v2`, `apigateway` v2, and `apigateway` v1 (ten more endpoints) so every list response now omits `NextToken` when there is no next page; AppSync's GraphQL `{items, nextToken}` shape is intentionally unchanged.
+- **`/health` reported `version: dev` in the published Docker image** — `pip` is stripped from the runtime image, so the `importlib.metadata` lookup that worked under `pip install ministack` returned the fallback. Now reads from a `MINISTACK_VERSION` env var injected at image build time.
+
---
## [1.3.15] — 2026-04-26
diff --git a/README.md b/README.md
index b6d98e94..3d9484f2 100644
--- a/README.md
+++ b/README.md
@@ -343,7 +343,7 @@ subnet = ec2.create_subnet(
| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support |
| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation |
| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType` |
-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key`, or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig |
+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig |
| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |
| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | |
| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, UpdateSecretVersionStage, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 47e74501..09d250a9 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -396,7 +396,9 @@ async def handle_execute(api_id, stage, path, method, headers, body, query_param
return 404, {"Content-Type": "application/json"}, json.dumps({"message": "No route found"}).encode()
raw_target = route.get("target", "").replace("integrations/", "")
- # Target may be "{integrationId}" or "{apiId}/{integrationId}" (CFN physical ID)
+ # Target is "{integrationId}" — the current Ref / CFN physical ID.
+ # Legacy stacks created against the broken #480 provisioner (fixed in
+ # #487) wrote "{apiId}/{integrationId}"; strip the prefix for compat.
integration_id = raw_target.split("/")[-1] if "/" in raw_target else raw_target
integration = _integrations.get(api_id, {}).get(integration_id)
if not integration:
@@ -645,7 +647,7 @@ def _get_api(api_id):
def _get_apis():
- return _apigw_response({"items": list(_apis.values()), "nextToken": None})
+ return _apigw_response({"items": list(_apis.values())})
def _delete_api(api_id):
@@ -690,7 +692,7 @@ def _create_route(api_id, data):
def _get_routes(api_id):
- return _apigw_response({"items": list(_routes.get(api_id, {}).values()), "nextToken": None})
+ return _apigw_response({"items": list(_routes.get(api_id, {}).values())})
def _get_route(api_id, route_id):
@@ -743,7 +745,7 @@ def _create_integration(api_id, data):
def _get_integrations(api_id):
- return _apigw_response({"items": list(_integrations.get(api_id, {}).values()), "nextToken": None})
+ return _apigw_response({"items": list(_integrations.get(api_id, {}).values())})
def _get_integration(api_id, int_id):
@@ -793,7 +795,7 @@ def _create_stage(api_id, data):
def _get_stages(api_id):
- return _apigw_response({"items": list(_stages.get(api_id, {}).values()), "nextToken": None})
+ return _apigw_response({"items": list(_stages.get(api_id, {}).values())})
def _get_stage(api_id, stage_name):
@@ -837,7 +839,7 @@ def _create_deployment(api_id, data):
def _get_deployments(api_id):
- return _apigw_response({"items": list(_deployments.get(api_id, {}).values()), "nextToken": None})
+ return _apigw_response({"items": list(_deployments.get(api_id, {}).values())})
def _get_deployment(api_id, deployment_id):
@@ -895,7 +897,7 @@ def _create_authorizer(api_id, data):
def _get_authorizers(api_id):
- return _apigw_response({"items": list(_authorizers.get(api_id, {}).values()), "nextToken": None})
+ return _apigw_response({"items": list(_authorizers.get(api_id, {}).values())})
def _get_authorizer(api_id, auth_id):
@@ -1129,7 +1131,9 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, route: dict, stage: st
from ministack.services import lambda_svc
raw_target = route.get("target", "").replace("integrations/", "")
- # Target may be "{integrationId}" or "{apiId}/{integrationId}" (CFN physical ID)
+ # Target is "{integrationId}" — the current Ref / CFN physical ID.
+ # Legacy stacks created against the broken #480 provisioner (fixed in
+ # #487) wrote "{apiId}/{integrationId}"; strip the prefix for compat.
integration_id = raw_target.split("/")[-1] if "/" in raw_target else raw_target
integration = _integrations.get(api_id, {}).get(integration_id)
if not integration:
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index dc36a214..5fd339f1 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -1053,7 +1053,7 @@ def _get_rest_api(api_id):
def _get_rest_apis():
- return _v1_response({"item": [_rest_api_view(a) for a in _rest_apis.values()], "nextToken": None})
+ return _v1_response({"item": [_rest_api_view(a) for a in _rest_apis.values()]})
def _update_rest_api(api_id, data):
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 69759895..ef9c060e 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -399,6 +399,20 @@ def _lambda_create(logical_id, props, stack_name):
layers = props.get("Layers", [])
code = props.get("Code", {})
+ # Resolve the actual code bytes:
+ # - inline ZipFile is wrapped to a real zip archive
+ # - S3{Bucket,Key,ObjectVersion} fetches from the in-memory S3
+ # service so AWS::Lambda::Function deployments backed by S3 work
+ # end-to-end (matching real CFN). Falls back to inline if S3
+ # fetch fails.
+ code_zip = _zip_inline(code.get("ZipFile"), handler, runtime)
+ if code_zip is None and code.get("S3Bucket") and code.get("S3Key"):
+ code_zip = _lambda_svc._fetch_code_from_s3(
+ code["S3Bucket"],
+ code["S3Key"],
+ version_id=code.get("S3ObjectVersion"),
+ )
+
func = {
"config": {
"FunctionName": name,
@@ -422,9 +436,10 @@ def _lambda_create(logical_id, props, stack_name):
"TracingConfig": props.get("TracingConfig", {"Mode": "PassThrough"}),
"RevisionId": new_uuid(),
},
- "code_zip": _zip_inline(code.get("ZipFile"), handler, runtime),
+ "code_zip": code_zip,
"code_s3_bucket": code.get("S3Bucket"),
"code_s3_key": code.get("S3Key"),
+ "code_s3_object_version": code.get("S3ObjectVersion"),
"versions": {},
"next_version": 1,
"tags": {},
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 3e3258d0..cae1ee15 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -200,15 +200,19 @@ _identity_pools = AccountScopedDict()
_identity_tags = AccountScopedDict() # identity_pool_id -> {key: value}
# ---------------------------------------------------------------------------
-# In-memory state — OAuth2 hosted-UI / federation codes
+# In-memory state — OAuth2 authorization codes
# ---------------------------------------------------------------------------
-# `_auth_codes` and `_authorization_codes` are intentionally plain dicts
-# (NOT AccountScopedDict). The OAuth2 token endpoint is a public callback
-# with no AWS authentication context — it identifies the caller via the
-# random code + client_id + client_secret, not via a SigV4 access key.
-# Wrapping these in AccountScopedDict would make the callback lookup
-# happen under a default account, invisible to codes issued under any
-# other tenant. Effective tenant isolation is provided by the random
+# Both `_auth_codes` (SAML / OIDC federation codes minted by
+# `_oauth2_authorize_federation` and `_saml2_idp_response`) and
+# `_authorization_codes` (managed-login PKCE flow) are intentionally
+# plain dicts — NOT AccountScopedDict.
+#
+# The mint paths and the redeem path (`_oauth2_token`) are all public
+# OAuth2 endpoints invoked without SigV4. With no AWS access key on the
+# request, every operation runs under the default account, so
+# AccountScopedDict would scope mint AND lookup to the same default
+# account — functionally equivalent to a plain dict, no isolation
+# gained or lost. Effective tenant isolation is provided by the random
# unguessable token namespace. See
# tests/test_cognito_auth_codes_persistence.py for a regression pin.
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index ec88ac5d..bc9a9352 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -110,6 +110,9 @@ def get_state():
"replays": copy.deepcopy(_replays),
"endpoints": copy.deepcopy(_endpoints),
"partner_event_sources": copy.deepcopy(_partner_event_sources),
+ "event_bus_policies": copy.deepcopy(_event_bus_policies),
+ "connections": copy.deepcopy(_connections),
+ "api_destinations": copy.deepcopy(_api_destinations),
}
@@ -122,6 +125,9 @@ def restore_state(data):
_archives.update(data.get("archives", {}))
_replays.update(data.get("replays", {}))
_endpoints.update(data.get("endpoints", {}))
+ _event_bus_policies.update(data.get("event_bus_policies", {}))
+ _connections.update(data.get("connections", {}))
+ _api_destinations.update(data.get("api_destinations", {}))
pe = data.get("partner_event_sources")
if pe is not None:
_partner_event_sources.clear()
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 7f238431..6c347e7d 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -136,6 +136,12 @@ def get_state():
"layers": copy.deepcopy(_layers),
"esms": copy.deepcopy(_esms),
"function_urls": copy.deepcopy(_function_urls),
+ # Stream-poll offsets must persist with the ESM record they
+ # belong to — without this, every warm-boot replays from the
+ # configured StartingPosition (TRIM_HORIZON ⇒ full backlog),
+ # violating at-least-once delivery semantics.
+ "kinesis_positions": copy.deepcopy(_kinesis_positions),
+ "dynamodb_stream_positions": copy.deepcopy(_dynamodb_stream_positions),
}
@@ -162,6 +168,8 @@ def restore_state(data):
_layers.update(data.get("layers", {}))
_esms.update(data.get("esms", {}))
_function_urls.update(data.get("function_urls", {}))
+ _kinesis_positions.update(data.get("kinesis_positions", {}))
+ _dynamodb_stream_positions.update(data.get("dynamodb_stream_positions", {}))
if _esms:
_ensure_poller()
@@ -401,15 +409,21 @@ def _normalize_endpoint_url(value: str) -> str:
return f"http://{host}"
-def _fetch_code_from_s3(bucket: str, key: str) -> bytes | None:
- """Fetch Lambda code zip from the in-memory S3 service."""
+def _fetch_code_from_s3(bucket: str, key: str, version_id: str | None = None) -> bytes | None:
+ """Fetch Lambda code zip from the in-memory S3 service.
+
+ `version_id` matches AWS Lambda's `Code.S3ObjectVersion` — when set,
+ fetches that specific S3 object version instead of the latest."""
try:
from ministack.services import s3 as s3_svc
- obj = s3_svc._get_object_data(bucket, key)
+ obj = s3_svc._get_object_data(bucket, key, version_id=version_id)
if obj is not None:
return obj
except Exception as e:
- logger.warning("Failed to fetch Lambda code from s3://%s/%s: %s", bucket, key, e)
+ logger.warning(
+ "Failed to fetch Lambda code from s3://%s/%s%s: %s",
+ bucket, key, f"?versionId={version_id}" if version_id else "", e,
+ )
return None
@@ -822,7 +836,11 @@ def _create_function(data: dict):
elif "ZipFile" in code_data:
code_zip = base64.b64decode(code_data["ZipFile"])
elif "S3Bucket" in code_data and "S3Key" in code_data:
- code_zip = _fetch_code_from_s3(code_data["S3Bucket"], code_data["S3Key"])
+ code_zip = _fetch_code_from_s3(
+ code_data["S3Bucket"],
+ code_data["S3Key"],
+ version_id=code_data.get("S3ObjectVersion"),
+ )
err = _validate_unzipped_size(code_zip)
if err is not None:
@@ -1180,7 +1198,11 @@ def _update_code(name: str, data: dict):
elif "ZipFile" in data:
code_zip = base64.b64decode(data["ZipFile"])
elif "S3Bucket" in data and "S3Key" in data:
- code_zip = _fetch_code_from_s3(data["S3Bucket"], data["S3Key"])
+ code_zip = _fetch_code_from_s3(
+ data["S3Bucket"],
+ data["S3Key"],
+ version_id=data.get("S3ObjectVersion"),
+ )
if code_zip is None:
return error_response_json(
"InvalidParameterValueException",
@@ -3373,7 +3395,11 @@ def _publish_layer_version(layer_name: str, data: dict):
if "ZipFile" in content:
zip_data = base64.b64decode(content["ZipFile"])
elif "S3Bucket" in content and "S3Key" in content:
- zip_data = _fetch_code_from_s3(content["S3Bucket"], content["S3Key"])
+ zip_data = _fetch_code_from_s3(
+ content["S3Bucket"],
+ content["S3Key"],
+ version_id=content.get("S3ObjectVersion"),
+ )
err = _validate_unzipped_size(zip_data)
if err is not None:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index e0a9a587..2bf088a0 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -189,11 +189,19 @@ def _error(code: str, message: str, status: int, resource: str = "") -> tuple:
return status, {"Content-Type": "application/xml"}, _xml_body(root)
-def _get_object_data(bucket_name: str, key: str) -> bytes | None:
- """Return raw object bytes, or None if not found. Used by Lambda S3 code fetch."""
+def _get_object_data(bucket_name: str, key: str, version_id: str | None = None) -> bytes | None:
+ """Return raw object bytes, or None if not found. Used by Lambda S3 code fetch.
+
+ When `version_id` is provided, returns the bytes for that specific
+ version from `_object_versions` — matches AWS GetObject(VersionId)."""
bucket = _buckets.get(bucket_name)
if bucket is None:
return None
+ if version_id:
+ for v in _object_versions.get((bucket_name, key), []):
+ if v["version_id"] == version_id:
+ return v.get("data")
+ return None
obj = bucket["objects"].get(key)
if obj is None:
return None
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 7bc6825d..ca6273fe 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -87,7 +87,7 @@ async def handle_request(method, path, headers, body, query_params):
# GET /v2/email/suppression/addresses
if sub == "/suppression/addresses" and method == "GET":
- return json_response({"SuppressedDestinationSummaries": [], "NextToken": None})
+ return json_response({"SuppressedDestinationSummaries": []})
# POST /v2/email/outbound-emails (SendEmail)
if sub == "/outbound-emails" and method == "POST":
@@ -177,7 +177,6 @@ async def handle_request(method, path, headers, body, query_params):
{"IdentityType": v["IdentityType"], "IdentityName": k, "SendingEnabled": True}
for k, v in _identities.items()
],
- "NextToken": None,
})
# GET /v2/email/identities/{identity}
@@ -203,7 +202,7 @@ async def handle_request(method, path, headers, body, query_params):
# GET /v2/email/configuration-sets (ListConfigurationSets)
if sub == "/configuration-sets" and method == "GET":
- return json_response({"ConfigurationSets": list(_config_sets.keys()), "NextToken": None})
+ return json_response({"ConfigurationSets": list(_config_sets.keys())})
# GET/DELETE /v2/email/configuration-sets/{name}
m = re.match(r"^/configuration-sets/([^/]+)$", sub)
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 64afde71..20b152e3 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -856,6 +856,11 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,
"body": body,
"md5": hashlib.md5(body.encode()).hexdigest(),
"message_attributes": sqs_attrs,
+ # Real SQS emits MD5OfMessageAttributes alongside MD5OfBody on
+ # ReceiveMessage; the field reads from msg["md5_attrs"]. Without
+ # this, raw SNS→SQS deliveries diverge from real AWS for
+ # consumers that verify the attribute MD5 (Java/Go SDKs do).
+ "md5_attrs": _sqs._md5_msg_attrs(sqs_attrs),
"receipt_handle": None,
"sent_at": now,
"visible_at": now,
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 937b0fdf..ff3c4724 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -49,7 +49,14 @@ _queues_lock = threading.Lock()
# ── Persistence ────────────────────────────────────────────
def get_state():
- return {"queues": copy.deepcopy(_queues), "queue_name_to_url": dict(_queue_name_to_url)}
+ # Both must be deepcopy(asd): dict(asd) iterates only the current
+ # request's tenant via AccountScopedDict.__iter__, so other tenants'
+ # name→url mappings would silently disappear at shutdown
+ # serialisation. Same bug family as #492.
+ return {
+ "queues": copy.deepcopy(_queues),
+ "queue_name_to_url": copy.deepcopy(_queue_name_to_url),
+ }
def restore_state(data):
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index 9fcb2560..9f4abc5a 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -32,12 +32,18 @@ _tags = AccountScopedDict()
# ── Persistence ────────────────────────────────────────────
def get_state():
- return {"parameters": copy.deepcopy(_parameters)}
+ return {
+ "parameters": copy.deepcopy(_parameters),
+ "parameter_history": copy.deepcopy(_parameter_history),
+ "tags": copy.deepcopy(_tags),
+ }
def restore_state(data):
if data:
_parameters.update(data.get("parameters", {}))
+ _parameter_history.update(data.get("parameter_history", {}))
+ _tags.update(data.get("tags", {}))
try:
diff --git a/pyproject.toml b/pyproject.toml
index a976ef9e..0c844584 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.15"
+version = "1.3.16"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_cloudwatch_logs_persistence.py b/tests/test_cloudwatch_logs_persistence.py
index a4ef493c..e998474d 100644
--- a/tests/test_cloudwatch_logs_persistence.py
+++ b/tests/test_cloudwatch_logs_persistence.py
@@ -4,17 +4,17 @@ Regression tests for the CloudWatch Logs persistence drops.
Three module-level AccountScopedDicts are mutated by public APIs but
were missing from `get_state()` / `restore_state()`:
- H-2 cloudwatch_logs._destinations (PutDestination)
- H-2 cloudwatch_logs._metric_filters (PutMetricFilter)
- H-2 cloudwatch_logs._queries (StartQuery)
+ - cloudwatch_logs._destinations (PutDestination)
+ - cloudwatch_logs._metric_filters (PutMetricFilter)
+ - cloudwatch_logs._queries (StartQuery)
Plus a follow-on consistency bug:
- M-9 Subscription filters live inside _log_groups (persisted) but
- reference destination ARNs in _destinations (not persisted).
- After warm-boot you get split-brain: the filter on the log group
- still references a destination that no longer exists in
- _destinations.
+ - Subscription filters live inside _log_groups (persisted) but
+ reference destination ARNs in _destinations (not persisted).
+ After warm-boot you get split-brain: the filter on the log group
+ still references a destination that no longer exists in
+ _destinations.
Each test exercises the FULL warm-boot path:
1. populate the in-memory dict
@@ -64,7 +64,7 @@ def _round_trip(mod, svc_key="cloudwatch_logs"):
mod.restore_state(loaded)
-# ── H-2: _destinations ─────────────────────────────────────────────────
+# ── _destinations ──────────────────────────────────────────────────────
def test_destinations_survive_warm_boot():
mod = _module()
@@ -88,7 +88,7 @@ def test_destinations_survive_warm_boot():
mod.reset()
-# ── H-2: _metric_filters ──────────────────────────────────────────────
+# ── _metric_filters ────────────────────────────────────────────────────
def test_metric_filters_survive_warm_boot():
mod = _module()
@@ -125,7 +125,7 @@ def test_metric_filters_survive_warm_boot():
mod.reset()
-# ── H-2: _queries ─────────────────────────────────────────────────────
+# ── _queries ───────────────────────────────────────────────────────────
def test_queries_survive_warm_boot():
mod = _module()
@@ -148,7 +148,7 @@ def test_queries_survive_warm_boot():
mod.reset()
-# ── M-9: subscription-filter ↔ destination consistency ────────────────
+# ── subscription-filter ↔ destination consistency ──────────────────────
def test_subscription_filter_destination_resolvable_after_warm_boot():
"""A subscription filter on a log group references a destination ARN.
diff --git a/tests/test_misc_medium_low_fixes.py b/tests/test_misc_medium_low_fixes.py
index d62eac40..637a9332 100644
--- a/tests/test_misc_medium_low_fixes.py
+++ b/tests/test_misc_medium_low_fixes.py
@@ -1,24 +1,24 @@
"""
-Regression tests for the §7.4 / §7.5 omnibus (MINISTACK_GAP_PLAN.md):
+Regression tests for three medium/low correctness bugs:
- M-1 apigateway + apigateway_v1 get_state() returned live
- AccountScopedDict references rather than deep copies. A
- concurrent write during shutdown serialisation could corrupt
- the persisted snapshot.
+ - apigateway + apigateway_v1 get_state() returned live
+ AccountScopedDict references rather than deep copies. A
+ concurrent write during shutdown serialisation could corrupt
+ the persisted snapshot.
- M-2 secretsmanager._delete_secret(force=True) deleted the secret
- record but left orphan entries in `_resource_policies` (keyed
- by ARN) — invisible to the API but accumulating in memory and
- surviving warm-boot via the persistence path.
+ - secretsmanager._delete_secret(force=True) deleted the secret
+ record but left orphan entries in `_resource_policies` (keyed
+ by ARN) — invisible to the API but accumulating in memory and
+ surviving warm-boot via the persistence path.
- L-2 acm._list_certificates returned `{"NextToken": null}`
- unconditionally. Real AWS omits the key when there is no next
- page; SDK consumers that paginate via
- `if "NextToken" in response` will loop forever.
+ - acm._list_certificates returned `{"NextToken": null}`
+ unconditionally. Real AWS omits the key when there is no next
+ page; SDK consumers that paginate via
+ `if "NextToken" in response` will loop forever.
Each test bypasses boto3 to inspect a layer it would otherwise hide:
-in-process module state (M-1, M-2) or the wire-level JSON before
-client-side null-stripping (L-2).
+in-process module state for the first two, or the wire-level JSON
+before client-side null-stripping for the NextToken case.
"""
import importlib
import json
@@ -37,7 +37,7 @@ def _module(name):
return importlib.import_module(f"ministack.services.{name}")
-# ── M-1: apigateway / apigateway_v1 get_state must deep-copy ──────────
+# ── apigateway / apigateway_v1 get_state must deep-copy ───────────────
@pytest.mark.parametrize("mod_name", ["apigateway", "apigateway_v1"])
def test_apigateway_get_state_returns_independent_copy(mod_name):
@@ -75,7 +75,7 @@ def test_apigateway_get_state_returns_independent_copy(mod_name):
mod.reset()
-# ── M-2: secretsmanager force-delete must clean up orphan policies ────
+# ── secretsmanager force-delete must clean up orphan policies ─────────
def test_secretsmanager_force_delete_removes_resource_policy():
"""ForceDeleteWithoutRecovery must remove not just the secret but
@@ -133,7 +133,7 @@ def _invoke_action(mod, action, params):
return resp_body.decode() if isinstance(resp_body, bytes) else resp_body
-# ── L-2: ACM ListCertificates must omit NextToken when no more pages ──
+# ── ACM ListCertificates must omit NextToken when no more pages ───────
def test_acm_list_certificates_omits_nexttoken_when_no_more_pages():
"""Returning `{"NextToken": null}` is non-standard AWS — real AWS
diff --git a/tests/test_state_dict_persistence.py b/tests/test_state_dict_persistence.py
index f8b174fd..1d18bbd1 100644
--- a/tests/test_state_dict_persistence.py
+++ b/tests/test_state_dict_persistence.py
@@ -6,14 +6,13 @@ but the dict is missing from `get_state()` and/or `restore_state()`. With
PERSIST_STATE=1, every record stored via that API silently disappears on
the next restart.
-This file covers five distinct state-dict persistence drops surfaced by
-the persistence-symmetry audit:
+This file covers five distinct state-dict persistence drops:
- H-1 secretsmanager._resource_policies
- H-3 kinesis._consumers (enhanced fan-out)
- H-4 ecs._attributes (PutAttributes / ListAttributes)
- H-5 sns._platform_applications
- H-5 sns._platform_endpoints
+ - secretsmanager._resource_policies
+ - kinesis._consumers (enhanced fan-out)
+ - ecs._attributes (PutAttributes / ListAttributes)
+ - sns._platform_applications
+ - sns._platform_endpoints
Each test populates the dict, snapshots state via the public
`get_state()` / `restore_state()` contract, simulates a restart, and
@@ -58,7 +57,7 @@ def _round_trip(mod, svc_key):
mod.restore_state(loaded)
-# ── H-1: secretsmanager._resource_policies ─────────────────────────────
+# ── secretsmanager._resource_policies ──────────────────────────────────
def test_secretsmanager_resource_policies_survive_warm_boot():
"""`PutResourcePolicy` writes to `_resource_policies`, but if that
@@ -78,7 +77,7 @@ def test_secretsmanager_resource_policies_survive_warm_boot():
mod.reset()
-# ── H-3: kinesis._consumers ────────────────────────────────────────────
+# ── kinesis._consumers ─────────────────────────────────────────────────
def test_kinesis_consumers_survive_warm_boot():
"""`RegisterStreamConsumer` writes to `_consumers`. Without
@@ -106,7 +105,7 @@ def test_kinesis_consumers_survive_warm_boot():
mod.reset()
-# ── H-4: ecs._attributes ───────────────────────────────────────────────
+# ── ecs._attributes ────────────────────────────────────────────────────
def test_ecs_attributes_survive_warm_boot():
"""`PutAttributes` writes to `_attributes`. Lost on restart without
@@ -129,7 +128,7 @@ def test_ecs_attributes_survive_warm_boot():
mod.reset()
-# ── H-5: sns._platform_applications + sns._platform_endpoints ─────────
+# ── sns._platform_applications + sns._platform_endpoints ──────────────
def test_sns_platform_applications_survive_warm_boot():
"""`CreatePlatformApplication` writes to `_platform_applications`.
@@ -233,7 +232,7 @@ def test_module_cold_import_with_typical_snapshot_does_not_log_restore_failure(
svc_key, mod_name, caplog,
):
"""Generic regression for the NameError-at-import pattern that hit
- `ecs._attributes` (this PR) and `acm._synthetic_pem` (#494).
+ `ecs._attributes` (#492) and `acm._synthetic_pem` (#494).
The bug shape: `restore_state(data)` references a module-level
symbol declared further down the file. The import-time `try: