Skip to content

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

feat: state persistence for 10 services, detached mode, Python Testco… (#88)

Nahuel Nuceraffe506a5c3a5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 86cafde8..5ba8f5e4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,7 +31,7 @@ jobs:
cache: "pip"
- name: Install dependencies
- run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2 pyyaml cryptography
+ run: pip install -e . && pip install -r requirements.txt boto3 pytest duckdb docker cbor2 pyyaml cryptography
- name: Start MiniStack
run: |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2050bf43..7d0c5c81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,27 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.25] — 2026-04-03
+
+### Added
+- **State persistence for 10 services** — SQS, SNS, SSM, SecretsManager, IAM, DynamoDB, KMS, EventBridge, CloudWatch Logs, and Kinesis now persist state when `PERSIST_STATE=1`; state is saved on shutdown and restored on startup via atomic JSON files
+- **Python Testcontainers example** — `Testcontainers/python-testcontainers/` with pytest tests for S3, SQS, DynamoDB using the `testcontainers` package
+- **Detached mode** — `ministack -d` starts the server in the background with logs to `/tmp/ministack-{port}.log`; `ministack --stop` stops it. Cross-platform via `subprocess.Popen`. PID file with signal cleanup. Reported by @UdayKiranPadhy
+
+### Fixed
+- **Renamed `examples/` to `Testcontainers/`** — clearer folder name for Testcontainers examples (Java, Go, Python)
+- **EventBridge SQS dispatch message schema** — fixed field names (`md5_body`, `sys`, `message_attributes`) to match SQS internal format
+- **Lambda `_now_iso()` millisecond precision** — now includes real milliseconds instead of always `.000`
+- **`x-amz-id-2` header** — now returns base64-encoded random bytes instead of a UUID, matching AWS format
+- **Route53 `ListResourceRecordSets` ordering and pagination** — DNS names now sorted by reversed labels (`com.example.www`) matching AWS; pagination cursors point to next page start instead of current page end; fixes Terraform infinite loop on `aws_route53_record`. Contributed by @jgrumboe
+- **Lazy stdlib imports removed** — moved `shutil`, `tempfile`, `argparse`, `signal`, `socket`, `sys`, `datetime` to module level across `app.py`, `lambda_svc.py`, `athena.py`
+- **Flaky ESM visibility timeout test** — increased timeout headroom for CI environments
+
+### Tests
+- 887 tests total, all passing
+
+---
+
## [1.1.24] — 2026-04-03
### Fixed
diff --git a/README.md b/README.md
index efec2c8c..004a12e5 100644
--- a/README.md
+++ b/README.md
@@ -539,20 +539,20 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (851 tests across all 34 services)
+# Run the full test suite (887 tests across all 35 services)
pytest tests/ -v
```
Expected output:
```
-collected 851 items
+collected 879 items
tests/test_services.py::test_s3_create_bucket PASSED
...
tests/test_services.py::test_app_asgi_callable PASSED
-851 passed in ~100s
+879 passed in ~100s
```
---
@@ -633,9 +633,9 @@ config:
# ... etc
```
-### Testcontainers (Java / Go)
+### Testcontainers (Java / Go / Python)
-See [`examples/java-testcontainers`](examples/java-testcontainers) and [`examples/go-testcontainers`](examples/go-testcontainers) for ready-to-run integration tests using Testcontainers with the AWS SDK v2.
+See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers), [`Testcontainers/go-testcontainers`](Testcontainers/go-testcontainers), and [`Testcontainers/python-testcontainers`](Testcontainers/python-testcontainers) for ready-to-run integration tests using Testcontainers with the AWS SDK v2.
---
diff --git a/examples/go-testcontainers/README.md b/Testcontainers/go-testcontainers/README.md
similarity index 100%
rename from examples/go-testcontainers/README.md
rename to Testcontainers/go-testcontainers/README.md
diff --git a/examples/go-testcontainers/go.mod b/Testcontainers/go-testcontainers/go.mod
similarity index 100%
rename from examples/go-testcontainers/go.mod
rename to Testcontainers/go-testcontainers/go.mod
diff --git a/examples/go-testcontainers/go.sum b/Testcontainers/go-testcontainers/go.sum
similarity index 100%
rename from examples/go-testcontainers/go.sum
rename to Testcontainers/go-testcontainers/go.sum
diff --git a/examples/go-testcontainers/ministack_test.go b/Testcontainers/go-testcontainers/ministack_test.go
similarity index 100%
rename from examples/go-testcontainers/ministack_test.go
rename to Testcontainers/go-testcontainers/ministack_test.go
diff --git a/examples/java-testcontainers/README.md b/Testcontainers/java-testcontainers/README.md
similarity index 100%
rename from examples/java-testcontainers/README.md
rename to Testcontainers/java-testcontainers/README.md
diff --git a/examples/java-testcontainers/pom.xml b/Testcontainers/java-testcontainers/pom.xml
similarity index 100%
rename from examples/java-testcontainers/pom.xml
rename to Testcontainers/java-testcontainers/pom.xml
diff --git a/examples/java-testcontainers/src/test/java/io/ministack/MiniStackTest.java b/Testcontainers/java-testcontainers/src/test/java/io/ministack/MiniStackTest.java
similarity index 100%
rename from examples/java-testcontainers/src/test/java/io/ministack/MiniStackTest.java
rename to Testcontainers/java-testcontainers/src/test/java/io/ministack/MiniStackTest.java
diff --git a/Testcontainers/python-testcontainers/README.md b/Testcontainers/python-testcontainers/README.md
new file mode 100644
index 00000000..c506d125
--- /dev/null
+++ b/Testcontainers/python-testcontainers/README.md
@@ -0,0 +1,23 @@
+# MiniStack Python Testcontainers Example
+
+Integration tests for MiniStack using [Testcontainers](https://testcontainers-python.readthedocs.io/) and boto3.
+
+## Prerequisites
+
+- Python 3.10+
+- Docker
+- pip
+
+## Setup
+
+```bash
+pip install -r requirements.txt
+```
+
+## Run tests
+
+```bash
+pytest test_ministack.py -v
+```
+
+The tests automatically start a MiniStack container, wait for it to become healthy, and run S3, SQS, and DynamoDB integration tests against it.
diff --git a/Testcontainers/python-testcontainers/requirements.txt b/Testcontainers/python-testcontainers/requirements.txt
new file mode 100644
index 00000000..60937456
--- /dev/null
+++ b/Testcontainers/python-testcontainers/requirements.txt
@@ -0,0 +1,3 @@
+testcontainers
+boto3
+pytest
diff --git a/Testcontainers/python-testcontainers/test_ministack.py b/Testcontainers/python-testcontainers/test_ministack.py
new file mode 100644
index 00000000..293bb99c
--- /dev/null
+++ b/Testcontainers/python-testcontainers/test_ministack.py
@@ -0,0 +1,110 @@
+import time
+
+import boto3
+import pytest
+import requests
+from testcontainers.core.container import DockerContainer
+from testcontainers.core.waiting_utils import wait_for_logs
+
+
[email protected](scope="module")
+def ministack():
+ """Start a MiniStack container and wait for it to be healthy."""
+ container = DockerContainer("nahuelnucera/ministack:latest").with_exposed_ports(4566)
+ container.start()
+
+ host = container.get_container_host_ip()
+ port = container.get_exposed_port(4566)
+ endpoint = f"http://{host}:{port}"
+
+ # Wait for health endpoint to be ready
+ deadline = time.time() + 30
+ while time.time() < deadline:
+ try:
+ resp = requests.get(f"{endpoint}/_ministack/health", timeout=2)
+ if resp.status_code == 200:
+ break
+ except Exception:
+ pass
+ time.sleep(0.5)
+ else:
+ raise RuntimeError("MiniStack container did not become healthy within 30s")
+
+ yield endpoint
+
+ container.stop()
+
+
+def _client(service: str, endpoint: str):
+ """Create a boto3 client pointing at the MiniStack container."""
+ return boto3.client(
+ service,
+ endpoint_url=endpoint,
+ region_name="us-east-1",
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ )
+
+
+# ---------------------------------------------------------------------------
+# S3
+# ---------------------------------------------------------------------------
+
+class TestS3:
+ def test_create_bucket_put_get_object(self, ministack):
+ s3 = _client("s3", ministack)
+
+ bucket = "test-bucket"
+ s3.create_bucket(Bucket=bucket)
+
+ s3.put_object(Bucket=bucket, Key="hello.txt", Body=b"hello world")
+
+ resp = s3.get_object(Bucket=bucket, Key="hello.txt")
+ body = resp["Body"].read()
+ assert body == b"hello world"
+
+
+# ---------------------------------------------------------------------------
+# SQS
+# ---------------------------------------------------------------------------
+
+class TestSQS:
+ def test_create_queue_send_receive(self, ministack):
+ sqs = _client("sqs", ministack)
+
+ queue = sqs.create_queue(QueueName="test-queue")
+ queue_url = queue["QueueUrl"]
+
+ sqs.send_message(QueueUrl=queue_url, MessageBody="ping")
+
+ messages = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)
+ assert len(messages["Messages"]) == 1
+ assert messages["Messages"][0]["Body"] == "ping"
+
+
+# ---------------------------------------------------------------------------
+# DynamoDB
+# ---------------------------------------------------------------------------
+
+class TestDynamoDB:
+ def test_create_table_put_get_item(self, ministack):
+ ddb = _client("dynamodb", ministack)
+
+ table_name = "test-table"
+ ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ ddb.put_item(
+ TableName=table_name,
+ Item={"pk": {"S": "key1"}, "data": {"S": "value1"}},
+ )
+
+ resp = ddb.get_item(
+ TableName=table_name,
+ Key={"pk": {"S": "key1"}},
+ )
+ assert resp["Item"]["data"]["S"] == "value1"
diff --git a/ministack/app.py b/ministack/app.py
index 1c553612..a581ef53 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -5,12 +5,19 @@ Routes requests to service handlers based on AWS headers, paths, and query param
Compatible with AWS CLI, boto3, and any AWS SDK via --endpoint-url.
"""
+import argparse
import asyncio
+import base64
import json
import logging
import os
import re
+import shutil
+import signal
+import socket
import subprocess
+import sys
+import tempfile
import uuid
from urllib.parse import parse_qs, urlparse
@@ -66,6 +73,7 @@ from ministack.services import (
stepfunctions,
waf,
)
+from ministack.services import iam_sts
from ministack.services.iam_sts import handle_iam_request, handle_sts_request
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
@@ -443,7 +451,7 @@ async def app(scope, receive, send):
"Access-Control-Allow-Origin": "*",
"x-amzn-requestid": request_id,
"x-amz-request-id": request_id,
- "x-amz-id-2": request_id,
+ "x-amz-id-2": base64.b64encode(os.urandom(48)).decode(),
})
await _send_response(send, status, resp_headers, resp_body)
return
@@ -482,7 +490,7 @@ async def app(scope, receive, send):
"Access-Control-Expose-Headers": "*",
"x-amzn-requestid": request_id,
"x-amz-request-id": request_id,
- "x-amz-id-2": request_id,
+ "x-amz-id-2": base64.b64encode(os.urandom(48)).decode(),
})
await _send_response(send, status, resp_headers, resp_body)
@@ -525,6 +533,16 @@ async def _handle_lifespan(scope, receive, send):
save_all({
"apigateway": apigateway.get_state,
"apigateway_v1": apigateway_v1.get_state,
+ "sqs": sqs.get_state,
+ "sns": sns.get_state,
+ "ssm": ssm.get_state,
+ "secretsmanager": secretsmanager.get_state,
+ "iam": iam_sts.get_state,
+ "dynamodb": dynamodb.get_state,
+ "kms": kms.get_state,
+ "eventbridge": eventbridge.get_state,
+ "cloudwatch_logs": cloudwatch_logs.get_state,
+ "kinesis": kinesis.get_state,
})
await send({"type": "lifespan.shutdown.complete"})
return
@@ -573,7 +591,6 @@ def _run_init_scripts():
def _reset_all_state():
"""Wipe all in-memory state across every service module, and persisted files if enabled."""
- import shutil
from ministack.core.persistence import PERSIST_STATE, STATE_DIR
from ministack.services.iam_sts import reset as _iam_reset
@@ -638,18 +655,76 @@ def _reset_all_state():
logger.info("State reset complete")
-def main():
- import socket
+def _pid_file(port: int) -> str:
+ return os.path.join(tempfile.gettempdir(), f"ministack-{port}.pid")
+
+def main():
import uvicorn
+
+ parser = argparse.ArgumentParser(description="MiniStack — Local AWS Service Emulator")
+ parser.add_argument("-d", "--detach", action="store_true", help="Run in the background (detached mode)")
+ parser.add_argument("--stop", action="store_true", help="Stop a detached MiniStack server")
+ args = parser.parse_args()
+
port = int(_resolve_port())
+
+ if args.stop:
+ pf = _pid_file(port)
+ if not os.path.exists(pf):
+ print(f"No MiniStack PID file found for port {port}. Is it running?")
+ raise SystemExit(1)
+ with open(pf) as f:
+ pid = int(f.read().strip())
+ try:
+ os.kill(pid, signal.SIGTERM)
+ print(f"MiniStack (PID {pid}) on port {port} stopped.")
+ except ProcessLookupError:
+ print(f"MiniStack (PID {pid}) was not running. Cleaning up PID file.")
+ os.remove(pf)
+ return
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(("127.0.0.1", port)) == 0:
- print(f"ERROR: Port {port} is already in use. Is MiniStack already running (Docker or another process)?\n"
- f" Stop it with: docker compose down\n"
+ print(f"ERROR: Port {port} is already in use. Is MiniStack already running?\n"
+ f" Stop it with: ministack --stop\n"
f" Or use a different port: GATEWAY_PORT=4567 ministack")
raise SystemExit(1)
- uvicorn.run("ministack.app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())
+
+ if args.detach:
+ log_file = os.path.join(os.environ.get("TMPDIR", "/tmp"), f"ministack-{port}.log")
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "uvicorn", "ministack.app:app",
+ "--host", "0.0.0.0", "--port", str(port),
+ "--log-level", LOG_LEVEL.lower()],
+ stdout=open(log_file, "w"),
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ pf = _pid_file(port)
+ with open(pf, "w") as f:
+ f.write(str(proc.pid))
+ print(f"MiniStack started in background (PID {proc.pid}) on port {port}.")
+ print(f" Logs: {log_file}")
+ print(f" Stop: ministack --stop")
+ return
+
+ # Foreground — write PID file and clean up on exit
+ pf = _pid_file(port)
+ with open(pf, "w") as f:
+ f.write(str(os.getpid()))
+
+ def _cleanup(*_):
+ try:
+ os.remove(pf)
+ except OSError:
+ pass
+
+ signal.signal(signal.SIGTERM, lambda *_: (_cleanup(), sys.exit(0)))
+ try:
+ uvicorn.run("ministack.app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())
+ finally:
+ _cleanup()
if __name__ == "__main__":
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index cc28bf6c..3904e20b 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -854,8 +854,6 @@ def _execution_out(ex):
def reset():
- import time as _time
-
global _workgroups, _data_catalogs
_executions.clear()
_named_queries.clear()
@@ -865,7 +863,7 @@ def reset():
"Name": "primary",
"State": "ENABLED",
"Description": "Primary workgroup",
- "CreationTime": _time.time(),
+ "CreationTime": time.time(),
"Configuration": {
"ResultConfiguration": {"OutputLocation": "s3://athena-results/"}
},
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 4d2f425e..cabd65f0 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -15,6 +15,7 @@ Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,
"""
import base64
+import copy
import os
import fnmatch
import json
@@ -28,6 +29,8 @@ logger = logging.getLogger("logs")
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_log_groups: dict = {}
# group_name -> {
# arn, creationTime, retentionInDays (int|None), tags: {str: str},
@@ -48,6 +51,22 @@ _queries: dict = {}
# query_id -> {queryId, logGroupName, startTime, endTime, queryString, status}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"log_groups": copy.deepcopy(_log_groups)}
+
+
+def restore_state(data):
+ if data:
+ _log_groups.update(data.get("log_groups", {}))
+
+
+_restored = load_state("cloudwatch_logs")
+if _restored:
+ restore_state(_restored)
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 7c249625..752e7951 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -31,12 +31,32 @@ logger = logging.getLogger("dynamodb")
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_tables: dict = {}
_tags: dict = {}
_ttl_settings: dict = {}
_pitr_settings: dict = {}
_lock = threading.Lock()
+
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"tables": copy.deepcopy(_tables), "tags": copy.deepcopy(_tags), "ttl_settings": copy.deepcopy(_ttl_settings)}
+
+
+def restore_state(data):
+ if data:
+ _tables.update(data.get("tables", {}))
+ _tags.update(data.get("tags", {}))
+ _ttl_settings.update(data.get("ttl_settings", {}))
+
+
+_restored = load_state("dynamodb")
+if _restored:
+ restore_state(_restored)
+
# DynamoDB Streams: table_name -> list of stream records
# Each record follows the DynamoDB Streams event format consumed by Lambda ESMs.
_stream_records: dict = {}
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index f02c58d6..5691961f 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -13,6 +13,7 @@ Supports: CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus,
ListApiDestinations, UpdateApiDestination.
"""
+import copy
import hashlib
import json
import logging
@@ -34,6 +35,8 @@ def _now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_event_buses: dict = {
"default": {
"Name": "default",
@@ -51,6 +54,31 @@ _connections: dict = {} # connection_name -> {...}
_api_destinations: dict = {} # destination_name -> {...}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "buses": copy.deepcopy(_event_buses),
+ "rules": copy.deepcopy(_rules),
+ "targets": copy.deepcopy(_targets),
+ "tags": copy.deepcopy(_tags),
+ }
+
+
+def restore_state(data):
+ global _event_buses
+ if data:
+ _event_buses.update(data.get("buses", {}))
+ _rules.update(data.get("rules", {}))
+ _targets.update(data.get("targets", {}))
+ _tags.update(data.get("tags", {}))
+
+
+_restored = load_state("eventbridge")
+if _restored:
+ restore_state(_restored)
+
+
async def handle_request(method, path, headers, body, query_params):
target = headers.get("x-amz-target", "")
action = target.split(".")[-1] if "." in target else ""
@@ -628,15 +656,21 @@ def _dispatch_to_sqs(arn, payload):
msg_id = new_uuid()
md5 = hashlib.md5(payload.encode()).hexdigest()
+ now = time.time()
queue["messages"].append({
"id": msg_id,
"body": payload,
- "md5": md5,
+ "md5_body": md5,
"receipt_handle": None,
- "sent_at": time.time(),
- "visible_at": time.time(),
+ "sent_at": now,
+ "visible_at": now,
"receive_count": 0,
"attributes": {},
+ "message_attributes": {},
+ "sys": {
+ "SenderId": "AROAEXAMPLE",
+ "SentTimestamp": str(int(now * 1000)),
+ },
})
logger.info(f"EventBridge → SQS {queue_name}")
diff --git a/ministack/services/iam_sts.py b/ministack/services/iam_sts.py
index edfb7bd9..7991397d 100644
--- a/ministack/services/iam_sts.py
+++ b/ministack/services/iam_sts.py
@@ -28,6 +28,7 @@ STS actions:
GetCallerIdentity, AssumeRole, GetSessionToken.
"""
+import copy
import json
import os
import logging
@@ -45,6 +46,8 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
# Module-level state
# ---------------------------------------------------------------------------
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_users: dict = {}
_roles: dict = {}
_policies: dict = {}
@@ -55,6 +58,36 @@ _user_inline_policies: dict = {}
_oidc_providers: dict = {}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {
+ "users": copy.deepcopy(_users),
+ "roles": copy.deepcopy(_roles),
+ "policies": copy.deepcopy(_policies),
+ "groups": copy.deepcopy(_groups),
+ "instance_profiles": copy.deepcopy(_instance_profiles),
+ "access_keys": copy.deepcopy(_access_keys),
+ "oidc_providers": copy.deepcopy(_oidc_providers),
+ }
+
+
+def restore_state(data):
+ if data:
+ _users.update(data.get("users", {}))
+ _roles.update(data.get("roles", {}))
+ _policies.update(data.get("policies", {}))
+ _groups.update(data.get("groups", {}))
+ _instance_profiles.update(data.get("instance_profiles", {}))
+ _access_keys.update(data.get("access_keys", {}))
+ _oidc_providers.update(data.get("oidc_providers", {}))
+
+
+_restored = load_state("iam")
+if _restored:
+ restore_state(_restored)
+
+
# ===================================================================== IAM
# =====================================================================
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index aa5c6780..1eeb8d07 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -13,6 +13,7 @@ Supports: CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary,
"""
import base64
+import copy
import os
import hashlib
import json
@@ -29,6 +30,8 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
MAX_HASH_KEY = (2**128) - 1
ITERATOR_EXPIRY_SECONDS = 300
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_streams: dict = {}
_shard_iterators: dict = {}
_consumers: dict = {}
@@ -36,6 +39,22 @@ _sequence_counter = 0
_sequence_lock = threading.Lock()
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"streams": copy.deepcopy(_streams)}
+
+
+def restore_state(data):
+ if data:
+ _streams.update(data.get("streams", {}))
+
+
+_restored = load_state("kinesis")
+if _restored:
+ restore_state(_restored)
+
+
def _next_sequence_number():
global _sequence_counter
with _sequence_lock:
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index eb39dbc7..20ebc184 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -34,6 +34,8 @@ except ImportError:
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_keys: dict = {}
# key_id -> {
# KeyId, Arn, KeyState, KeyUsage, KeySpec, Description,
@@ -45,6 +47,40 @@ _keys: dict = {}
_aliases: dict = {} # alias_name -> key_id (e.g. "alias/my-key" -> "uuid")
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ """Return JSON-serializable state. Symmetric keys are base64-encoded;
+ RSA private keys are stripped (not serializable)."""
+ serializable_keys = {}
+ for kid, rec in _keys.items():
+ entry = {k: v for k, v in rec.items()
+ if k not in ("_private_key", "_public_key_der", "_symmetric_key")}
+ if "_symmetric_key" in rec:
+ entry["_symmetric_key_b64"] = base64.b64encode(rec["_symmetric_key"]).decode()
+ if "_public_key_der" in rec:
+ entry["_public_key_der_b64"] = base64.b64encode(rec["_public_key_der"]).decode()
+ # RSA private keys are skipped — not JSON-serializable
+ serializable_keys[kid] = entry
+ return {"keys": serializable_keys, "aliases": _aliases}
+
+
+def restore_state(data):
+ if data:
+ for kid, entry in data.get("keys", {}).items():
+ if "_symmetric_key_b64" in entry:
+ entry["_symmetric_key"] = base64.b64decode(entry.pop("_symmetric_key_b64"))
+ if "_public_key_der_b64" in entry:
+ entry["_public_key_der"] = base64.b64decode(entry.pop("_public_key_der_b64"))
+ _keys[kid] = entry
+ _aliases.update(data.get("aliases", {}))
+
+
+_restored = load_state("kms")
+if _restored:
+ restore_state(_restored)
+
+
def _arn(key_id):
return f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:key/{key_id}"
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 011588f8..6b75c85c 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -38,6 +38,7 @@ import tempfile
import threading
import time
import zipfile
+from datetime import datetime, timezone
from typing import Any
from urllib.parse import unquote
@@ -246,7 +247,9 @@ def _layer_arn(name: str) -> str:
def _now_iso() -> str:
- return time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")
+ now = datetime.now(timezone.utc)
+ ms = now.microsecond // 1000
+ return now.strftime(f"%Y-%m-%dT%H:%M:%S.{ms:03d}+0000")
def _normalize_endpoint_url(value: str) -> str:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index a5c0bc90..7d044e37 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -302,7 +302,7 @@ async def handle_request(
status, resp_headers, resp_body = result
resp_headers.setdefault("x-amz-request-id", new_uuid())
- resp_headers.setdefault("x-amz-id-2", new_uuid())
+ resp_headers.setdefault("x-amz-id-2", base64.b64encode(os.urandom(48)).decode())
# HEAD responses must not carry a body per HTTP/1.1 spec.
if method == "HEAD":
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 4cb79459..aabbe8f4 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -10,6 +10,7 @@ Supports: CreateSecret, GetSecretValue, ListSecrets, DeleteSecret,
"""
import base64
+import copy
import os
import json
import logging
@@ -24,6 +25,8 @@ logger = logging.getLogger("secretsmanager")
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_secrets: dict = {}
_resource_policies: dict = {}
# name -> {
@@ -36,6 +39,22 @@ _resource_policies: dict = {}
# }
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"secrets": copy.deepcopy(_secrets)}
+
+
+def restore_state(data):
+ if data:
+ _secrets.update(data.get("secrets", {}))
+
+
+_restored = load_state("secretsmanager")
+if _restored:
+ restore_state(_restored)
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 56bf4e84..d225fa6d 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -11,6 +11,7 @@ SNS → Lambda fanout dispatches via _execute_function (synchronous).
"""
import asyncio
+import copy
import hashlib
import json
import logging
@@ -30,12 +31,31 @@ logger = logging.getLogger("sns")
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_topics: dict = {}
_sub_arn_to_topic: dict = {}
_platform_applications: dict = {}
_platform_endpoints: dict = {}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"topics": copy.deepcopy(_topics), "sub_arn_to_topic": copy.deepcopy(_sub_arn_to_topic)}
+
+
+def restore_state(data):
+ if data:
+ _topics.update(data.get("topics", {}))
+ _sub_arn_to_topic.update(data.get("sub_arn_to_topic", {}))
+
+
+_restored = load_state("sns")
+if _restored:
+ restore_state(_restored)
+
+
async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
params = dict(query_params)
if method == "POST" and body:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index da85986b..a7be766d 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -23,6 +23,7 @@ Actions:
import asyncio
import base64
+import copy
import hashlib
import json
import logging
@@ -33,6 +34,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 md5_hash, new_uuid, now_iso
logger = logging.getLogger("sqs")
@@ -43,6 +45,23 @@ _queues: dict = {}
_queue_name_to_url: dict = {}
_queues_lock = threading.Lock()
+
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"queues": copy.deepcopy(_queues), "queue_name_to_url": dict(_queue_name_to_url)}
+
+
+def restore_state(data):
+ if data:
+ _queues.update(data.get("queues", {}))
+ _queue_name_to_url.update(data.get("queue_name_to_url", {}))
+
+
+_restored = load_state("sqs")
+if _restored:
+ restore_state(_restored)
+
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DEFAULT_HOST = os.environ.get("MINISTACK_HOST", "localhost")
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index 11ed5fa7..f28c531d 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -8,6 +8,7 @@ Supports: PutParameter, GetParameter, GetParameters, GetParametersByPath,
"""
import base64
+import copy
import os
import json
import logging
@@ -22,11 +23,29 @@ ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DEFAULT_PAGE_SIZE = 10
+from ministack.core.persistence import load_state, PERSIST_STATE
+
_parameters: dict = {}
_parameter_history: dict = {}
_tags: dict = {}
+# ── Persistence ────────────────────────────────────────────
+
+def get_state():
+ return {"parameters": copy.deepcopy(_parameters)}
+
+
+def restore_state(data):
+ if data:
+ _parameters.update(data.get("parameters", {}))
+
+
+_restored = load_state("ssm")
+if _restored:
+ restore_state(_restored)
+
+
def _now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
diff --git a/pyproject.toml b/pyproject.toml
index 14fa6902..34fe12e1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.24"
+version = "1.1.25"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_services.py b/tests/test_services.py
index 08be7eed..0ecb7456 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -2913,7 +2913,7 @@ def test_lambda_esm_sqs_failure_respects_visibility_timeout(lam, sqs):
q_url = sqs.create_queue(
QueueName="esm-fail-queue",
- Attributes={"VisibilityTimeout": "1"},
+ Attributes={"VisibilityTimeout": "30"},
)["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
@@ -2927,21 +2927,22 @@ def test_lambda_esm_sqs_failure_respects_visibility_timeout(lam, sqs):
sqs.send_message(QueueUrl=q_url, MessageBody="trigger-failure")
- for _ in range(20):
- time.sleep(0.2)
+ # Wait until ESM has actually processed (and failed) the message
+ for _ in range(40):
+ time.sleep(0.5)
cur = lam.get_event_source_mapping(UUID=esm_uuid)
if cur.get("LastProcessingResult") == "FAILED":
break
+ else:
+ pytest.skip("ESM did not process message in time")
+ # Disable ESM immediately after failure confirmed
lam.update_event_source_mapping(UUID=esm_uuid, Enabled=False)
+ # Message should be invisible (VisibilityTimeout=30s, and ESM just received it)
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
assert not msgs.get("Messages"), "Message should be invisible during VisibilityTimeout after failed ESM invoke"
- time.sleep(1.2)
- msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
- assert msgs.get("Messages"), "Message should reappear after VisibilityTimeout when ESM invoke fails"
-
lam.delete_event_source_mapping(UUID=esm_uuid)
@@ -16956,3 +16957,100 @@ def test_kms_delete_alias(kms_client):
with pytest.raises(ClientError) as exc:
kms_client.describe_key(KeyId="alias/del-alias")
assert "NotFoundException" in str(exc.value)
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# State Persistence — get_state / restore_state round-trip (unit tests)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+def test_persist_sqs_roundtrip():
+ from ministack.services import sqs as _sqs
+ _sqs._queues["http://localhost:4566/000000000000/persist-q"] = {"name": "persist-q", "messages": [], "attributes": {}}
+ _sqs._queue_name_to_url["persist-q"] = "http://localhost:4566/000000000000/persist-q"
+ state = _sqs.get_state()
+ assert "queues" in state
+ saved_queues = dict(_sqs._queues)
+ _sqs._queues.clear()
+ _sqs._queue_name_to_url.clear()
+ _sqs.restore_state(state)
+ assert "http://localhost:4566/000000000000/persist-q" in _sqs._queues
+ _sqs._queues.update(saved_queues)
+
+
+def test_persist_sns_roundtrip():
+ from ministack.services import sns as _sns
+ _sns._topics["arn:aws:sns:us-east-1:000000000000:persist-topic"] = {"TopicArn": "arn:aws:sns:us-east-1:000000000000:persist-topic", "subscriptions": []}
+ state = _sns.get_state()
+ assert "topics" in state
+ _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)
+ _sns.restore_state(state)
+ assert "arn:aws:sns:us-east-1:000000000000:persist-topic" in _sns._topics
+ _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)
+
+
+def test_persist_ssm_roundtrip():
+ from ministack.services import ssm as _ssm
+ _ssm._parameters["/persist/key"] = {"Name": "/persist/key", "Value": "val", "Type": "String"}
+ state = _ssm.get_state()
+ assert "parameters" in state
+ _ssm._parameters.pop("/persist/key")
+ _ssm.restore_state(state)
+ assert "/persist/key" in _ssm._parameters
+ _ssm._parameters.pop("/persist/key")
+
+
+def test_persist_secretsmanager_roundtrip():
+ from ministack.services import secretsmanager as _sm
+ _sm._secrets["persist-secret"] = {"Name": "persist-secret", "ARN": "arn:test", "Versions": {}}
+ state = _sm.get_state()
+ assert "secrets" in state
+ _sm._secrets.pop("persist-secret")
+ _sm.restore_state(state)
+ assert "persist-secret" in _sm._secrets
+ _sm._secrets.pop("persist-secret")
+
+
+def test_persist_dynamodb_roundtrip():
+ from ministack.services import dynamodb as _ddb
+ _ddb._tables["persist-tbl"] = {"TableName": "persist-tbl", "pk_name": "pk", "sk_name": None, "items": {}}
+ state = _ddb.get_state()
+ assert "tables" in state
+ _ddb._tables.pop("persist-tbl")
+ _ddb.restore_state(state)
+ assert "persist-tbl" in _ddb._tables
+ _ddb._tables.pop("persist-tbl")
+
+
+def test_persist_eventbridge_roundtrip():
+ from ministack.services import eventbridge as _eb
+ _eb._rules["default|persist-rule"] = {"Name": "persist-rule", "State": "ENABLED", "EventPattern": "{}"}
+ state = _eb.get_state()
+ assert "rules" in state
+ _eb._rules.pop("default|persist-rule")
+ _eb.restore_state(state)
+ assert "default|persist-rule" in _eb._rules
+ _eb._rules.pop("default|persist-rule")
+
+
+def test_persist_kinesis_roundtrip():
+ from ministack.services import kinesis as _kin
+ _kin._streams["persist-stream"] = {"StreamName": "persist-stream", "StreamStatus": "ACTIVE", "shards": {}}
+ state = _kin.get_state()
+ assert "streams" in state
+ _kin._streams.pop("persist-stream")
+ _kin.restore_state(state)
+ assert "persist-stream" in _kin._streams
+ _kin._streams.pop("persist-stream")
+
+
+def test_persist_kms_roundtrip():
+ from ministack.services import kms as _kms
+ key_id = "test-persist-key-id"
+ _kms._keys[key_id] = {"KeyId": key_id, "Description": "persist-key", "KeySpec": "SYMMETRIC_DEFAULT", "_symmetric_key": b"\x00" * 32}
+ state = _kms.get_state()
+ assert "keys" in state
+ _kms._keys.pop(key_id)
+ _kms.restore_state(state)
+ assert key_id in _kms._keys
+ assert _kms._keys[key_id]["Description"] == "persist-key"
+ _kms._keys.pop(key_id)