Skip to content

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

fixing pending s3 issue on state (#426)

Nahuel Nucera256cf4203ac5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec0dcdd8..4d123f1a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,18 +7,31 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.3.9] — 2026-04-22
+
+### Fixed
+- **S3 bucket logging / accelerate / request-payment config never persisted** — `s3.get_state()` and `s3.restore_state()` only enumerated 11 of the 14 module-level `_bucket_*` dicts, so `_bucket_logging_config`, `_bucket_accelerate_config`, and `_bucket_request_payment_config` silently evaporated on warm boot. `GetBucketLogging` / `GetBucketAccelerateConfiguration` / `GetBucketRequestPayment` returned empty responses on restart even though the config was set pre-shutdown. Fixed by replacing the hand-maintained enumeration with a `_PERSISTED_BUCKET_DICTS` registry (one entry per global, driven by a single iteration in both functions), closing the entire class of "forgot to add the new dict to get_state/restore_state" bug. Reported by @whittin3.
+- **EC2 `tag:*` / `tag-key` / `tag-value` filters ignored on most `Describe*` calls** — instance tag filters landed in 1.3.8 (contributed by @costi) but the same gap existed on security groups, route tables, NAT gateways, network ACLs, flow logs, VPC peering connections, prefix lists, VPN gateways, and launch templates — each did its own inline filter logic and silently accepted every resource regardless of `tag:*`. Factored tag filter handling into a shared `_resource_matches_tag_filters` helper and wired it into every `Describe*` call that already parses filters. Also added `tag-value` (match by value across any key) and AWS-compatible wildcard support (`*` / `?`) to every tag filter. Reported by @costi.
+- **EC2 `DescribeImages` missing `RootDeviceName` + `BlockDeviceMappings`** — built-in stub AMIs returned `RootDeviceType: ebs` but omitted the root device name and block device mapping entirely, so Terraform's AWS provider errored with `finding Root Device Name for AMI` before ever reaching `RunInstances`. CLI `run-instances` was unaffected (doesn't consult these fields). Stubs now expose `/dev/xvda` for Linux AMIs and `/dev/sda1` for the Windows Server stub, with an 8 GB `gp2` EBS block device mapping; the Windows stub also now reports `Platform=windows`, matching AWS. Reported by @fatmoon.
+
+### Changed
+- **`_parse_filters` consumers share a single tag-matching helper** — the three `_matches_*_filters` functions (instances, VPCs, subnets) and 9 inline filter sites now all call `_resource_matches_tag_filters(resource_id, filters)` instead of re-implementing `tag:` handling per resource. New EC2 resource types need zero tag-filter code — the helper walks the resource's entry in `_tags` and short-circuits on the first failing tag predicate.
+- **ECS exited-container reaper** — `RunTask` spawned containers via `docker run -d` without `auto_remove`, so every short-lived task command (e.g. `echo`, `wget` probes) exited but left an `Exited (0)` container on the Docker daemon indefinitely. `StopTask` and `/_ministack/reset` only ever listed running containers, so the exited ones accumulated across sessions. A background daemon thread now sweeps exited `ministack=ecs` containers every `ECS_REAP_INTERVAL_SECONDS` (default 60), `reset()` now reaps exited containers alongside running ones, and the reaper starts lazily on first `RunTask` so no-docker install paths are unaffected.
+
+---
+
## [1.3.8] — 2026-04-21
### Added
-- **S3 `s3:TestEvent` on `PutBucketNotificationConfiguration`** — configuring bucket notifications now delivers a flat `s3:TestEvent` payload (no `Records` wrapper) to every SQS / SNS / Lambda destination, matching real AWS S3 behaviour so tooling that listens for the test event on bucket setup works locally. Contributed by @nigel-campbell (#416)
+- **S3 `s3:TestEvent` on `PutBucketNotificationConfiguration`** — configuring bucket notifications now delivers a flat `s3:TestEvent` payload (no `Records` wrapper) to every SQS / SNS / Lambda destination, matching real AWS S3 behaviour so tooling that listens for the test event on bucket setup works locally. Contributed by @nigel-campbell.
### Fixed
-- **Lambda persistence crash on warm start with any event source mapping** — `lambda_svc.restore_state()` called `_ensure_poller()` when restoring ESMs, but the module-level invocation ran at line 170 while `_ensure_poller` was defined ~3,500 lines later. Warm starts with `PERSIST_STATE=1` and an ESM in `lambda.json` raised `NameError: name '_ensure_poller' is not defined` on every Lambda request until the state file was deleted. The module-level load/restore is now at the bottom of the file, after every helper it may call. Reported by @whittin3. Fixes #412
-- **DynamoDB `SSEDescription` used the request shape instead of the response shape** — `CreateTable` stored the caller's `SSESpecification` (`Enabled`/`KMSMasterKeyId`) directly as the response `SSEDescription`, which is missing the `Status` field Terraform v6 waits on; `UpdateTable` silently ignored `SSESpecification`. Warm-boot `terraform apply` on any encrypted table hung forever with `unexpected state '', wanted target 'DISABLED, ENABLED'`. Fixed by converting spec → description (`Status`, `SSEType`, `KMSMasterKeyArn`) at create + update, plus a one-shot migration in `restore_state` for legacy persisted tables. Reported by @whittin3. Fixes #411
+- **Lambda persistence crash on warm start with any event source mapping** — `lambda_svc.restore_state()` called `_ensure_poller()` when restoring ESMs, but the module-level invocation ran at line 170 while `_ensure_poller` was defined ~3,500 lines later. Warm starts with `PERSIST_STATE=1` and an ESM in `lambda.json` raised `NameError: name '_ensure_poller' is not defined` on every Lambda request until the state file was deleted. The module-level load/restore is now at the bottom of the file, after every helper it may call. Reported by @whittin3.
+- **DynamoDB `SSEDescription` used the request shape instead of the response shape** — `CreateTable` stored the caller's `SSESpecification` (`Enabled`/`KMSMasterKeyId`) directly as the response `SSEDescription`, which is missing the `Status` field Terraform v6 waits on; `UpdateTable` silently ignored `SSESpecification`. Warm-boot `terraform apply` on any encrypted table hung forever with `unexpected state '', wanted target 'DISABLED, ENABLED'`. Fixed by converting spec → description (`Status`, `SSEType`, `KMSMasterKeyArn`) at create + update, plus a one-shot migration in `restore_state` for legacy persisted tables. Reported by @whittin3.
- **`test_s3_put_notification_sends_test_event` was flaky under parallel load** — background thread delivering `s3:TestEvent` raced the test's poll. `PutBucketNotification` now delivers the test event synchronously (matching AWS effective behaviour) before returning; removes the race and also fixes multi-tenant delivery where the worker thread lost the caller's account contextvar.
### Changed
-- **Hardened persisted-state restore across every service** — 35 service modules wrapped their module-level `load_state()` + `restore_state()` invocation in `try/except` so a corrupt or schema-incompatible `{service}.json` logs and continues with a fresh store instead of breaking the service at import. Audited every `restore_state` / `load_persisted_state` for forward references (0 other violators) and unsafe `data[key]` subscript accesses (all guarded). This closes the entire class of bug around #412.
+- **Hardened persisted-state restore across every service** — 35 service modules wrapped their module-level `load_state()` + `restore_state()` invocation in `try/except` so a corrupt or schema-incompatible `{service}.json` logs and continues with a fresh store instead of breaking the service at import. Audited every `restore_state` / `load_persisted_state` for forward references (0 other violators) and unsafe `data[key]` subscript accesses (all guarded).
---
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 336224b3..7fdd2fbd 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -511,19 +511,26 @@ def _reboot_instances(p):
# Images (AMIs) — stub
# ---------------------------------------------------------------------------
+# (ami_id, name, description, platform, root_device_name)
+# platform: "windows" or "" (Linux/Unix — matches AWS's empty-field behaviour)
+# root_device_name: Windows AMIs use /dev/sda1, Linux HVM uses /dev/xvda.
_STUB_AMIS = [
- ("ami-0abcdef1234567890", "amzn2-ami-hvm-2.0.20231116.0-x86_64-gp2", "Amazon Linux 2"),
- ("ami-0123456789abcdef0", "ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server", "Ubuntu 22.04"),
- ("ami-0fedcba9876543210", "Windows_Server-2022-English-Full-Base", "Windows Server 2022"),
+ ("ami-0abcdef1234567890", "amzn2-ami-hvm-2.0.20231116.0-x86_64-gp2", "Amazon Linux 2", "", "/dev/xvda"),
+ ("ami-0123456789abcdef0", "ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server", "Ubuntu 22.04", "", "/dev/xvda"),
+ ("ami-0fedcba9876543210", "Windows_Server-2022-English-Full-Base", "Windows Server 2022", "windows", "/dev/sda1"),
]
def _describe_images(p):
filter_ids = _parse_member_list(p, "ImageId")
items = ""
- for ami_id, name, desc in _STUB_AMIS:
+ for ami_id, name, desc, platform, root_device in _STUB_AMIS:
if filter_ids and ami_id not in filter_ids:
continue
+ # RootDeviceName + BlockDeviceMappings are required by Terraform's AWS
+ # provider on aws_instance — it resolves them from DescribeImages before
+ # RunInstances and fails with "finding Root Device Name for AMI" if absent.
+ platform_xml = f"<platform>{platform}</platform>" if platform else ""
items += f"""<item>
<imageId>{ami_id}</imageId>
<imageLocation>{name}</imageLocation>
@@ -534,7 +541,19 @@ def _describe_images(p):
<imageType>machine</imageType>
<name>{name}</name>
<description>{desc}</description>
+ {platform_xml}
<rootDeviceType>ebs</rootDeviceType>
+ <rootDeviceName>{root_device}</rootDeviceName>
+ <blockDeviceMapping>
+ <item>
+ <deviceName>{root_device}</deviceName>
+ <ebs>
+ <volumeSize>8</volumeSize>
+ <volumeType>gp2</volumeType>
+ <deleteOnTermination>true</deleteOnTermination>
+ </ebs>
+ </item>
+ </blockDeviceMapping>
<virtualizationType>hvm</virtualizationType>
<hypervisor>xen</hypervisor>
</item>"""
@@ -600,6 +619,8 @@ def _describe_security_groups(p):
for sg in _security_groups.values():
if filter_ids and sg["GroupId"] not in filter_ids:
continue
+ if not _resource_matches_tag_filters(sg["GroupId"], filters):
+ continue
vpc_filter = filters.get("vpc-id", [])
if vpc_filter and sg.get("VpcId", "") not in vpc_filter:
continue
@@ -808,6 +829,8 @@ def _describe_vpcs(p):
def _matches_vpc_filters(vpc, filters):
+ if not _resource_matches_tag_filters(vpc["VpcId"], filters):
+ return False
for name, vals in filters.items():
if name == "vpc-id":
if vpc["VpcId"] not in vals:
@@ -825,16 +848,6 @@ def _matches_vpc_filters(vpc, filters):
is_def = "true" if vpc["IsDefault"] else "false"
if is_def not in vals:
return False
- elif name.startswith("tag:"):
- tag_key = name[4:]
- tag_list = _tags.get(vpc["VpcId"], [])
- tag_val = next((t["Value"] for t in tag_list if t["Key"] == tag_key), None)
- if tag_val not in vals:
- return False
- elif name == "tag-key":
- tag_list = _tags.get(vpc["VpcId"], [])
- if not any(t["Key"] in vals for t in tag_list):
- return False
return True
@@ -1009,6 +1022,8 @@ def _describe_subnets(p):
def _matches_subnet_filters(subnet, filters):
+ if not _resource_matches_tag_filters(subnet["SubnetId"], filters):
+ return False
for name, vals in filters.items():
if name == "vpc-id":
if subnet["VpcId"] not in vals:
@@ -1023,16 +1038,6 @@ def _matches_subnet_filters(subnet, filters):
val = "true" if subnet.get("DefaultForAz") else "false"
if val not in vals:
return False
- elif name.startswith("tag:"):
- tag_key = name[4:]
- tag_list = _tags.get(subnet["SubnetId"], [])
- tag_val = next((t["Value"] for t in tag_list if t["Key"] == tag_key), None)
- if tag_val not in vals:
- return False
- elif name == "tag-key":
- tag_list = _tags.get(subnet["SubnetId"], [])
- if not any(t["Key"] in vals for t in tag_list):
- return False
return True
@@ -1219,6 +1224,8 @@ def _describe_route_tables(p):
for rtb in _route_tables.values():
if filter_ids and rtb["RouteTableId"] not in filter_ids:
continue
+ if not _resource_matches_tag_filters(rtb["RouteTableId"], filters):
+ continue
# Filter by association.route-table-association-id
assoc_filter = filters.get("association.route-table-association-id", [])
if assoc_filter:
@@ -2278,8 +2285,52 @@ def _parse_filters(params):
return filters
+def _glob_match(pattern: str, value: str) -> bool:
+ """AWS filter value match: exact when no wildcards, fnmatch glob otherwise.
+ AWS supports `*` (zero or more) and `?` (exactly one) in tag filter values.
+ """
+ if "*" in pattern or "?" in pattern:
+ import fnmatch
+ return fnmatch.fnmatchcase(value, pattern)
+ return pattern == value
+
+
+def _resource_matches_tag_filters(resource_id: str, filters: dict) -> bool:
+ """Apply AWS EC2 tag-related filters to any resource by id.
+
+ Supports:
+ tag:<key> — instance has a tag with this Key whose Value matches any
+ entry in `vals` (wildcards permitted per entry).
+ tag-key — instance has any tag whose Key matches any entry in `vals`.
+ tag-value — instance has any tag whose Value matches any entry in `vals`.
+
+ Returns True when no tag-related filter is present or every tag-related
+ filter passes. Non-tag filter names are ignored here (callers handle them).
+ Safe to call unconditionally — short-circuits on the first failing filter.
+ """
+ tag_list = None
+ for name, vals in filters.items():
+ if not (name.startswith("tag:") or name in ("tag-key", "tag-value")):
+ continue
+ if tag_list is None:
+ tag_list = _tags.get(resource_id, [])
+ if name.startswith("tag:"):
+ tag_key = name[4:]
+ actual = next((t["Value"] for t in tag_list if t["Key"] == tag_key), None)
+ if actual is None or not any(_glob_match(pat, actual) for pat in vals):
+ return False
+ elif name == "tag-key":
+ if not any(_glob_match(pat, t["Key"]) for t in tag_list for pat in vals):
+ return False
+ elif name == "tag-value":
+ if not any(_glob_match(pat, t.get("Value", "")) for t in tag_list for pat in vals):
+ return False
+ return True
+
+
def _matches_filters(inst, filters):
- tag_list = _tags.get(inst["InstanceId"], [])
+ if not _resource_matches_tag_filters(inst["InstanceId"], filters):
+ return False
for name, vals in filters.items():
if name == "instance-state-name":
if inst["State"]["Name"] not in vals:
@@ -2290,14 +2341,6 @@ def _matches_filters(inst, filters):
elif name == "image-id":
if inst["ImageId"] not in vals:
return False
- elif name.startswith("tag:"):
- tag_key = name[4:]
- tag_val = next((t["Value"] for t in tag_list if t["Key"] == tag_key), None)
- if tag_val not in vals:
- return False
- elif name == "tag-key":
- if not any(t["Key"] in vals for t in tag_list):
- return False
return True
@@ -2480,6 +2523,8 @@ def _describe_nat_gateways(params):
for nat in _nat_gateways.values():
if ids and nat["NatGatewayId"] not in ids:
continue
+ if not _resource_matches_tag_filters(nat["NatGatewayId"], filters):
+ continue
if filters.get("state") and nat["State"] not in filters["state"]:
continue
if filters.get("vpc-id") and nat["VpcId"] not in filters["vpc-id"]:
@@ -2551,6 +2596,8 @@ def _describe_network_acls(params):
for acl in _network_acls.values():
if ids and acl["NetworkAclId"] not in ids:
continue
+ if not _resource_matches_tag_filters(acl["NetworkAclId"], filters):
+ continue
if filters.get("vpc-id") and acl["VpcId"] not in filters["vpc-id"]:
continue
if filters.get("default"):
@@ -2691,6 +2738,8 @@ def _describe_flow_logs(params):
for fl in _flow_logs.values():
if ids and fl["FlowLogId"] not in ids:
continue
+ if not _resource_matches_tag_filters(fl["FlowLogId"], filters):
+ continue
if filters.get("resource-id") and fl["ResourceId"] not in filters["resource-id"]:
continue
items += f"""<item>
@@ -2767,6 +2816,8 @@ def _describe_vpc_peering_connections(params):
for pcx in _vpc_peering.values():
if ids and pcx["VpcPeeringConnectionId"] not in ids:
continue
+ if not _resource_matches_tag_filters(pcx["VpcPeeringConnectionId"], filters):
+ continue
if filters.get("status-code") and pcx["Status"]["Code"] not in filters["status-code"]:
continue
items += f"""<item>
@@ -3022,6 +3073,8 @@ def _describe_prefix_lists(p):
for pl in _prefix_lists.values():
if filter_ids and pl["PrefixListId"] not in filter_ids:
continue
+ if not _resource_matches_tag_filters(pl["PrefixListId"], filters):
+ continue
if filters.get("prefix-list-name") and pl.get("PrefixListName", "") not in filters["prefix-list-name"]:
continue
entries = "".join(f"<item><cidr>{e['Cidr']}</cidr></item>" for e in pl.get("Entries", []))
@@ -3066,6 +3119,8 @@ def _describe_managed_prefix_lists(p):
for pl in _prefix_lists.values():
if filter_ids and pl["PrefixListId"] not in filter_ids:
continue
+ if not _resource_matches_tag_filters(pl["PrefixListId"], filters):
+ continue
if filters.get("prefix-list-name") and pl.get("PrefixListName", "") not in filters["prefix-list-name"]:
continue
items += _prefix_list_xml(pl)
@@ -3161,6 +3216,8 @@ def _describe_vpn_gateways(p):
for vgw in _vpn_gateways.values():
if filter_ids and vgw["VpnGatewayId"] not in filter_ids:
continue
+ if not _resource_matches_tag_filters(vgw["VpnGatewayId"], filters):
+ continue
if filters.get("attachment.vpc-id"):
vpc_ids = [a["VpcId"] for a in vgw.get("Attachments", [])]
if not any(v in vpc_ids for v in filters["attachment.vpc-id"]):
@@ -3921,6 +3978,8 @@ def _describe_launch_templates(p):
continue
if lt_names and lt["LaunchTemplateName"] not in lt_names:
continue
+ if not _resource_matches_tag_filters(lt["LaunchTemplateId"], filters):
+ continue
if filters:
if "launch-template-name" in filters:
if lt["LaunchTemplateName"] not in filters["launch-template-name"]:
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 94cc2812..c2f48cac 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -27,6 +27,7 @@ import copy
import json
import logging
import os
+import threading
import time
from ministack.core.persistence import load_state
@@ -55,6 +56,46 @@ _capacity_providers = AccountScopedDict()
_docker = None
+# ECS exited-container reaper. Every ministack=ecs container we start via
+# RunTask lingers after its command exits (docker-py detach=True without
+# auto_remove leaves Exited containers on the daemon). StopTask and reset
+# clean what they know about, but short-lived commands (echo, wget probes)
+# exit on their own and accumulate indefinitely. A background daemon thread
+# sweeps them every ECS_REAP_INTERVAL_SECONDS (default 60).
+_ECS_REAP_INTERVAL = int(os.environ.get("ECS_REAP_INTERVAL_SECONDS", "60"))
+_ecs_reaper_started = False
+_ecs_reaper_lock = threading.Lock()
+
+
+def _reap_exited_containers():
+ docker_client = _get_docker()
+ if not docker_client:
+ return
+ # all=True includes exited containers; reset() uses list() (running only),
+ # so this complements — and overlaps harmlessly — with the reset path.
+ for c in docker_client.containers.list(all=True, filters={"label": "ministack=ecs"}):
+ if c.status in ("exited", "dead", "created"):
+ try:
+ c.remove(v=True, force=True)
+ except Exception:
+ pass
+
+
+def _ensure_ecs_reaper_thread():
+ global _ecs_reaper_started
+ with _ecs_reaper_lock:
+ if _ecs_reaper_started:
+ return
+ def _loop():
+ while True:
+ time.sleep(_ECS_REAP_INTERVAL)
+ try:
+ _reap_exited_containers()
+ except Exception as exc:
+ logger.debug("ECS reaper iteration error: %s", exc)
+ threading.Thread(target=_loop, daemon=True, name="ministack-ecs-reaper").start()
+ _ecs_reaper_started = True
+
# ── Persistence ────────────────────────────────────────────
@@ -879,6 +920,7 @@ def _run_task(data):
docker_client = _get_docker()
if docker_client and td:
+ _ensure_ecs_reaper_thread()
# Detect the Docker network Ministack is running on,
# so ECS containers can reach sibling services (S3, etc.)
ecs_network = None
@@ -1624,13 +1666,16 @@ _ACTION_MAP = {
def reset():
docker_client = _get_docker()
if docker_client:
- # Stop containers by label instead of chasing individual IDs —
- # avoids slow 404s for containers that were already removed.
+ # Stop + remove every ministack=ecs container (running OR exited).
+ # Including exited ones matters because short-lived commands
+ # (echo, wget probes) leave Exited containers behind that otherwise
+ # only the background reaper would remove.
try:
- for c in docker_client.containers.list(filters={"label": "ministack=ecs"}):
+ for c in docker_client.containers.list(all=True, filters={"label": "ministack=ecs"}):
try:
- c.stop(timeout=2)
- c.remove(v=True)
+ if c.status == "running":
+ c.stop(timeout=2)
+ c.remove(v=True, force=True)
except Exception:
pass
except Exception:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 261d79ff..aa64f2ba 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -83,6 +83,31 @@ _multipart_uploads = AccountScopedDict()
# ── Persistence (metadata only — object bodies are NOT persisted here) ────
+# Module-level registry of per-bucket dicts that round-trip through s3.json.
+# One entry per module global: adding a new _bucket_* dict means one line here,
+# not two separate edits in get_state/restore_state. Must sit below every
+# _bucket_* declaration above — the dict literal holds live references.
+# Excludes _buckets (has bespoke objects-stripping + legacy fallback) and
+# per-bucket keys like _ownership_controls / _public_access_block that live
+# on _buckets[name] and travel with buckets_meta.
+_PERSISTED_BUCKET_DICTS = {
+ "bucket_versioning": _bucket_versioning,
+ "bucket_notifications": _bucket_notifications,
+ "bucket_tags": _bucket_tags,
+ "bucket_policies": _bucket_policies,
+ "bucket_encryption": _bucket_encryption,
+ "bucket_lifecycle": _bucket_lifecycle,
+ "bucket_cors": _bucket_cors,
+ "bucket_acl": _bucket_acl,
+ "bucket_websites": _bucket_websites,
+ "bucket_logging_config": _bucket_logging_config,
+ "bucket_accelerate_config": _bucket_accelerate_config,
+ "bucket_request_payment_config": _bucket_request_payment_config,
+ "bucket_object_lock": _bucket_object_lock,
+ "bucket_replication": _bucket_replication,
+}
+
+
def get_state():
# Persist bucket metadata without object bodies.
# Use _data directly to capture ALL accounts, not just the current one.
@@ -90,46 +115,28 @@ def get_state():
for scoped_key, bkt in _buckets._data.items():
meta = {k: v for k, v in bkt.items() if k != "objects"}
buckets_meta._data[scoped_key] = 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),
- }
+ state = {"buckets_meta": copy.deepcopy(buckets_meta)}
+ for key, d in _PERSISTED_BUCKET_DICTS.items():
+ state[key] = copy.deepcopy(d)
+ return state
def restore_state(data):
- if data:
- 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", {}))
- _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", {}))
+ if not data:
+ return
+ 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": {}}
+ for key, d in _PERSISTED_BUCKET_DICTS.items():
+ d.update(data.get(key, {}))
try:
diff --git a/pyproject.toml b/pyproject.toml
index 844596f9..c4bab3cb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.8"
+version = "1.3.9"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index afd1a665..ee1bcd66 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -88,6 +88,26 @@ def test_ec2_describe_images(ec2):
assert len(resp["Images"]) >= 1
assert all("ImageId" in img for img in resp["Images"])
+
+def test_ec2_describe_images_has_root_device_and_block_mappings(ec2):
+ # Terraform's AWS provider resolves these before aws_instance creation;
+ # absence produced "finding Root Device Name for AMI" and blocked apply.
+ resp = ec2.describe_images(ImageIds=["ami-0abcdef1234567890"])
+ img = resp["Images"][0]
+ assert img["RootDeviceType"] == "ebs"
+ assert img["RootDeviceName"] == "/dev/xvda"
+ bdms = img["BlockDeviceMappings"]
+ assert bdms and bdms[0]["DeviceName"] == "/dev/xvda"
+ assert bdms[0]["Ebs"]["VolumeSize"] == 8
+ assert bdms[0]["Ebs"]["VolumeType"] == "gp2"
+
+ # Windows AMI uses /dev/sda1 and exposes Platform=windows.
+ resp = ec2.describe_images(ImageIds=["ami-0fedcba9876543210"])
+ win = resp["Images"][0]
+ assert win["RootDeviceName"] == "/dev/sda1"
+ assert win.get("Platform") == "windows"
+ assert win["BlockDeviceMappings"][0]["DeviceName"] == "/dev/sda1"
+
def test_ec2_security_group_crud(ec2):
sg_id = ec2.create_security_group(GroupName="qa-ec2-sg", Description="test sg")["GroupId"]
assert sg_id.startswith("sg-")
@@ -258,6 +278,101 @@ def test_ec2_describe_instances_tag_filter_excludes_untagged(ec2):
ec2.terminate_instances(InstanceIds=[untagged_id, tagged_id])
+def test_ec2_describe_instances_tag_filter_wildcard(ec2):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ tagged = ec2.run_instances(
+ ImageId="ami-wild",
+ MinCount=1,
+ MaxCount=1,
+ TagSpecifications=[{
+ "ResourceType": "instance",
+ "Tags": [{"Key": "Env", "Value": f"prod-{suffix}"}],
+ }],
+ )["Instances"][0]["InstanceId"]
+ other = ec2.run_instances(
+ ImageId="ami-wild",
+ MinCount=1,
+ MaxCount=1,
+ TagSpecifications=[{
+ "ResourceType": "instance",
+ "Tags": [{"Key": "Env", "Value": f"dev-{suffix}"}],
+ }],
+ )["Instances"][0]["InstanceId"]
+
+ resp = ec2.describe_instances(Filters=[{"Name": "tag:Env", "Values": [f"prod-{suffix[:4]}*"]}])
+ ids = [i["InstanceId"] for r in resp["Reservations"] for i in r["Instances"]]
+ assert tagged in ids
+ assert other not in ids
+ ec2.terminate_instances(InstanceIds=[tagged, other])
+
+
+def test_ec2_describe_instances_tag_value_and_tag_key_filters(ec2):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ match_v = ec2.run_instances(
+ ImageId="ami-tv",
+ MinCount=1, MaxCount=1,
+ TagSpecifications=[{"ResourceType": "instance",
+ "Tags": [{"Key": f"anykey-{suffix}", "Value": f"payload-{suffix}"}]}],
+ )["Instances"][0]["InstanceId"]
+ other_v = ec2.run_instances(
+ ImageId="ami-tv",
+ MinCount=1, MaxCount=1,
+ TagSpecifications=[{"ResourceType": "instance",
+ "Tags": [{"Key": f"anykey-{suffix}", "Value": f"nope-{suffix}"}]}],
+ )["Instances"][0]["InstanceId"]
+
+ resp = ec2.describe_instances(Filters=[{"Name": "tag-value", "Values": [f"payload-{suffix}"]}])
+ ids = [i["InstanceId"] for r in resp["Reservations"] for i in r["Instances"]]
+ assert match_v in ids
+ assert other_v not in ids
+
+ resp = ec2.describe_instances(Filters=[{"Name": "tag-key", "Values": [f"anykey-{suffix}"]}])
+ ids = [i["InstanceId"] for r in resp["Reservations"] for i in r["Instances"]]
+ assert match_v in ids and other_v in ids
+
+ ec2.terminate_instances(InstanceIds=[match_v, other_v])
+
+
+def test_ec2_describe_vpcs_tag_filter(ec2):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ tagged_vpc = ec2.create_vpc(
+ CidrBlock="10.99.0.0/16",
+ TagSpecifications=[{"ResourceType": "vpc",
+ "Tags": [{"Key": "Team", "Value": f"core-{suffix}"}]}],
+ )["Vpc"]["VpcId"]
+ untagged_vpc = ec2.create_vpc(CidrBlock="10.98.0.0/16")["Vpc"]["VpcId"]
+ try:
+ resp = ec2.describe_vpcs(Filters=[{"Name": "tag:Team", "Values": [f"core-{suffix}"]}])
+ ids = [v["VpcId"] for v in resp["Vpcs"]]
+ assert tagged_vpc in ids
+ assert untagged_vpc not in ids
+ finally:
+ ec2.delete_vpc(VpcId=tagged_vpc)
+ ec2.delete_vpc(VpcId=untagged_vpc)
+
+
+def test_ec2_describe_security_groups_tag_filter(ec2):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ vpc = ec2.create_vpc(CidrBlock="10.97.0.0/16")["Vpc"]["VpcId"]
+ try:
+ tagged_sg = ec2.create_security_group(
+ GroupName=f"tagged-{suffix}", Description="x", VpcId=vpc,
+ TagSpecifications=[{"ResourceType": "security-group",
+ "Tags": [{"Key": "Scope", "Value": f"svc-{suffix}"}]}],
+ )["GroupId"]
+ untagged_sg = ec2.create_security_group(
+ GroupName=f"untagged-{suffix}", Description="y", VpcId=vpc,
+ )["GroupId"]
+ resp = ec2.describe_security_groups(Filters=[{"Name": "tag:Scope", "Values": [f"svc-{suffix}"]}])
+ ids = [s["GroupId"] for s in resp["SecurityGroups"]]
+ assert tagged_sg in ids
+ assert untagged_sg not in ids
+ finally:
+ ec2.delete_security_group(GroupId=tagged_sg)
+ ec2.delete_security_group(GroupId=untagged_sg)
+ ec2.delete_vpc(VpcId=vpc)
+
+
def test_ec2_modify_vpc_attribute(ec2):
vpc_id = ec2.create_vpc(CidrBlock="10.10.0.0/16")["Vpc"]["VpcId"]
ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={"Value": True})
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 7453ace4..f05a3a6e 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -332,6 +332,34 @@ def test_ministack_persist_s3_metadata_roundtrip():
_s3._buckets.pop("persist-bkt")
_s3._bucket_versioning.pop("persist-bkt")
+def test_ministack_persist_s3_logging_accelerate_request_payment_roundtrip():
+ # Regression for #424 + the two adjacent landmines: logging, accelerate,
+ # and request-payment configs must all survive save/restore. Previously
+ # _bucket_logging_config / _bucket_accelerate_config / _bucket_request_payment_config
+ # were never enumerated in get_state/restore_state, so they silently
+ # evaporated on warm boot. Now driven by _PERSISTED_BUCKET_DICTS.
+ from ministack.services import s3 as _s3
+ _s3._buckets["persist-log-bkt"] = {"created": "2025-01-01T00:00:00Z", "objects": {}, "region": "us-east-1"}
+ _s3._bucket_logging_config["persist-log-bkt"] = "<BucketLoggingStatus><LoggingEnabled><TargetBucket>tgt</TargetBucket></LoggingEnabled></BucketLoggingStatus>"
+ _s3._bucket_accelerate_config["persist-log-bkt"] = "<AccelerateConfiguration><Status>Enabled</Status></AccelerateConfiguration>"
+ _s3._bucket_request_payment_config["persist-log-bkt"] = "<RequestPaymentConfiguration><Payer>Requester</Payer></RequestPaymentConfiguration>"
+ state = _s3.get_state()
+ assert "bucket_logging_config" in state
+ assert "bucket_accelerate_config" in state
+ assert "bucket_request_payment_config" in state
+ _s3._buckets.pop("persist-log-bkt")
+ _s3._bucket_logging_config.pop("persist-log-bkt")
+ _s3._bucket_accelerate_config.pop("persist-log-bkt")
+ _s3._bucket_request_payment_config.pop("persist-log-bkt")
+ _s3.restore_state(state)
+ assert "TargetBucket>tgt" in _s3._bucket_logging_config["persist-log-bkt"]
+ assert "Enabled" in _s3._bucket_accelerate_config["persist-log-bkt"]
+ assert "Requester" in _s3._bucket_request_payment_config["persist-log-bkt"]
+ _s3._buckets.pop("persist-log-bkt")
+ _s3._bucket_logging_config.pop("persist-log-bkt")
+ _s3._bucket_accelerate_config.pop("persist-log-bkt")
+ _s3._bucket_request_payment_config.pop("persist-log-bkt")
+
def test_ministack_persist_lambda_roundtrip():
from ministack.services import lambda_svc as _lam
_lam._functions["persist-fn"] = {