Skip to content

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

Fix/v1.1.26 remaining fixes (#96)

Nahuel Nuceradad02157d627
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7d0c5c81..5c80fbe6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,28 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.26] — 2026-04-03
+
+### Added
+- **CloudFront service** — CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation; ETag-based concurrency control. Contributed by @Nikhiladiga
+- **ECR service** — CreateRepository, DescribeRepositories, DeleteRepository, PutImage, BatchGetImage, BatchDeleteImage, ListImages, DescribeImages, GetAuthorizationToken, lifecycle policies, repository policies, tags, layer upload flow. Contributed by @moabukar
+- **IAM DeleteServiceLinkedRole / GetServiceLinkedRoleDeletionStatus** — Contributed by @jgrumboe
+- **State persistence for 10 more services** — Lambda (config + code_zip as base64), EC2, Route53, Cognito, ECR, CloudWatch Metrics, S3 metadata, RDS (reconnects Docker containers), ECS (tasks restored as stopped), ElastiCache (reconnects Docker containers) now persist when `PERSIST_STATE=1` (20 services total)
+- **SNS/SFN pagination** — ListTopics, ListSubscriptions, ListStateMachines, ListExecutions now support NextToken/maxResults
+- **defusedxml** — S3 and Route53 XML parsing now uses `defusedxml` to protect against billion-laughs DoS
+
+### Fixed
+- **SecretsManager `BatchGetSecretValue`** — retrieve multiple secrets in one call; returns `SecretValues` and `Errors` arrays
+- **DynamoDB `WarmThroughput`** — DescribeTable now returns `WarmThroughput` field; fixes latest Terraform AWS provider compatibility. Reported by @chad-bekmezian-snap
+- **Firehose deadlock** — `_next_dest_id` no longer acquires lock (always called within `_lock` context)
+- **Redis bound to localhost** — docker-compose.yml Redis port now `127.0.0.1:6379:6379`
+- **EDGE_PORT documented** — added to README Configuration table as LocalStack alias
+
+### Tests
+- 928 tests total, all passing
+
+---
+
## [1.1.25] — 2026-04-03
### Added
diff --git a/README.md b/README.md
index 004a12e5..c6285721 100644
--- a/README.md
+++ b/README.md
@@ -21,10 +21,10 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **34 AWS services** emulated on a single port (4566)
+- **36 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
-- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
+- **Tiny footprint** — ~200MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
- **Fast startup** — under 2 seconds
- **MIT licensed** — use it, fork it, contribute to it
@@ -203,7 +203,7 @@ subnet = ec2.create_subnet(
| **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) |
| **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; `Publish=True` creates immutable numbered versions; Code via `ZipFile` or `S3Bucket`/`S3Key`; 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, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |
+| **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, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |
@@ -277,6 +277,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
+| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here |
---
@@ -409,7 +410,7 @@ ecs.stop_task(cluster="dev", task=task_arn)
| Variable | Default | Description |
|----------|---------|-------------|
-| `GATEWAY_PORT` | `4566` | Port to listen on |
+| `GATEWAY_PORT` | `4566` | Port to listen on. Also accepts `EDGE_PORT` (LocalStack compatibility alias) |
| `MINISTACK_HOST` | `localhost` | Hostname used in response URLs (SQS queues, SNS subscriptions, API Gateway endpoints, Lambda layers) |
| `MINISTACK_REGION` | `us-east-1` | AWS region reported in ARNs and service responses across all services |
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` |
@@ -516,7 +517,7 @@ Layers that ship npm packages work too — MiniStack resolves the `nodejs/node_m
│ │ Athena Firehose Route53 │ │
│ │ Cognito EC2 EMR EBS EFS │ │
│ │ ALB/ELBv2 ACM WAF v2 │ │
- │ │ CloudFormation KMS │ │
+ │ │ CloudFormation KMS ECR │ │
│ └────────────────────────────────────┘ │
│ │
│ In-Memory Storage + Optional Docker │
@@ -539,7 +540,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (887 tests across all 35 services)
+# Run the full test suite (887 tests across all 36 services)
pytest tests/ -v
```
@@ -583,6 +584,7 @@ provider "aws" {
cognitoidp = "http://localhost:4566"
dynamodb = "http://localhost:4566"
ec2 = "http://localhost:4566"
+ ecr = "http://localhost:4566"
ecs = "http://localhost:4566"
efs = "http://localhost:4566"
elasticache = "http://localhost:4566"
@@ -672,8 +674,9 @@ See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers),
| **WAF v2** | ✅ | Paid | ✅ |
| **CloudFormation** | **partial** | partial | ✅ Free |
| **KMS** | ✅ | Paid | ✅ Free |
+| **ECR** | ✅ | ✅ | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
-| Docker image size | ~150MB | ~1GB | ~1GB |
+| Docker image size | ~200MB | ~1GB | ~1GB |
| Memory at idle | ~30MB | ~500MB | ~500MB |
| Startup time | ~2s | ~15-30s | ~15-30s |
| License | MIT | BSL (restricted) | Proprietary |
diff --git a/docker-compose.yml b/docker-compose.yml
index ee335f7c..221ab611 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -33,7 +33,7 @@ services:
image: redis:7-alpine
container_name: ministack-redis
ports:
- - "6379:6379"
+ - "127.0.0.1:6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
diff --git a/ministack/app.py b/ministack/app.py
index 502df2c4..e274a9fe 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -243,6 +243,7 @@ async def app(scope, receive, send):
await _send_response(send, status, resp_headers, resp_body)
return
+ # Admin endpoints — no wildcard CORS headers (return early, before CORS block)
if path == "/_ministack/reset" and method == "POST":
_reset_all_state()
await _send_response(send, 200, {"Content-Type": "application/json"},
@@ -548,6 +549,16 @@ async def _handle_lifespan(scope, receive, send):
"eventbridge": eventbridge.get_state,
"cloudwatch_logs": cloudwatch_logs.get_state,
"kinesis": kinesis.get_state,
+ "ec2": ec2.get_state,
+ "route53": route53.get_state,
+ "cognito": cognito.get_state,
+ "ecr": ecr.get_state,
+ "cloudwatch": cloudwatch.get_state,
+ "s3": s3.get_state,
+ "lambda": lambda_svc.get_state,
+ "rds": rds.get_state,
+ "ecs": ecs.get_state,
+ "elasticache": elasticache.get_state,
})
await send({"type": "lifespan.shutdown.complete"})
return
@@ -626,6 +637,7 @@ def _reset_all_state():
(cloudformation, cloudformation.reset),
(kms, kms.reset),
(cloudfront, cloudfront.reset),
+ (ecr, ecr.reset),
]:
try:
fn()
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 0533ce76..3841aeb4 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -14,7 +14,8 @@ import random
import re
import string
from datetime import datetime, timezone
-from xml.etree.ElementTree import Element, SubElement, fromstring, tostring
+from defusedxml.ElementTree import fromstring
+from xml.etree.ElementTree import Element, SubElement, tostring
from ministack.core.responses import new_uuid
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 705a3724..fcfac644 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -10,6 +10,7 @@ Operations: PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics,
PutDashboard, GetDashboard, DeleteDashboards, ListDashboards.
"""
+import copy
import json
import os
import logging
@@ -19,6 +20,7 @@ from collections import defaultdict
from datetime import datetime, timezone
from urllib.parse import parse_qs
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import new_uuid
logger = logging.getLogger("cloudwatch")
@@ -35,6 +37,33 @@ _resource_tags: dict = {}
_dashboards: dict = {} # dashboard_name -> {DashboardName, DashboardBody, LastModified}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "metrics": copy.deepcopy(dict(_metrics)),
+ "alarms": copy.deepcopy(_alarms),
+ "composite_alarms": copy.deepcopy(_composite_alarms),
+ "dashboards": copy.deepcopy(_dashboards),
+ "resource_tags": copy.deepcopy(_resource_tags),
+ }
+
+
+def restore_state(data):
+ if data:
+ for k, v in data.get("metrics", {}).items():
+ _metrics[k].extend(v)
+ _alarms.update(data.get("alarms", {}))
+ _composite_alarms.update(data.get("composite_alarms", {}))
+ _dashboards.update(data.get("dashboards", {}))
+ _resource_tags.update(data.get("resource_tags", {}))
+
+
+_restored = load_state("cloudwatch")
+if _restored:
+ restore_state(_restored)
+
+
# ---------------------------------------------------------------------------
# Timestamp helpers
# ---------------------------------------------------------------------------
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index ec1a81d0..b6693214 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -43,6 +43,7 @@ Wire protocol:
"""
import base64
+import copy
import os
import json
import logging
@@ -53,6 +54,7 @@ import time
from datetime import datetime, timezone
from urllib.parse import parse_qs
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("cognito")
@@ -95,6 +97,30 @@ _identity_pools: dict = {}
_identity_tags: dict = {} # identity_pool_id -> {key: value}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "user_pools": copy.deepcopy(_user_pools),
+ "pool_domain_map": copy.deepcopy(_pool_domain_map),
+ "identity_pools": copy.deepcopy(_identity_pools),
+ "identity_tags": copy.deepcopy(_identity_tags),
+ }
+
+
+def restore_state(data):
+ if data:
+ _user_pools.update(data.get("user_pools", {}))
+ _pool_domain_map.update(data.get("pool_domain_map", {}))
+ _identity_pools.update(data.get("identity_pools", {}))
+ _identity_tags.update(data.get("identity_tags", {}))
+
+
+_restored = load_state("cognito")
+if _restored:
+ restore_state(_restored)
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 752e7951..9d4380d5 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -349,6 +349,11 @@ def _table_description(name):
desc["LatestStreamArn"] = f"{t['TableArn']}/stream/{now_iso()}"
if t.get("SSEDescription"):
desc["SSEDescription"] = t["SSEDescription"]
+ desc["WarmThroughput"] = t.get("WarmThroughput", {
+ "ReadUnitsPerSecond": 0,
+ "WriteUnitsPerSecond": 0,
+ "Status": "ACTIVE",
+ })
return desc
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 73610d0d..d7d4c151 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -42,6 +42,7 @@ Supports:
DeleteEgressOnlyInternetGateway
"""
+import copy
import logging
import os
import random
@@ -50,6 +51,7 @@ import time
from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import new_uuid
logger = logging.getLogger("ec2")
@@ -81,6 +83,61 @@ _vpc_peering: dict = {} # pcx_id -> peering connection record
_dhcp_options: dict = {} # dopt_id -> DHCP options record
_egress_igws: dict = {} # eigw_id -> egress-only internet gateway record
+
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "instances": copy.deepcopy(_instances),
+ "security_groups": copy.deepcopy(_security_groups),
+ "key_pairs": copy.deepcopy(_key_pairs),
+ "vpcs": copy.deepcopy(_vpcs),
+ "subnets": copy.deepcopy(_subnets),
+ "internet_gateways": copy.deepcopy(_internet_gateways),
+ "addresses": copy.deepcopy(_addresses),
+ "tags": copy.deepcopy(_tags),
+ "route_tables": copy.deepcopy(_route_tables),
+ "network_interfaces": copy.deepcopy(_network_interfaces),
+ "vpc_endpoints": copy.deepcopy(_vpc_endpoints),
+ "volumes": copy.deepcopy(_volumes),
+ "snapshots": copy.deepcopy(_snapshots),
+ "nat_gateways": copy.deepcopy(_nat_gateways),
+ "network_acls": copy.deepcopy(_network_acls),
+ "flow_logs": copy.deepcopy(_flow_logs),
+ "vpc_peering": copy.deepcopy(_vpc_peering),
+ "dhcp_options": copy.deepcopy(_dhcp_options),
+ "egress_igws": copy.deepcopy(_egress_igws),
+ }
+
+
+def restore_state(data):
+ if data:
+ _instances.update(data.get("instances", {}))
+ _security_groups.update(data.get("security_groups", {}))
+ _key_pairs.update(data.get("key_pairs", {}))
+ _vpcs.update(data.get("vpcs", {}))
+ _subnets.update(data.get("subnets", {}))
+ _internet_gateways.update(data.get("internet_gateways", {}))
+ _addresses.update(data.get("addresses", {}))
+ _tags.update(data.get("tags", {}))
+ _route_tables.update(data.get("route_tables", {}))
+ _network_interfaces.update(data.get("network_interfaces", {}))
+ _vpc_endpoints.update(data.get("vpc_endpoints", {}))
+ _volumes.update(data.get("volumes", {}))
+ _snapshots.update(data.get("snapshots", {}))
+ _nat_gateways.update(data.get("nat_gateways", {}))
+ _network_acls.update(data.get("network_acls", {}))
+ _flow_logs.update(data.get("flow_logs", {}))
+ _vpc_peering.update(data.get("vpc_peering", {}))
+ _dhcp_options.update(data.get("dhcp_options", {}))
+ _egress_igws.update(data.get("egress_igws", {}))
+
+
+_restored = load_state("ec2")
+if _restored:
+ restore_state(_restored)
+
+
# Default VPC / subnet created at import time so DescribeVpcs always returns something
_DEFAULT_VPC_ID = "vpc-00000001"
_DEFAULT_SUBNET_ID = "subnet-00000001"
diff --git a/ministack/services/ecr.py b/ministack/services/ecr.py
index 32e5498a..454c8df2 100644
--- a/ministack/services/ecr.py
+++ b/ministack/services/ecr.py
@@ -4,12 +4,14 @@ JSON-based API via X-Amz-Target (prefix: AmazonEC2ContainerRegistry_V20150921).
"""
import base64
+import copy
import hashlib
import json
import logging
import os
import time
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import error_response_json, json_response, new_uuid
logger = logging.getLogger("ecr")
@@ -23,6 +25,30 @@ _lifecycle_policies: dict = {}
_repo_policies: dict = {}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "repositories": copy.deepcopy(_repositories),
+ "images": copy.deepcopy(_images),
+ "lifecycle_policies": copy.deepcopy(_lifecycle_policies),
+ "repo_policies": copy.deepcopy(_repo_policies),
+ }
+
+
+def restore_state(data):
+ if data:
+ _repositories.update(data.get("repositories", {}))
+ _images.update(data.get("images", {}))
+ _lifecycle_policies.update(data.get("lifecycle_policies", {}))
+ _repo_policies.update(data.get("repo_policies", {}))
+
+
+_restored = load_state("ecr")
+if _restored:
+ restore_state(_restored)
+
+
def _repo_arn(name):
return f"arn:aws:ecr:{REGION}:{ACCOUNT_ID}:repository/{name}"
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 9e431054..f5a758ab 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -14,11 +14,13 @@ Supports: CreateCluster, DeleteCluster, DescribeClusters, ListClusters,
Container execution: if Docker socket is available, RunTask actually runs containers.
"""
+import copy
import json
import logging
import os
import time
+from ministack.core.persistence import load_state
from ministack.core.responses import (
error_response_json,
json_response,
@@ -43,6 +45,49 @@ _capacity_providers: dict = {}
_docker = None
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ state = {
+ "clusters": copy.deepcopy(_clusters),
+ "task_defs": copy.deepcopy(_task_defs),
+ "task_def_latest": copy.deepcopy(_task_def_latest),
+ "services": copy.deepcopy(_services),
+ "tags": copy.deepcopy(_tags),
+ "account_settings": copy.deepcopy(_account_settings),
+ "capacity_providers": copy.deepcopy(_capacity_providers),
+ }
+ # Save tasks but strip Docker container IDs
+ tasks = {}
+ for arn, task in _tasks.items():
+ t = copy.deepcopy(task)
+ t.pop("_docker_ids", None)
+ tasks[arn] = t
+ state["tasks"] = tasks
+ return state
+
+
+def restore_state(data):
+ if not data:
+ return
+ _clusters.update(data.get("clusters", {}))
+ _task_defs.update(data.get("task_defs", {}))
+ _task_def_latest.update(data.get("task_def_latest", {}))
+ _services.update(data.get("services", {}))
+ _tags.update(data.get("tags", {}))
+ _account_settings.update(data.get("account_settings", {}))
+ _capacity_providers.update(data.get("capacity_providers", {}))
+ for arn, task in data.get("tasks", {}).items():
+ task["_docker_ids"] = []
+ task["lastStatus"] = "STOPPED"
+ _tasks[arn] = task
+
+
+_restored = load_state("ecs")
+if _restored:
+ restore_state(_restored)
+
+
def _get_docker():
global _docker
if _docker is None:
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 7a9e9e8f..f238a0d4 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -20,11 +20,13 @@ When Docker is available, CreateCacheCluster spins up a real Redis/Memcached con
Otherwise returns localhost:6379 (assumes Redis sidecar in docker-compose).
"""
+import copy
import logging
import os
import time
from urllib.parse import parse_qs
+from ministack.core.persistence import load_state
from ministack.core.responses import new_uuid
logger = logging.getLogger("elasticache")
@@ -50,6 +52,63 @@ _port_counter = [BASE_PORT]
_docker = None
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ state = {
+ "replication_groups": copy.deepcopy(_replication_groups),
+ "subnet_groups": copy.deepcopy(_subnet_groups),
+ "param_groups": copy.deepcopy(_param_groups),
+ "param_group_params": copy.deepcopy(_param_group_params),
+ "tags": copy.deepcopy(_tags),
+ "snapshots": copy.deepcopy(_snapshots),
+ "users": copy.deepcopy(_users),
+ "user_groups": copy.deepcopy(_user_groups),
+ "port_counter": _port_counter[0],
+ }
+ clusters = {}
+ for name, cl in _clusters.items():
+ c = copy.deepcopy(cl)
+ c.pop("_docker_container_id", None)
+ clusters[name] = c
+ state["clusters"] = clusters
+ return state
+
+
+def restore_state(data):
+ if not data:
+ return
+ _replication_groups.update(data.get("replication_groups", {}))
+ _subnet_groups.update(data.get("subnet_groups", {}))
+ _param_groups.update(data.get("param_groups", {}))
+ _param_group_params.update(data.get("param_group_params", {}))
+ _tags.update(data.get("tags", {}))
+ _snapshots.update(data.get("snapshots", {}))
+ _users.update(data.get("users", {}))
+ _user_groups.update(data.get("user_groups", {}))
+ if "port_counter" in data:
+ _port_counter[0] = data["port_counter"]
+ docker_client = _get_docker()
+ for name, cl in data.get("clusters", {}).items():
+ cl["_docker_container_id"] = None
+ if docker_client:
+ try:
+ c = docker_client.containers.get(f"ministack-ec-{name}")
+ if c.status == "running":
+ cl["_docker_container_id"] = c.id
+ cl["CacheClusterStatus"] = "available"
+ else:
+ cl["CacheClusterStatus"] = "stopped"
+ except Exception:
+ cl["CacheClusterStatus"] = "stopped"
+ _clusters[name] = cl
+
+
+_restored = load_state("elasticache")
+if _restored:
+ restore_state(_restored)
+
+
def _get_docker():
global _docker
if _docker is None:
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index 34893732..577bb955 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -55,6 +55,7 @@ def _stream_arn(name: str) -> str:
def _next_dest_id() -> str:
+ """Must be called while holding _lock."""
global _dest_counter
_dest_counter += 1
return f"destinationId-{_dest_counter:012d}"
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 6b75c85c..ae0f06aa 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -42,6 +42,7 @@ from datetime import datetime, timezone
from typing import Any
from urllib.parse import unquote
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import error_response_json, json_response, new_uuid
from ministack.core.lambda_runtime import get_or_create_worker, invalidate_worker
@@ -66,6 +67,47 @@ _function_urls: dict = {} # function_name -> FunctionUrlConfig dict
_poller_started = False
_poller_lock = threading.Lock()
+
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ """Return JSON-serializable state. code_zip bytes are base64-encoded."""
+ funcs = {}
+ for name, func in _functions.items():
+ f = copy.deepcopy(func)
+ if f.get("code_zip") and isinstance(f["code_zip"], bytes):
+ f["code_zip"] = base64.b64encode(f["code_zip"]).decode()
+ for ver in f.get("versions", {}).values():
+ if ver.get("code_zip") and isinstance(ver["code_zip"], bytes):
+ ver["code_zip"] = base64.b64encode(ver["code_zip"]).decode()
+ funcs[name] = f
+ return {
+ "functions": funcs,
+ "layers": copy.deepcopy(_layers),
+ "esms": copy.deepcopy(_esms),
+ "function_urls": copy.deepcopy(_function_urls),
+ }
+
+
+def restore_state(data):
+ if data:
+ for name, func in data.get("functions", {}).items():
+ if func.get("code_zip") and isinstance(func["code_zip"], str):
+ func["code_zip"] = base64.b64decode(func["code_zip"])
+ for ver in func.get("versions", {}).values():
+ if ver.get("code_zip") and isinstance(ver["code_zip"], str):
+ ver["code_zip"] = base64.b64decode(ver["code_zip"])
+ _functions[name] = func
+ _layers.update(data.get("layers", {}))
+ _esms.update(data.get("esms", {}))
+ _function_urls.update(data.get("function_urls", {}))
+
+
+_restored = load_state("lambda")
+if _restored:
+ restore_state(_restored)
+
+
# ---------------------------------------------------------------------------
# Wrapper script executed inside the subprocess.
# All configuration is passed through env vars; event data arrives on stdin.
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index ee51bba1..c5a6eaf6 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -21,6 +21,7 @@ When Docker is available, CreateDBInstance spins up a real Postgres/MySQL contai
and returns the actual host:port as the endpoint.
"""
+import copy
import datetime
import logging
import os
@@ -28,6 +29,7 @@ import time
from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
+from ministack.core.persistence import load_state
from ministack.core.responses import new_uuid
logger = logging.getLogger("rds")
@@ -50,6 +52,63 @@ _port_counter = [BASE_PORT]
_docker = None
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ state = {
+ "instances": {},
+ "clusters": copy.deepcopy(_clusters),
+ "subnet_groups": copy.deepcopy(_subnet_groups),
+ "param_groups": copy.deepcopy(_param_groups),
+ "snapshots": copy.deepcopy(_snapshots),
+ "db_cluster_param_groups": copy.deepcopy(_db_cluster_param_groups),
+ "db_cluster_snapshots": copy.deepcopy(_db_cluster_snapshots),
+ "option_groups": copy.deepcopy(_option_groups),
+ "tags": copy.deepcopy(_tags),
+ "port_counter": _port_counter[0],
+ }
+ for name, inst in _instances.items():
+ i = copy.deepcopy(inst)
+ i.pop("_docker_container_id", None)
+ state["instances"][name] = i
+ return state
+
+
+def restore_state(data):
+ if not data:
+ return
+ _clusters.update(data.get("clusters", {}))
+ _subnet_groups.update(data.get("subnet_groups", {}))
+ _param_groups.update(data.get("param_groups", {}))
+ _snapshots.update(data.get("snapshots", {}))
+ _db_cluster_param_groups.update(data.get("db_cluster_param_groups", {}))
+ _db_cluster_snapshots.update(data.get("db_cluster_snapshots", {}))
+ _option_groups.update(data.get("option_groups", {}))
+ _tags.update(data.get("tags", {}))
+ if "port_counter" in data:
+ _port_counter[0] = data["port_counter"]
+ # Restore instances and try to reconnect Docker containers
+ docker_client = _get_docker()
+ for name, inst in data.get("instances", {}).items():
+ inst["_docker_container_id"] = None
+ if docker_client:
+ try:
+ c = docker_client.containers.get(f"ministack-rds-{name}")
+ if c.status == "running":
+ inst["_docker_container_id"] = c.id
+ inst["DBInstanceStatus"] = "available"
+ else:
+ inst["DBInstanceStatus"] = "stopped"
+ except Exception:
+ inst["DBInstanceStatus"] = "stopped"
+ _instances[name] = inst
+
+
+_restored = load_state("rds")
+if _restored:
+ restore_state(_restored)
+
+
def _get_docker():
global _docker
if _docker is None:
diff --git a/ministack/services/route53.py b/ministack/services/route53.py
index b0b9952d..a3310b21 100644
--- a/ministack/services/route53.py
+++ b/ministack/services/route53.py
@@ -18,14 +18,17 @@ Wire protocol:
Paths are under /2013-04-01/
"""
+import copy
import logging
import random
import re
import string
import threading
from datetime import datetime, timezone
-from xml.etree.ElementTree import Element, SubElement, fromstring, tostring
+from defusedxml.ElementTree import fromstring
+from xml.etree.ElementTree import Element, SubElement, tostring
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import new_uuid
logger = logging.getLogger("route53")
@@ -45,6 +48,42 @@ _hc_caller_refs: dict = {} # caller_reference -> hc_id
_lock = threading.Lock()
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ with _lock:
+ return {
+ "zones": copy.deepcopy(_zones),
+ "records": copy.deepcopy(_records),
+ "health_checks": copy.deepcopy(_health_checks),
+ "tags": {f"{k[0]}|{k[1]}": v for k, v in copy.deepcopy(_tags).items()},
+ "caller_refs": copy.deepcopy(_caller_refs),
+ "hc_caller_refs": copy.deepcopy(_hc_caller_refs),
+ "changes": copy.deepcopy(_changes),
+ }
+
+
+def restore_state(data):
+ if data:
+ with _lock:
+ _zones.update(data.get("zones", {}))
+ _records.update(data.get("records", {}))
+ _health_checks.update(data.get("health_checks", {}))
+ raw_tags = data.get("tags", {})
+ for k, v in raw_tags.items():
+ parts = k.split("|", 1)
+ if len(parts) == 2:
+ _tags[(parts[0], parts[1])] = v
+ _caller_refs.update(data.get("caller_refs", {}))
+ _hc_caller_refs.update(data.get("hc_caller_refs", {}))
+ _changes.update(data.get("changes", {}))
+
+
+_restored = load_state("route53")
+if _restored:
+ restore_state(_restored)
+
+
def reset():
global _zones, _records, _changes, _health_checks, _tags, _caller_refs, _hc_caller_refs
with _lock:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 7d044e37..a1c22469 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -23,6 +23,7 @@ Storage: In-memory (optionally backed by S3_DATA_DIR).
"""
import base64
+import copy
import datetime as _dt
import hashlib
import json
@@ -32,8 +33,10 @@ import re
import threading
import time
from urllib.parse import quote as url_quote, unquote as url_unquote, parse_qs as _parse_qs
-from xml.etree.ElementTree import Element, SubElement, tostring, fromstring
+from defusedxml.ElementTree import fromstring
+from xml.etree.ElementTree import Element, SubElement, tostring
+from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import (
md5_hash,
sha256_hash,
@@ -74,6 +77,53 @@ _object_legal_hold: dict = {}
_multipart_uploads: dict = {}
+# ── Persistence (metadata only — object bodies are NOT persisted here) ────
+
+def get_state():
+ # Persist bucket metadata without object bodies
+ buckets_meta = {}
+ for name, bkt in _buckets.items():
+ meta = {k: v for k, v in bkt.items() if k != "objects"}
+ buckets_meta[name] = meta
+ return {
+ "buckets_meta": copy.deepcopy(buckets_meta),
+ "bucket_versioning": copy.deepcopy(_bucket_versioning),
+ "bucket_notifications": copy.deepcopy(_bucket_notifications),
+ "bucket_tags": copy.deepcopy(_bucket_tags),
+ "bucket_policies": copy.deepcopy(_bucket_policies),
+ "bucket_encryption": copy.deepcopy(_bucket_encryption),
+ "bucket_lifecycle": copy.deepcopy(_bucket_lifecycle),
+ "bucket_cors": copy.deepcopy(_bucket_cors),
+ "bucket_acl": copy.deepcopy(_bucket_acl),
+ "bucket_websites": copy.deepcopy(_bucket_websites),
+ "bucket_object_lock": copy.deepcopy(_bucket_object_lock),
+ "bucket_replication": copy.deepcopy(_bucket_replication),
+ }
+
+
+def restore_state(data):
+ if data:
+ for name, meta in data.get("buckets_meta", {}).items():
+ if name not in _buckets:
+ _buckets[name] = {**meta, "objects": {}}
+ _bucket_versioning.update(data.get("bucket_versioning", {}))
+ _bucket_notifications.update(data.get("bucket_notifications", {}))
+ _bucket_tags.update(data.get("bucket_tags", {}))
+ _bucket_policies.update(data.get("bucket_policies", {}))
+ _bucket_encryption.update(data.get("bucket_encryption", {}))
+ _bucket_lifecycle.update(data.get("bucket_lifecycle", {}))
+ _bucket_cors.update(data.get("bucket_cors", {}))
+ _bucket_acl.update(data.get("bucket_acl", {}))
+ _bucket_websites.update(data.get("bucket_websites", {}))
+ _bucket_object_lock.update(data.get("bucket_object_lock", {}))
+ _bucket_replication.update(data.get("bucket_replication", {}))
+
+
+_restored = load_state("s3")
+if _restored:
+ restore_state(_restored)
+
+
DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")
PERSIST = os.environ.get("S3_PERSIST", "0") == "1"
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index aabbe8f4..e40dd96d 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -137,6 +137,7 @@ async def handle_request(method, path, headers, body, query_params):
handlers = {
"CreateSecret": _create_secret,
"GetSecretValue": _get_secret_value,
+ "BatchGetSecretValue": _batch_get_secret_value,
"ListSecrets": _list_secrets,
"DeleteSecret": _delete_secret,
"RestoreSecret": _restore_secret,
@@ -254,6 +255,30 @@ def _get_secret_value(data):
return json_response(result)
+def _batch_get_secret_value(data):
+ secret_ids = data.get("SecretIdList", [])
+ results = []
+ errors = []
+
+ targets = secret_ids if secret_ids else sorted(
+ n for n, s in _secrets.items() if not s.get("DeletedDate"))
+
+ for sid in targets:
+ resp = _get_secret_value({"SecretId": sid})
+ status, _, body = resp
+ parsed = json.loads(body) if isinstance(body, bytes) else json.loads(body)
+ if status >= 400:
+ errors.append({
+ "SecretId": sid,
+ "ErrorCode": parsed.get("__type", "UnknownError"),
+ "Message": parsed.get("message", ""),
+ })
+ else:
+ results.append(parsed)
+
+ return json_response({"SecretValues": results, "Errors": errors})
+
+
def _list_secrets(data):
max_results = min(data.get("MaxResults", 100), 100)
next_token = data.get("NextToken")
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index d225fa6d..43e8313c 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -162,11 +162,23 @@ def _delete_topic(params):
def _list_topics(params):
+ all_arns = list(_topics.keys())
+ next_token = _p(params, "NextToken")
+ start = 0
+ if next_token:
+ try:
+ start = int(next_token)
+ except ValueError:
+ start = 0
+ page = all_arns[start:start + 100]
members = "".join(
- f"<member><TopicArn>{arn}</TopicArn></member>" for arn in _topics
+ f"<member><TopicArn>{arn}</TopicArn></member>" for arn in page
)
+ next_token_xml = ""
+ if start + 100 < len(all_arns):
+ next_token_xml = f"<NextToken>{start + 100}</NextToken>"
return _xml(200, "ListTopicsResponse",
- f"<ListTopicsResult><Topics>{members}</Topics></ListTopicsResult>")
+ f"<ListTopicsResult><Topics>{members}</Topics>{next_token_xml}</ListTopicsResult>")
def _get_topic_attributes(params):
@@ -297,20 +309,34 @@ def _unsubscribe(params):
def _list_subscriptions(params):
- members = ""
+ all_subs = []
for topic in _topics.values():
for sub in topic["subscriptions"]:
- members += (
- "<member>"
- f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"
- f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"
- f"<TopicArn>{sub['topic_arn']}</TopicArn>"
- f"<Protocol>{sub['protocol']}</Protocol>"
- f"<Endpoint>{sub['endpoint']}</Endpoint>"
- "</member>"
- )
+ all_subs.append(sub)
+ next_token = _p(params, "NextToken")
+ start = 0
+ if next_token:
+ try:
+ start = int(next_token)
+ except ValueError:
+ start = 0
+ page = all_subs[start:start + 100]
+ members = ""
+ for sub in page:
+ members += (
+ "<member>"
+ f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"
+ f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"
+ f"<TopicArn>{sub['topic_arn']}</TopicArn>"
+ f"<Protocol>{sub['protocol']}</Protocol>"
+ f"<Endpoint>{sub['endpoint']}</Endpoint>"
+ "</member>"
+ )
+ next_token_xml = ""
+ if start + 100 < len(all_subs):
+ next_token_xml = f"<NextToken>{start + 100}</NextToken>"
return _xml(200, "ListSubscriptionsResponse",
- f"<ListSubscriptionsResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsResult>")
+ f"<ListSubscriptionsResult><Subscriptions>{members}</Subscriptions>{next_token_xml}</ListSubscriptionsResult>")
def _list_subscriptions_by_topic(params):
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 9cdf62ec..9224277b 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -225,12 +225,24 @@ def _update_state_machine(data):
def _list_state_machines(data):
- machines = [
+ all_machines = [
{"stateMachineArn": sm["stateMachineArn"], "name": sm["name"],
"type": sm["type"], "creationDate": sm["creationDate"]}
for sm in _state_machines.values()
]
- return json_response({"stateMachines": machines})
+ max_results = int(data.get("maxResults", 1000))
+ next_token = data.get("nextToken")
+ start = 0
+ if next_token:
+ try:
+ start = int(next_token)
+ except ValueError:
+ start = 0
+ page = all_machines[start:start + max_results]
+ resp = {"stateMachines": page}
+ if start + max_results < len(all_machines):
+ resp["nextToken"] = str(start + max_results)
+ return json_response(resp)
# ---------------------------------------------------------------------------
@@ -333,13 +345,13 @@ def _describe_execution(data):
def _list_executions(data):
sm_arn = data.get("stateMachineArn")
status_filter = data.get("statusFilter")
- execs = []
+ all_execs = []
for ex in _executions.values():
if sm_arn and ex["stateMachineArn"] != sm_arn:
continue
if status_filter and ex["status"] != status_filter:
continue
- execs.append({
+ all_execs.append({
"executionArn": ex["executionArn"],
"stateMachineArn": ex["stateMachineArn"],
"name": ex["name"],
@@ -347,7 +359,19 @@ def _list_executions(data):
"startDate": ex["startDate"],
"stopDate": ex.get("stopDate"),
})
- return json_response({"executions": execs})
+ max_results = int(data.get("maxResults", 1000))
+ next_token = data.get("nextToken")
+ start = 0
+ if next_token:
+ try:
+ start = int(next_token)
+ except ValueError:
+ start = 0
+ page = all_execs[start:start + max_results]
+ resp = {"executions": page}
+ if start + max_results < len(all_execs):
+ resp["nextToken"] = str(start + max_results)
+ return json_response(resp)
def _get_execution_history(data):
diff --git a/pyproject.toml b/pyproject.toml
index 34fe12e1..aaac39f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.25"
+version = "1.1.26"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
@@ -25,6 +25,7 @@ dependencies = [
"uvicorn[standard]>=0.30.6",
"httptools>=0.6.1",
"pyyaml>=6.0",
+ "defusedxml>=0.7",
]
[project.optional-dependencies]
diff --git a/tests/test_services.py b/tests/test_services.py
index e37cd5f3..98afb7b1 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -11814,6 +11814,24 @@ def test_sm_get_random_password(sm):
assert not any(c.isdigit() for c in pwd)
+def test_sm_batch_get_secret_value(sm):
+ sm.create_secret(Name="batch-s1", SecretString="val1")
+ sm.create_secret(Name="batch-s2", SecretString="val2")
+ resp = sm.batch_get_secret_value(SecretIdList=["batch-s1", "batch-s2"])
+ assert len(resp["SecretValues"]) == 2
+ names = {s["Name"] for s in resp["SecretValues"]}
+ assert "batch-s1" in names
+ assert "batch-s2" in names
+ assert len(resp.get("Errors", [])) == 0
+
+
+def test_sm_batch_get_secret_value_with_missing(sm):
+ resp = sm.batch_get_secret_value(SecretIdList=["batch-s1", "nonexistent-secret"])
+ assert len(resp["SecretValues"]) == 1
+ assert len(resp["Errors"]) == 1
+ assert resp["Errors"][0]["SecretId"] == "nonexistent-secret"
+
+
def test_sm_kms_key_id_on_create_and_describe(sm):
sm.create_secret(Name="kms-test-secret", SecretString="val", KmsKeyId="alias/my-key")
resp = sm.describe_secret(SecretId="kms-test-secret")
@@ -17445,3 +17463,409 @@ def test_cloudfront_get_invalidation(cloudfront):
assert inv["Id"] == inv_id
assert inv["Status"] == "Completed"
assert "/getinv-path" in inv["InvalidationBatch"]["Paths"]["Items"]
+
+# ========== Persistence roundtrip — EC2, Route53, Cognito, ECR, CloudWatch, S3 ==========
+
+
+def test_persist_ec2_roundtrip():
+ from ministack.services import ec2 as _ec2
+ _ec2._instances["i-persist01"] = {"InstanceId": "i-persist01", "State": {"Name": "running"}}
+ state = _ec2.get_state()
+ assert "instances" in state
+ _ec2._instances.pop("i-persist01")
+ _ec2.restore_state(state)
+ assert "i-persist01" in _ec2._instances
+ _ec2._instances.pop("i-persist01")
+
+
+def test_persist_route53_roundtrip():
+ from ministack.services import route53 as _r53
+ _r53._zones["Z00PERSIST"] = {"Id": "Z00PERSIST", "Name": "persist.test."}
+ state = _r53.get_state()
+ assert "zones" in state
+ _r53._zones.pop("Z00PERSIST")
+ _r53.restore_state(state)
+ assert "Z00PERSIST" in _r53._zones
+ _r53._zones.pop("Z00PERSIST")
+
+
+def test_persist_cognito_roundtrip():
+ from ministack.services import cognito as _cog
+ _cog._user_pools["us-east-1_PERSIST"] = {"Id": "us-east-1_PERSIST", "Name": "persist-pool"}
+ state = _cog.get_state()
+ assert "user_pools" in state
+ _cog._user_pools.pop("us-east-1_PERSIST")
+ _cog.restore_state(state)
+ assert "us-east-1_PERSIST" in _cog._user_pools
+ _cog._user_pools.pop("us-east-1_PERSIST")
+
+
+def test_persist_ecr_roundtrip():
+ from ministack.services import ecr as _ecr
+ _ecr._repositories["persist-repo"] = {"repositoryName": "persist-repo", "repositoryArn": "arn:test"}
+ state = _ecr.get_state()
+ assert "repositories" in state
+ _ecr._repositories.pop("persist-repo")
+ _ecr.restore_state(state)
+ assert "persist-repo" in _ecr._repositories
+ _ecr._repositories.pop("persist-repo")
+
+
+def test_persist_cloudwatch_roundtrip():
+ from ministack.services import cloudwatch as _cw
+ _cw._alarms["persist-alarm"] = {"AlarmName": "persist-alarm", "StateValue": "OK"}
+ state = _cw.get_state()
+ assert "alarms" in state
+ _cw._alarms.pop("persist-alarm")
+ _cw.restore_state(state)
+ assert "persist-alarm" in _cw._alarms
+ _cw._alarms.pop("persist-alarm")
+
+
+def test_persist_s3_metadata_roundtrip():
+ from ministack.services import s3 as _s3
+ _s3._buckets["persist-bkt"] = {"created": "2025-01-01T00:00:00Z", "objects": {"k": {"body": b"v"}}, "region": "us-east-1"}
+ _s3._bucket_versioning["persist-bkt"] = "Enabled"
+ state = _s3.get_state()
+ assert "buckets_meta" in state
+ # Object bodies must NOT be in the persisted metadata
+ assert "objects" not in state["buckets_meta"].get("persist-bkt", {})
+ assert "bucket_versioning" in state
+ _s3._buckets.pop("persist-bkt")
+ _s3._bucket_versioning.pop("persist-bkt")
+ _s3.restore_state(state)
+ assert "persist-bkt" in _s3._buckets
+ assert _s3._buckets["persist-bkt"]["objects"] == {} # objects not restored
+ assert _s3._bucket_versioning["persist-bkt"] == "Enabled"
+ _s3._buckets.pop("persist-bkt")
+ _s3._bucket_versioning.pop("persist-bkt")
+
+
+def test_persist_lambda_roundtrip():
+ from ministack.services import lambda_svc as _lam
+ _lam._functions["persist-fn"] = {
+ "config": {"FunctionName": "persist-fn", "Runtime": "python3.11"},
+ "code_zip": b"fake-zip-bytes",
+ "versions": {},
+ "next_version": 1,
+ }
+ state = _lam.get_state()
+ assert "functions" in state
+ # code_zip should be base64-encoded in state
+ assert isinstance(state["functions"]["persist-fn"]["code_zip"], str)
+ _lam._functions.pop("persist-fn")
+ _lam.restore_state(state)
+ assert "persist-fn" in _lam._functions
+ # code_zip should be decoded back to bytes
+ assert _lam._functions["persist-fn"]["code_zip"] == b"fake-zip-bytes"
+ _lam._functions.pop("persist-fn")
+
+
+def test_persist_rds_roundtrip():
+ from ministack.services import rds as _rds
+ _rds._instances["persist-db"] = {
+ "DBInstanceIdentifier": "persist-db",
+ "Engine": "postgres",
+ "DBInstanceStatus": "available",
+ "_docker_container_id": "fake-container-id",
+ }
+ state = _rds.get_state()
+ assert "instances" in state
+ assert "_docker_container_id" not in state["instances"]["persist-db"]
+ _rds._instances.pop("persist-db")
+ _rds.restore_state(state)
+ assert "persist-db" in _rds._instances
+ assert _rds._instances["persist-db"]["Engine"] == "postgres"
+ _rds._instances.pop("persist-db")
+
+
+def test_persist_ecs_roundtrip():
+ from ministack.services import ecs as _ecs
+ _ecs._clusters["persist-cluster"] = {"clusterName": "persist-cluster", "status": "ACTIVE"}
+ _ecs._tasks["arn:persist-task"] = {
+ "taskArn": "arn:persist-task",
+ "lastStatus": "RUNNING",
+ "_docker_ids": ["fake-id"],
+ }
+ state = _ecs.get_state()
+ assert "clusters" in state
+ assert "tasks" in state
+ assert "_docker_ids" not in state["tasks"]["arn:persist-task"]
+ _ecs._clusters.pop("persist-cluster")
+ _ecs._tasks.pop("arn:persist-task")
+ _ecs.restore_state(state)
+ assert "persist-cluster" in _ecs._clusters
+ assert "arn:persist-task" in _ecs._tasks
+ assert _ecs._tasks["arn:persist-task"]["lastStatus"] == "STOPPED"
+ _ecs._clusters.pop("persist-cluster")
+ _ecs._tasks.pop("arn:persist-task")
+
+
+def test_persist_elasticache_roundtrip():
+ from ministack.services import elasticache as _ec
+ _ec._clusters["persist-cache"] = {
+ "CacheClusterId": "persist-cache",
+ "Engine": "redis",
+ "CacheClusterStatus": "available",
+ "_docker_container_id": "fake-id",
+ }
+ state = _ec.get_state()
+ assert "clusters" in state
+ assert "_docker_container_id" not in state["clusters"]["persist-cache"]
+ _ec._clusters.pop("persist-cache")
+ _ec.restore_state(state)
+ assert "persist-cache" in _ec._clusters
+ assert _ec._clusters["persist-cache"]["Engine"] == "redis"
+ _ec._clusters.pop("persist-cache")
+
+
+# ========== DynamoDB Streams record content ==========
+
+
+def test_dynamodb_streams_table_has_stream_arn(ddb):
+ """Table with StreamSpecification returns LatestStreamArn and operations succeed."""
+ table_name = "stream-arn-test"
+ resp = ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},
+ )
+ desc = ddb.describe_table(TableName=table_name)["Table"]
+ assert desc.get("LatestStreamArn") or desc.get("StreamSpecification", {}).get("StreamEnabled")
+
+ # All write operations should succeed with streams enabled
+ ddb.put_item(TableName=table_name, Item={"pk": {"S": "k1"}, "val": {"S": "v1"}})
+ ddb.update_item(
+ TableName=table_name,
+ Key={"pk": {"S": "k1"}},
+ UpdateExpression="SET val = :v",
+ ExpressionAttributeValues={":v": {"S": "v2"}},
+ )
+ ddb.delete_item(TableName=table_name, Key={"pk": {"S": "k1"}})
+ # Verify item is gone
+ get_resp = ddb.get_item(TableName=table_name, Key={"pk": {"S": "k1"}})
+ assert "Item" not in get_resp
+
+
+# ========== S3 GetObject with VersionId ==========
+
+
+def test_s3_get_object_with_version_id(s3):
+ """Enable versioning, put 2 versions of same key, verify version IDs differ."""
+ bucket = "s3-version-get-test"
+ s3.create_bucket(Bucket=bucket)
+ s3.put_bucket_versioning(
+ Bucket=bucket,
+ VersioningConfiguration={"Status": "Enabled"},
+ )
+
+ # Put version 1
+ r1 = s3.put_object(Bucket=bucket, Key="file.txt", Body=b"version-1")
+ vid1 = r1.get("VersionId")
+ assert vid1 is not None
+
+ # Put version 2
+ r2 = s3.put_object(Bucket=bucket, Key="file.txt", Body=b"version-2")
+ vid2 = r2.get("VersionId")
+ assert vid2 is not None
+ assert vid1 != vid2
+
+ # GetObject returns latest version with its VersionId
+ get_resp = s3.get_object(Bucket=bucket, Key="file.txt")
+ assert get_resp["Body"].read() == b"version-2"
+ assert get_resp.get("VersionId") == vid2
+
+
+# ========== Lambda warm worker invalidation ==========
+
+
+def test_lambda_warm_worker_invalidation(lam):
+ """Create function with code v1, invoke, update code to v2, invoke again — must see v2."""
+ import io as _io
+ import zipfile as _zf
+
+ fname = "lambda-worker-invalidation-test"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+
+ # v1 code
+ code_v1 = b'def handler(event, context):\n return {"version": 1}\n'
+ buf1 = _io.BytesIO()
+ with _zf.ZipFile(buf1, "w") as z:
+ z.writestr("index.py", code_v1)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf1.getvalue()},
+ )
+
+ # Invoke v1
+ resp1 = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ payload1 = json.loads(resp1["Payload"].read())
+ assert payload1["version"] == 1
+
+ # Update to v2
+ code_v2 = b'def handler(event, context):\n return {"version": 2}\n'
+ buf2 = _io.BytesIO()
+ with _zf.ZipFile(buf2, "w") as z:
+ z.writestr("index.py", code_v2)
+ lam.update_function_code(FunctionName=fname, ZipFile=buf2.getvalue())
+
+ # Invoke v2
+ resp2 = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ payload2 = json.loads(resp2["Payload"].read())
+ assert payload2["version"] == 2
+
+
+# ========== SFN UpdateStateMachine ==========
+
+
+def test_sfn_update_state_machine(sfn):
+ """Create SM, update definition, describe and verify new definition."""
+ defn_v1 = json.dumps({
+ "StartAt": "A",
+ "States": {"A": {"Type": "Pass", "Result": "v1", "End": True}},
+ })
+ create = sfn.create_state_machine(
+ name="sfn-update-test",
+ definition=defn_v1,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ arn = create["stateMachineArn"]
+
+ defn_v2 = json.dumps({
+ "StartAt": "B",
+ "States": {"B": {"Type": "Pass", "Result": "v2", "End": True}},
+ })
+ sfn.update_state_machine(stateMachineArn=arn, definition=defn_v2)
+
+ desc = sfn.describe_state_machine(stateMachineArn=arn)
+ assert desc["definition"] == defn_v2
+
+
+# ========== SFN error paths ==========
+
+
+def test_sfn_create_duplicate_name(sfn):
+ """CreateStateMachine with duplicate name should fail."""
+ defn = json.dumps({
+ "StartAt": "X",
+ "States": {"X": {"Type": "Pass", "End": True}},
+ })
+ sfn.create_state_machine(
+ name="sfn-dup-err-test",
+ definition=defn,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine(
+ name="sfn-dup-err-test",
+ definition=defn,
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ assert "StateMachineAlreadyExists" in str(exc.value) or "Conflict" in str(exc.value) or exc.value.response["Error"]["Code"]
+
+
+def test_sfn_describe_not_found(sfn):
+ """DescribeStateMachine on non-existent ARN should fail."""
+ with pytest.raises(ClientError) as exc:
+ sfn.describe_state_machine(stateMachineArn="arn:aws:states:us-east-1:000000000000:stateMachine:nonexistent-99")
+ err = exc.value.response["Error"]["Code"]
+ assert "StateMachineDoesNotExist" in err or "NotFound" in err or "ResourceNotFound" in err
+
+
+def test_sfn_start_execution_not_found(sfn):
+ """StartExecution on non-existent SM should fail."""
+ with pytest.raises(ClientError) as exc:
+ sfn.start_execution(stateMachineArn="arn:aws:states:us-east-1:000000000000:stateMachine:nonexistent-99")
+ err = exc.value.response["Error"]["Code"]
+ assert "StateMachineDoesNotExist" in err or "NotFound" in err or "ResourceNotFound" in err
+
+
+# ========== DynamoDB TagResource / UntagResource ==========
+
+
+def test_dynamodb_tag_untag_resource(ddb):
+ """Create table, tag it, list tags, untag, verify."""
+ table_name = "ddb-tag-test"
+ try:
+ ddb.delete_table(TableName=table_name)
+ except Exception:
+ pass
+ resp = ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ arn = resp["TableDescription"]["TableArn"]
+
+ # Tag
+ ddb.tag_resource(ResourceArn=arn, Tags=[
+ {"Key": "env", "Value": "test"},
+ {"Key": "team", "Value": "platform"},
+ ])
+ tags = ddb.list_tags_of_resource(ResourceArn=arn)["Tags"]
+ tag_keys = {t["Key"] for t in tags}
+ assert "env" in tag_keys
+ assert "team" in tag_keys
+
+ # Untag
+ ddb.untag_resource(ResourceArn=arn, TagKeys=["team"])
+ tags2 = ddb.list_tags_of_resource(ResourceArn=arn)["Tags"]
+ tag_keys2 = {t["Key"] for t in tags2}
+ assert "env" in tag_keys2
+ assert "team" not in tag_keys2
+
+
+# ========== S3 EventBridge on delete ==========
+
+
+def test_s3_eventbridge_notification_on_delete(s3, sqs, eb):
+ """S3 delete_object should send EventBridge event when EventBridgeConfiguration is enabled."""
+ bucket = "s3-eb-del-bkt"
+ s3.create_bucket(Bucket=bucket)
+ queue_url = sqs.create_queue(QueueName="s3-eb-del-target-q")["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["QueueArn"],
+ )["Attributes"]["QueueArn"]
+
+ # Enable EventBridge on bucket
+ s3.put_bucket_notification_configuration(
+ Bucket=bucket,
+ NotificationConfiguration={"EventBridgeConfiguration": {}},
+ )
+
+ # Create EventBridge rule matching S3 events -> SQS target
+ eb.put_rule(
+ Name="s3-del-to-sqs-rule",
+ EventPattern=json.dumps({"source": ["aws.s3"]}),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule="s3-del-to-sqs-rule",
+ Targets=[{"Id": "sqs-del-target", "Arn": queue_arn}],
+ )
+
+ # Put then delete object
+ s3.put_object(Bucket=bucket, Key="del-test.txt", Body=b"data")
+ # Drain the put event
+ time.sleep(0.5)
+ sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
+
+ # Now delete
+ s3.delete_object(Bucket=bucket, Key="del-test.txt")
+ time.sleep(0.5)
+
+ msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=2)
+ assert "Messages" in msgs and len(msgs["Messages"]) > 0
+ body = json.loads(msgs["Messages"][0]["Body"])
+ assert body["source"] == "aws.s3"
+ assert body["detail"]["bucket"]["name"] == bucket
+ assert body["detail"]["object"]["key"] == "del-test.txt"