Skip to content

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

Fix/multi tenant persistence v57 (#203)

Nahuel Nuceraecb7a7198f3e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5de11e6c..2751ceb2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,15 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.57] — 2026-04-09
+
+### Fixed
+- **EventBridge wildcard and content-filter patterns not matching** — event patterns using `{"wildcard": "*simple*"}`, `{"prefix": "..."}`, `{"suffix": "..."}`, etc. in top-level fields like `detail-type` and `source` were silently ignored. Content-based filters now work in all pattern fields, not just `detail`. Also added `wildcard` support to the content filter engine (uses `fnmatch` glob matching). Reported by @jfisbein
+- **IAM tags not saved on CreateRole/CreateUser** — tags passed at creation time via `Tags.member.N.Key/Value` were silently ignored. `GetRole` and `GetUser` now return tags set during creation. Same pattern as the KMS and SQS tag fixes in prior releases.
+- **Multi-tenant state persistence loses non-default accounts on restart** — when `PERSIST_STATE=1`, resources created under custom account IDs were restored under `000000000000` after container restart. Affected services: **S3**, **Lambda**, **ECS**, **KMS**. All four services' `get_state()` functions now iterate all accounts' data (via `_data`) instead of only the current request context. S3 file persistence (`S3_DATA_DIR`) layout changed to `DATA_DIR/<account_id>/<bucket>/<key>`; legacy flat layout auto-detected on load. The other 14 services (SQS, SNS, DynamoDB, IAM, EC2, SSM, etc.) were already safe — they use `copy.deepcopy()` which preserves all accounts.
+
+---
+
## [1.1.56] — 2026-04-09
### Added
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index a696eb34..25573f9e 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -67,12 +67,14 @@ def get_state():
"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():
+ # Save tasks but strip Docker container IDs.
+ # Iterate _data directly to capture ALL accounts.
+ from ministack.core.responses import AccountScopedDict
+ tasks = AccountScopedDict()
+ for scoped_key, task in _tasks._data.items():
t = copy.deepcopy(task)
t.pop("_docker_ids", None)
- tasks[arn] = t
+ tasks._data[scoped_key] = t
state["tasks"] = tasks
return state
@@ -87,10 +89,18 @@ def restore_state(data):
_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
+ from ministack.core.responses import AccountScopedDict
+ tasks_data = data.get("tasks", {})
+ if isinstance(tasks_data, AccountScopedDict):
+ for scoped_key, task in tasks_data._data.items():
+ task["_docker_ids"] = []
+ task["lastStatus"] = "STOPPED"
+ _tasks._data[scoped_key] = task
+ else:
+ for arn, task in tasks_data.items():
+ task["_docker_ids"] = []
+ task["lastStatus"] = "STOPPED"
+ _tasks[arn] = task
_restored = load_state("ecs")
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 4d80ba7b..a75b33a7 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -14,6 +14,7 @@ Supports: CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus,
"""
import copy
+import fnmatch
import hashlib
import json
import logging
@@ -536,7 +537,14 @@ def _matches_pattern(pattern_str, event):
def _matches_field(value, pattern_values):
if isinstance(pattern_values, list):
- return value in pattern_values
+ for item in pattern_values:
+ if isinstance(item, dict):
+ # Content-based filter (wildcard, prefix, suffix, etc.)
+ if _matches_content_filter(value, item):
+ return True
+ elif value == item:
+ return True
+ return False
return value == pattern_values
@@ -569,6 +577,8 @@ def _matches_detail(detail, pattern):
def _matches_content_filter(value, filter_rule):
+ if "wildcard" in filter_rule:
+ return isinstance(value, str) and fnmatch.fnmatch(value, filter_rule["wildcard"])
if "prefix" in filter_rule:
return isinstance(value, str) and value.startswith(filter_rule["prefix"])
if "suffix" in filter_rule:
diff --git a/ministack/services/iam_sts.py b/ministack/services/iam_sts.py
index 66b23241..f3301b7f 100644
--- a/ministack/services/iam_sts.py
+++ b/ministack/services/iam_sts.py
@@ -135,7 +135,7 @@ def _create_user(p):
"CreateDate": _now(),
"Path": path,
"AttachedPolicies": [],
- "Tags": [],
+ "Tags": _extract_tags(p),
}
return _xml(200, "CreateUserResponse",
f"<CreateUserResult><User>{_user_xml(name)}</User></CreateUserResult>",
@@ -211,7 +211,7 @@ def _create_role(p):
"MaxSessionDuration": int(_p(p, "MaxSessionDuration") or 3600),
"AttachedPolicies": [],
"InlinePolicies": {},
- "Tags": [],
+ "Tags": _extract_tags(p),
}
return _xml(200, "CreateRoleResponse",
f"<CreateRoleResult><Role>{_role_xml(name)}</Role></CreateRoleResult>",
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index 70c5d38c..55646123 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -51,8 +51,10 @@ _aliases = AccountScopedDict() # alias_name -> key_id (e.g. "alias/my-key" -> "
def get_state():
"""Return JSON-serializable state. Symmetric keys are base64-encoded;
RSA private keys are PEM-encoded if cryptography is available."""
- serializable_keys = {}
- for kid, rec in _keys.items():
+ from ministack.core.responses import AccountScopedDict
+ serializable_keys = AccountScopedDict()
+ # Iterate _data directly to capture ALL accounts
+ for scoped_key, rec in _keys._data.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:
@@ -69,13 +71,15 @@ def get_state():
entry["_private_key_pem"] = base64.b64encode(pem).decode()
except Exception:
pass
- serializable_keys[kid] = entry
+ serializable_keys._data[scoped_key] = entry
return {"keys": serializable_keys, "aliases": _aliases}
def restore_state(data):
if data:
- for kid, entry in data.get("keys", {}).items():
+ from ministack.core.responses import AccountScopedDict
+ keys_data = data.get("keys", {})
+ def _restore_key_entry(entry):
if "_symmetric_key_b64" in entry:
entry["_symmetric_key"] = base64.b64decode(entry.pop("_symmetric_key_b64"))
if "_public_key_der_b64" in entry:
@@ -86,7 +90,14 @@ def restore_state(data):
entry["_private_key"] = serialization.load_pem_private_key(pem_bytes, password=None)
except Exception:
pass
- _keys[kid] = entry
+ if isinstance(keys_data, AccountScopedDict):
+ for scoped_key, entry in keys_data._data.items():
+ _restore_key_entry(entry)
+ _keys._data[scoped_key] = entry
+ else:
+ for kid, entry in keys_data.items():
+ _restore_key_entry(entry)
+ _keys[kid] = entry
_aliases.update(data.get("aliases", {}))
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 1eb4f88a..0fcef165 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -72,15 +72,17 @@ _poller_lock = threading.Lock()
def get_state():
"""Return JSON-serializable state. code_zip bytes are base64-encoded."""
- funcs = {}
- for name, func in _functions.items():
+ from ministack.core.responses import AccountScopedDict
+ funcs = AccountScopedDict()
+ # Iterate _data directly to capture ALL accounts, not just current request context
+ for scoped_key, func in _functions._data.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
+ funcs._data[scoped_key] = f
return {
"functions": funcs,
"layers": copy.deepcopy(_layers),
@@ -91,13 +93,24 @@ def get_state():
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
+ from ministack.core.responses import AccountScopedDict
+ funcs = data.get("functions", {})
+ if isinstance(funcs, AccountScopedDict):
+ for scoped_key, func in funcs._data.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._data[scoped_key] = func
+ else:
+ for name, func in funcs.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", {}))
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 59cb6d16..e5245bfc 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -82,11 +82,12 @@ _multipart_uploads = AccountScopedDict()
# ── 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():
+ # Persist bucket metadata without object bodies.
+ # Use _data directly to capture ALL accounts, not just the current one.
+ buckets_meta = AccountScopedDict()
+ for scoped_key, bkt in _buckets._data.items():
meta = {k: v for k, v in bkt.items() if k != "objects"}
- buckets_meta[name] = meta
+ buckets_meta._data[scoped_key] = meta
return {
"buckets_meta": copy.deepcopy(buckets_meta),
"bucket_versioning": copy.deepcopy(_bucket_versioning),
@@ -105,9 +106,17 @@ def get_state():
def restore_state(data):
if data:
- for name, meta in data.get("buckets_meta", {}).items():
- if name not in _buckets:
- _buckets[name] = {**meta, "objects": {}}
+ bm = data.get("buckets_meta", {})
+ if isinstance(bm, AccountScopedDict):
+ # Restore all accounts' buckets directly via _data
+ for scoped_key, meta in bm._data.items():
+ if scoped_key not in _buckets._data:
+ _buckets._data[scoped_key] = {**meta, "objects": {}}
+ else:
+ # Legacy plain-dict format (pre-multi-tenancy)
+ for name, meta in bm.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", {}))
@@ -2740,7 +2749,8 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):
def _persist_object(bucket: str, key: str, obj):
try:
- fpath = os.path.realpath(os.path.join(DATA_DIR, bucket, key))
+ account_id = get_account_id()
+ fpath = os.path.realpath(os.path.join(DATA_DIR, account_id, bucket, key))
if not fpath.startswith(os.path.realpath(DATA_DIR)):
logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)
return
@@ -2768,50 +2778,77 @@ def _load_persisted_data():
if not PERSIST or not os.path.isdir(DATA_DIR):
return
try:
- for bucket_name in os.listdir(DATA_DIR):
- bucket_path = os.path.join(DATA_DIR, bucket_name)
- if not os.path.isdir(bucket_path):
+ # Support both layouts:
+ # New: DATA_DIR/<account_id>/<bucket>/<key>
+ # Legacy: DATA_DIR/<bucket>/<key>
+ for entry in os.listdir(DATA_DIR):
+ entry_path = os.path.join(DATA_DIR, entry)
+ if not os.path.isdir(entry_path):
continue
- if bucket_name not in _buckets:
- _buckets[bucket_name] = {
- "created": now_iso(),
- "objects": {},
- "region": None,
- }
- bucket = _buckets[bucket_name]
- for dirpath, _dirnames, filenames in os.walk(bucket_path):
- for fname in filenames:
- if fname.endswith(".meta.json"):
- continue
- abs_path = os.path.join(dirpath, fname)
- key = os.path.relpath(abs_path, bucket_path)
- meta_path = abs_path + ".meta.json"
- with open(abs_path, "rb") as f:
- data = f.read()
- meta = {}
- if os.path.exists(meta_path):
- try:
- with open(meta_path) as mf:
- meta = json.load(mf)
- except Exception:
- pass
- bucket["objects"][key] = {
- "body": data,
- "content_type": meta.get(
- "content_type", "application/octet-stream"
- ),
- "content_encoding": meta.get("content_encoding"),
- "etag": meta.get("etag") or f'"{md5_hash(data)}"',
- "last_modified": meta.get("last_modified") or now_iso(),
- "size": len(data),
- "metadata": meta.get("metadata", {}),
- "preserved_headers": meta.get("preserved_headers", {}),
- }
+ # Detect if this entry is an account ID directory (12-digit or has bucket subdirs)
+ if entry.isdigit() and len(entry) == 12:
+ # New layout: entry is an account ID
+ _load_persisted_account(entry, entry_path)
+ else:
+ # Legacy layout: entry is a bucket name under default account
+ _load_persisted_bucket("000000000000", entry, entry_path)
logger.info("Loaded persisted S3 data from %s", DATA_DIR)
except Exception as e:
logger.warning("Failed to load persisted S3 data: %s", e)
+def _load_persisted_account(account_id, account_path):
+ """Load all buckets for a given account from disk."""
+ for bucket_name in os.listdir(account_path):
+ bucket_path = os.path.join(account_path, bucket_name)
+ if os.path.isdir(bucket_path):
+ _load_persisted_bucket(account_id, bucket_name, bucket_path)
+
+
+def _load_persisted_bucket(account_id, bucket_name, bucket_path):
+ """Load a single bucket's objects from disk into the correct account scope."""
+ # Skip empty directories (may be leftover from layout migration)
+ has_files = any(
+ not f.endswith(".meta.json") for _, _, files in os.walk(bucket_path) for f in files
+ )
+ if not has_files and not os.listdir(bucket_path):
+ return
+ scoped_key = (account_id, bucket_name)
+ if scoped_key not in _buckets._data:
+ _buckets._data[scoped_key] = {
+ "created": now_iso(),
+ "objects": {},
+ "region": None,
+ }
+ bucket = _buckets._data[scoped_key]
+ for dirpath, _dirnames, filenames in os.walk(bucket_path):
+ for fname in filenames:
+ if fname.endswith(".meta.json"):
+ continue
+ abs_path = os.path.join(dirpath, fname)
+ key = os.path.relpath(abs_path, bucket_path)
+ meta_path = abs_path + ".meta.json"
+ with open(abs_path, "rb") as f:
+ data = f.read()
+ meta = {}
+ if os.path.exists(meta_path):
+ try:
+ with open(meta_path) as mf:
+ meta = json.load(mf)
+ except Exception:
+ pass
+ bucket["objects"][key] = {
+ "body": data,
+ "content_type": meta.get("content_type", "application/octet-stream"),
+ "content_encoding": meta.get("content_encoding"),
+ "etag": meta.get("etag") or f'"{md5_hash(data)}"',
+ "last_modified": meta.get("last_modified") or now_iso(),
+ "size": len(data),
+ "metadata": meta.get("metadata", {}),
+ "preserved_headers": meta.get("preserved_headers", {}),
+ }
+
+
_load_persisted_data()
diff --git a/pyproject.toml b/pyproject.toml
index e4e2dded..f54beb9b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.56"
+version = "1.1.57"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index 743b6cfa..fb1442c4 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -349,6 +349,86 @@ def test_eventbridge_content_filter_prefix(eb, sqs):
msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
assert len(msgs2.get("Messages", [])) == 0
+def test_eventbridge_wildcard_detail_type(eb, sqs):
+ """EventBridge wildcard pattern matches detail-type field."""
+ bus_name = "qa-eb-wc-bus"
+ eb.create_event_bus(Name=bus_name)
+ q_url = sqs.create_queue(QueueName="qa-eb-wc-q")["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ eb.put_rule(
+ Name="qa-eb-wc-rule",
+ EventBusName=bus_name,
+ EventPattern=json.dumps({"detail-type": [{"wildcard": "*simple*"}]}),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule="qa-eb-wc-rule",
+ EventBusName=bus_name,
+ Targets=[{"Id": "t1", "Arn": q_arn}],
+ )
+ # Should match: detail-type contains "simple"
+ eb.put_events(
+ Entries=[{
+ "Source": "test-source",
+ "DetailType": "simple-detail",
+ "Detail": json.dumps({"key1": "value1"}),
+ "EventBusName": bus_name,
+ }]
+ )
+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
+ assert len(msgs.get("Messages", [])) == 1, "Wildcard *simple* should match 'simple-detail'"
+ # Should NOT match: detail-type does not contain "simple"
+ eb.put_events(
+ Entries=[{
+ "Source": "test-source",
+ "DetailType": "complex-detail",
+ "Detail": json.dumps({"key1": "value1"}),
+ "EventBusName": bus_name,
+ }]
+ )
+ msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
+ assert len(msgs2.get("Messages", [])) == 0, "Wildcard *simple* should not match 'complex-detail'"
+
+
+def test_eventbridge_wildcard_in_detail(eb, sqs):
+ """EventBridge wildcard pattern works inside detail fields too."""
+ bus_name = "qa-eb-wcd-bus"
+ eb.create_event_bus(Name=bus_name)
+ q_url = sqs.create_queue(QueueName="qa-eb-wcd-q")["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ eb.put_rule(
+ Name="qa-eb-wcd-rule",
+ EventBusName=bus_name,
+ EventPattern=json.dumps({"detail": {"env": [{"wildcard": "prod*"}]}}),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule="qa-eb-wcd-rule",
+ EventBusName=bus_name,
+ Targets=[{"Id": "t1", "Arn": q_arn}],
+ )
+ eb.put_events(
+ Entries=[{
+ "Source": "app",
+ "DetailType": "deploy",
+ "Detail": json.dumps({"env": "production"}),
+ "EventBusName": bus_name,
+ }]
+ )
+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
+ assert len(msgs.get("Messages", [])) == 1
+ eb.put_events(
+ Entries=[{
+ "Source": "app",
+ "DetailType": "deploy",
+ "Detail": json.dumps({"env": "staging"}),
+ "EventBusName": bus_name,
+ }]
+ )
+ msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
+ assert len(msgs2.get("Messages", [])) == 0
+
+
def test_eventbridge_anything_but_filter(eb, sqs):
"""EventBridge anything-but filter excludes specified values."""
bus_name = "qa-eb-anybut-bus"