Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Fix/multi sdk regression extended v1.2.6 (#274)
Nahuel Nucera4fbacd162622
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9bc6091e..f17f0428 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,38 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.2.6] — 2026-04-12++### Fixed+- **EFS timestamp format** — `CreationTime` now returns integer epoch seconds instead of ISO string, fixing Java SDK v2 unmarshalling errors.+- **ECS timestamps** — `createdAt` and other timestamp fields now return integer epoch seconds instead of floats with sub-second precision.+- **DynamoDB `X-Amz-Crc32` header** — all DynamoDB responses now include the CRC32 checksum header, fixing Go SDK v2 `failed to close HTTP response body` warnings.+- **EC2 DescribeInternetGateways not-found** — returns `InvalidInternetGatewayID.NotFound` for nonexistent IDs.+- **EC2 CreateVpc CIDR validation** — rejects invalid CIDR blocks with `InvalidParameterValue`.+- **EC2 duplicate security group rule** — `AuthorizeSecurityGroupIngress` returns `InvalidPermission.Duplicate` for existing rules.+- **EC2 CreateVolume/CreateSnapshot TagSpecifications** — tags specified in `TagSpecifications` are now persisted.+- **ElastiCache CreateCacheSubnetGroup** — `DescribeCacheSubnetGroups` now returns the `Subnets` list with subnet identifiers and availability zones.+- **SNS error code** — `GetTopicAttributes`, `Publish`, and other operations on nonexistent topics now return `NotFound` instead of `NotFoundException`, matching real AWS.+- **LocalStack init script path compatibility** — now supports `/etc/localstack/init/ready.d/` in addition to `/docker-entrypoint-initaws.d/ready.d/` for drop-in LocalStack replacement. Contributed by @AdigaAkhil (#271)+- **CloudWatch error response protocol mismatch** — error responses now match the request protocol (JSON errors for JSON requests, CBOR errors for CBOR requests). Previously, JSON-protocol requests received CBOR-encoded errors causing boto3 `UnicodeDecodeError`.+- **AppSync apiId length** — `CreateGraphQLApi` now generates 26-character alphanumeric IDs matching real AWS format. Previously 8 characters, which broke boto3 ARN validation for tag operations.+- **EC2 CreateTags persistence** — tags applied via `CreateTags` now appear in `DescribeVpcs`, `DescribeSubnets`, `DescribeSecurityGroups`, and `DescribeInternetGateways`. Previously returned empty `<tagSet/>`.+- **EC2 RunInstances TagSpecifications** — tags specified in `TagSpecifications` with `ResourceType=instance` are now persisted and returned in `DescribeInstances`.+- **EC2 Describe not-found errors** — `DescribeVpcs`, `DescribeSubnets`, `DescribeSecurityGroups`, `DescribeKeyPairs`, `DescribeInstances`, `DescribeVolumes`, `DescribeSnapshots` now return proper AWS error codes (`InvalidVpcID.NotFound`, etc.) when specific IDs are requested but don't exist.+- **EFS not-found errors** — `DescribeFileSystems` and `DescribeMountTargets` now return `FileSystemNotFound` / `MountTargetNotFound` for nonexistent IDs.+- **ELBv2 not-found errors** — `DescribeLoadBalancers`, `DescribeTargetGroups` return proper errors for nonexistent ARNs/names. `DeleteListener`, `DeleteTargetGroup` return errors for nonexistent ARNs.+- **ElastiCache not-found errors** — `DescribeCacheSubnetGroups`, `DeleteCacheSubnetGroup`, `DescribeCacheParameterGroups`, `DeleteCacheParameterGroup` now return proper `CacheSubnetGroupNotFoundFault` / `CacheParameterGroupNotFound` errors.+- **Glue validation** — `CreateTable` rejects nonexistent database, `CreateCrawler` rejects duplicate names, `DeleteTable` / `DeleteConnection` return `EntityNotFoundException` for nonexistent resources.+- **CloudFront CallerReference idempotency** — `CreateDistribution` with a duplicate `CallerReference` returns the existing distribution instead of creating a duplicate.+- **WAFv2 LockToken enforcement** — `UpdateWebACL` validates `LockToken` and returns `WAFOptimisticLockException` for stale tokens.+- **WAFv2 duplicate name** — `CreateWebACL` rejects duplicate names within the same scope with `WAFDuplicateItemException`.+- **ServiceDiscovery duplicate namespace** — `CreateHttpNamespace` rejects duplicate names with `NamespaceAlreadyExists`.+- **AutoScaling DescribePolicies** — response now includes `AdjustmentType`, `ScalingAdjustment`, and `Cooldown` fields.+- **ECS TagResource validation** — rejects nonexistent resource ARNs with `InvalidParameterException`.+- **EC2 DescribeVpcs filters** — filters parameter (`owner-id`, `vpc-id`, `cidr`, `state`, `is-default`, `tag:*`) now applied correctly. Previously silently ignored.++---+## [1.2.5] — 2026-04-12### Fixeddiff --git a/ministack/app.py b/ministack/app.pyindex 67330707..088625dd 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -578,6 +578,7 @@ async def _send_response(send, status, headers, body):await send({"type": "http.response.body","body": body_bytes,+ "more_body": False,})diff --git a/ministack/services/alb.py b/ministack/services/alb.pyindex f05484ad..af42d8b5 100644--- a/ministack/services/alb.py+++ b/ministack/services/alb.py@@ -374,8 +374,12 @@ def _describe_lbs(params):results = list(_lbs.values())if arn_filter:results = [lb for lb in results if lb["LoadBalancerArn"] in arn_filter]+ if not results:+ return _error("LoadBalancerNotFound", "One or more load balancers not found", 400)if name_filter:results = [lb for lb in results if lb["LoadBalancerName"] in name_filter]+ if not results:+ return _error("LoadBalancerNotFound", "One or more load balancers not found", 400)return _xml(200, "DescribeLoadBalancers",f"<LoadBalancers>{''.join(_lb_xml(lb) for lb in results)}</LoadBalancers>")@@ -469,6 +473,8 @@ def _describe_tgs(params):results = list(_tgs.values())if arn_filter:results = [tg for tg in results if tg["TargetGroupArn"] in arn_filter]+ if not results:+ return _error("TargetGroupNotFound", "One or more target groups not found", 400)if name_filter:results = [tg for tg in results if tg["TargetGroupName"] in name_filter]if lb_arn:@@ -506,6 +512,8 @@ def _modify_tg(params):def _delete_tg(params):arn = _p(params, "TargetGroupArn")+ if arn not in _tgs:+ return _error("TargetGroupNotFound", f"Target group '{arn}' not found", 400)_tgs.pop(arn, None)_targets.pop(arn, None)_tg_attrs.pop(arn, None)@@ -614,6 +622,8 @@ def _modify_listener(params):def _delete_listener(params):arn = _p(params, "ListenerArn")+ if arn not in _listeners:+ return _error("ListenerNotFound", f"Listener '{arn}' not found", 400)_listeners.pop(arn, None)_tags.pop(arn, None)for rarn in [k for k, v in list(_rules.items()) if v.get("ListenerArn") == arn]:diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex bae9489c..68893f64 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -76,7 +76,7 @@ def _json(status, body):# ---------------------------------------------------------------------------def _create_graphql_api(body):- api_id = new_uuid()[:8]+ api_id = new_uuid().replace("-", "")[:26]name = body.get("name", "")auth_type = body.get("authenticationType", "API_KEY")additional_auth = body.get("additionalAuthenticationProviders", [])diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.pyindex 4bc6fab4..c149aad4 100644--- a/ministack/services/autoscaling.py+++ b/ministack/services/autoscaling.py@@ -292,6 +292,9 @@ def _describe_policies(p):f"<PolicyName>{pol['PolicyName']}</PolicyName>"f"<AutoScalingGroupName>{pol['AutoScalingGroupName']}</AutoScalingGroupName>"f"<PolicyType>{pol['PolicyType']}</PolicyType>"+ f"<AdjustmentType>{pol.get('AdjustmentType', '')}</AdjustmentType>"+ f"<ScalingAdjustment>{pol.get('ScalingAdjustment', 0)}</ScalingAdjustment>"+ f"<Cooldown>{pol.get('Cooldown', 300)}</Cooldown>"f"</member>")return _xml(200, "DescribePoliciesResponse",f"<DescribePoliciesResult><ScalingPolicies>{members}</ScalingPolicies></DescribePoliciesResult>")diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex 297fd657..d6bec38b 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -324,8 +324,15 @@ def _create_distribution(headers, body):if config_el is None:return _error("MalformedXML", "The XML document is malformed.", 400)- if not _text(config_el, "CallerReference"):+ caller_ref = _text(config_el, "CallerReference")+ if not caller_ref:return _error("InvalidArgument", "CallerReference is required.", 400)+ # CallerReference idempotency — return existing distribution if CallerReference matches+ for existing in _distributions.values():+ if existing.get("CallerReference") == caller_ref:+ def build(root, _dist=existing):+ _build_distribution_xml(root, _dist)+ return _xml_response("Distribution", build, status=200, extra_headers={"ETag": existing["ETag"]})if _find(config_el, "Origins") is None:return _error("InvalidArgument", "Origins is required.", 400)if _find(config_el, "DefaultCacheBehavior") is None:@@ -342,6 +349,7 @@ def _create_distribution(headers, body):"DomainName": f"{dist_id}.cloudfront.net","LastModifiedTime": now,"ETag": etag,+ "CallerReference": caller_ref,"config_xml": tostring(config_el, encoding="unicode"),"enabled": _get_enabled(config_el),}diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex 4f571264..1dca49c0 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -293,7 +293,7 @@ async def handle_request(method, path, headers, body, query_params):handler = handlers.get(action)if not handler:return _error(- "InvalidAction", f"Unknown action: {action}", 400, is_cbor or is_json+ "InvalidAction", f"Unknown action: {action}", 400, use_json=is_json, use_cbor=is_cbor)return handler(params, cbor_data, is_cbor, is_json)@@ -1098,7 +1098,7 @@ def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):alarm = _alarms.get(name) or _composite_alarms.get(name)if not alarm:return _error(- "ResourceNotFound", f"Alarm {name} not found", 404, is_cbor or is_json+ "ResourceNotFound", f"Alarm {name} not found", 404, use_json=is_json, use_cbor=is_cbor)old_state = alarm["StateValue"]@@ -1217,7 +1217,7 @@ def _put_dashboard(params, cbor_data, is_cbor, is_json=False):"InvalidParameterValue","DashboardName is required",400,- is_cbor or is_json,+ use_json=is_json, use_cbor=is_cbor,)_dashboards[name] = {@@ -1251,7 +1251,7 @@ def _get_dashboard(params, cbor_data, is_cbor, is_json=False):"ResourceNotFound",f"Dashboard {name} does not exist",404,- is_cbor or is_json,+ use_json=is_json, use_cbor=is_cbor,)if is_cbor:@@ -1386,18 +1386,18 @@ def _xml(status, root_tag, inner):return status, {"Content-Type": "application/xml"}, body-def _error(code, message, status, use_json=False):- if use_json:+def _error(code, message, status, use_json=False, use_cbor=False):+ if use_cbor:try:import cbor2-body = cbor2.dumps({"__type": code, "message": message})- return status, {"Content-Type": "application/cbor"}, body- except Exception:+ return status, {"Content-Type": "application/cbor", "smithy-protocol": "rpc-v2-cbor"}, body+ except ImportError:pass+ if use_json or use_cbor:return (status,- {"Content-Type": "application/json"},+ {"Content-Type": "application/x-amz-json-1.0"},json.dumps({"__type": code, "message": message}).encode(),)body = (diff --git a/ministack/services/codebuild.py b/ministack/services/codebuild.pyindex f988674f..f87f484f 100644--- a/ministack/services/codebuild.py+++ b/ministack/services/codebuild.py@@ -70,7 +70,7 @@ def _build_id(project_name):def _make_build_record(project, build_id, source_version=None):"""Create a build record that immediately shows SUCCEEDED."""- now = time.time()+ now = int(time.time())return {"id": build_id,"arn": _build_arn(build_id),@@ -151,7 +151,7 @@ def _create_project(data):return error_response_json("ResourceAlreadyExistsException",f"Project already exists: {name}", 400)- now = time.time()+ now = int(time.time())project = {"name": name,"arn": _project_arn(name),diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 3701cb2d..5cda9746 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -200,7 +200,12 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, quehandler = handlers.get(action)if not handler:return error_response_json("UnknownOperationException", f"Unknown operation: {action}", 400)- return handler(data)+ status, resp_headers, resp_body = handler(data)+ # Add CRC32 checksum — Go SDK v2 DynamoDB client validates this on Close()+ import zlib+ body_bytes = resp_body if isinstance(resp_body, bytes) else resp_body.encode("utf-8")+ resp_headers["x-amz-crc32"] = str(zlib.crc32(body_bytes) & 0xFFFFFFFF)+ return status, resp_headers, resp_body# ---------------------------------------------------------------------------diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 76435f89..a156c78f 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -316,6 +316,23 @@ def _run_instances(p):}created.append(_instances[instance_id])+ # Process TagSpecifications+ i = 1+ while _p(p, f"TagSpecification.{i}.ResourceType"):+ rtype = _p(p, f"TagSpecification.{i}.ResourceType")+ spec_tags = []+ j = 1+ while _p(p, f"TagSpecification.{i}.Tag.{j}.Key"):+ spec_tags.append({+ "Key": _p(p, f"TagSpecification.{i}.Tag.{j}.Key"),+ "Value": _p(p, f"TagSpecification.{i}.Tag.{j}.Value", ""),+ })+ j += 1+ if rtype == "instance" and spec_tags:+ for inst in created:+ _tags[inst["InstanceId"]] = spec_tags[:]+ i += 1+items = "".join(_instance_xml(i) for i in created)inner = f"""<instancesSet>{items}</instancesSet><reservationId>r-{new_uuid().replace('-','')[:17]}</reservationId>@@ -335,6 +352,11 @@ def _describe_instances(p):for k in stale:_instances.pop(k, None)+ if filter_ids:+ for iid in filter_ids:+ if iid not in _instances:+ return _error("InvalidInstanceID.NotFound", f"The instance ID '{iid}' does not exist", 400)+results = []for inst in _instances.values():if filter_ids and inst["InstanceId"] not in filter_ids:@@ -525,6 +547,10 @@ def _delete_security_group(p):def _describe_security_groups(p):filter_ids = _parse_member_list(p, "GroupId")filters = _parse_filters(p)+ if filter_ids:+ for gid in filter_ids:+ if gid not in _security_groups:+ return _error("InvalidGroup.NotFound", f"The security group '{gid}' does not exist", 400)items = ""for sg in _security_groups.values():if filter_ids and sg["GroupId"] not in filter_ids:@@ -547,8 +573,9 @@ def _authorize_sg_ingress(p):return _error("InvalidGroup.NotFound", f"Security group {sg_id} not found", 400)rules = _parse_ip_permissions(p, "IpPermissions")for r in rules:- if r not in sg["IpPermissions"]:- sg["IpPermissions"].append(r)+ if r in sg["IpPermissions"]:+ return _error("InvalidPermission.Duplicate", "The specified rule already exists", 400)+ sg["IpPermissions"].append(r)return _xml(200, "AuthorizeSecurityGroupIngressResponse", "<return>true</return>")@@ -625,6 +652,10 @@ def _delete_key_pair(p):def _describe_key_pairs(p):filter_names = _parse_member_list(p, "KeyName")+ if filter_names:+ for kn in filter_names:+ if kn not in _key_pairs:+ return _error("InvalidKeyPair.NotFound", f"The key pair '{kn}' does not exist", 400)items = ""for kp in _key_pairs.values():if filter_names and kp["KeyName"] not in filter_names:@@ -659,16 +690,55 @@ def _import_key_pair(p):def _describe_vpcs(p):filter_ids = _parse_member_list(p, "VpcId")+ if filter_ids:+ for vid in filter_ids:+ if vid not in _vpcs:+ return _error("InvalidVpcID.NotFound", f"The vpc ID '{vid}' does not exist", 400)+ filters = _parse_filters(p)items = ""for vpc in _vpcs.values():if filter_ids and vpc["VpcId"] not in filter_ids:continue+ if not _matches_vpc_filters(vpc, filters):+ continueitems += _vpc_xml(vpc)return _xml(200, "DescribeVpcsResponse", f"<vpcSet>{items}</vpcSet>")+def _matches_vpc_filters(vpc, filters):+ for name, vals in filters.items():+ if name == "vpc-id":+ if vpc["VpcId"] not in vals:+ return False+ elif name == "cidr" or name == "cidr-block-association.cidr-block":+ if vpc["CidrBlock"] not in vals:+ return False+ elif name == "state":+ if vpc["State"] not in vals:+ return False+ elif name == "owner-id":+ if vpc["OwnerId"] not in vals:+ return False+ elif name == "is-default":+ 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+ return True++def _create_vpc(p):cidr = _p(p, "CidrBlock") or "10.0.0.0/16"+ try:+ import ipaddress+ ipaddress.ip_network(cidr, strict=False)+ except ValueError:+ return _error("InvalidParameterValue", f"Value ({cidr}) for parameter cidrBlock is invalid.", 400)vpc_id = _new_vpc_id()# Per-VPC default network ACLacl_id = "acl-" + "".join(random.choices(string.hexdigits[:16], k=17))@@ -725,6 +795,10 @@ def _delete_vpc(p):def _describe_subnets(p):filter_ids = _parse_member_list(p, "SubnetId")filters = _parse_filters(p)+ if filter_ids:+ for sid in filter_ids:+ if sid not in _subnets:+ return _error("InvalidSubnetID.NotFound", f"The subnet ID '{sid}' does not exist", 400)items = ""for subnet in _subnets.values():if filter_ids and subnet["SubnetId"] not in filter_ids:@@ -798,6 +872,10 @@ def _delete_internet_gateway(p):def _describe_internet_gateways(p):filter_ids = _parse_member_list(p, "InternetGatewayId")+ if filter_ids:+ for gid in filter_ids:+ if gid not in _internet_gateways:+ return _error("InvalidInternetGatewayID.NotFound", f"The internet gateway ID '{gid}' does not exist", 400)items = ""for igw in _internet_gateways.values():if filter_ids and igw["InternetGatewayId"] not in filter_ids:@@ -1257,6 +1335,19 @@ def _describe_addresses(p):# Tags# ---------------------------------------------------------------------------++def _tag_set_xml(resource_id):+ """Build <tagSet> XML from _tags for a resource. Returns <tagSet/> if no tags."""+ tag_list = _tags.get(resource_id, [])+ if not tag_list:+ return "<tagSet/>"+ items = "".join(+ f"<item><key>{_esc(t['Key'])}</key><value>{_esc(t.get('Value', ''))}</value></item>"+ for t in tag_list+ )+ return f"<tagSet>{items}</tagSet>"++def _create_tags(p):resource_ids = _parse_member_list(p, "ResourceId")tags = _parse_tags(p)@@ -1345,6 +1436,19 @@ def _create_volume(p):"MultiAttachEnabled": False,"Throughput": 125 if vol_type == "gp3" else 0,}+ # Process TagSpecifications+ i = 1+ while _p(p, f"TagSpecification.{i}.ResourceType"):+ if _p(p, f"TagSpecification.{i}.ResourceType") == "volume":+ vol_tags = []+ j = 1+ while _p(p, f"TagSpecification.{i}.Tag.{j}.Key"):+ vol_tags.append({"Key": _p(p, f"TagSpecification.{i}.Tag.{j}.Key"),+ "Value": _p(p, f"TagSpecification.{i}.Tag.{j}.Value", "")})+ j += 1+ if vol_tags:+ _tags[vol_id] = vol_tags+ i += 1return _xml(200, "CreateVolumeResponse", _volume_inner_xml(_volumes[vol_id]))@@ -1361,6 +1465,10 @@ def _delete_volume(p):def _describe_volumes(p):filter_ids = _parse_member_list(p, "VolumeId")+ if filter_ids:+ for vid in filter_ids:+ if vid not in _volumes:+ return _error("InvalidVolume.NotFound", f"The volume '{vid}' does not exist", 400)items = ""for vol in _volumes.values():if filter_ids and vol["VolumeId"] not in filter_ids:@@ -1540,6 +1648,19 @@ def _create_snapshot(p):"Encrypted": vol["Encrypted"],"StorageTier": "standard",}+ # Process TagSpecifications+ i = 1+ while _p(p, f"TagSpecification.{i}.ResourceType"):+ if _p(p, f"TagSpecification.{i}.ResourceType") == "snapshot":+ snap_tags = []+ j = 1+ while _p(p, f"TagSpecification.{i}.Tag.{j}.Key"):+ snap_tags.append({"Key": _p(p, f"TagSpecification.{i}.Tag.{j}.Key"),+ "Value": _p(p, f"TagSpecification.{i}.Tag.{j}.Value", "")})+ j += 1+ if snap_tags:+ _tags[snap_id] = snap_tags+ i += 1return _xml(200, "CreateSnapshotResponse", _snapshot_inner_xml(_snapshots[snap_id]))@@ -1554,6 +1675,10 @@ def _delete_snapshot(p):def _describe_snapshots(p):filter_ids = _parse_member_list(p, "SnapshotId")owner_ids = _parse_member_list(p, "Owner")+ if filter_ids:+ for sid in filter_ids:+ if sid not in _snapshots:+ return _error("InvalidSnapshot.NotFound", f"The snapshot '{sid}' does not exist", 400)items = ""for snap in _snapshots.values():if filter_ids and snap["SnapshotId"] not in filter_ids:@@ -1681,7 +1806,7 @@ def _sg_xml(sg):<vpcId>{sg['VpcId']}</vpcId><ipPermissions>{ingress}</ipPermissions><ipPermissionsEgress>{egress}</ipPermissionsEgress>- <tagSet/>+ {_tag_set_xml(sg['GroupId'])}</item>"""@@ -1712,7 +1837,7 @@ def _vpc_fields_xml(vpc, tag="item"):{'<defaultNetworkAclId>' + vpc.get('DefaultNetworkAclId', '') + '</defaultNetworkAclId>' if vpc.get('DefaultNetworkAclId') else ''}{'<defaultSecurityGroupId>' + vpc.get('DefaultSecurityGroupId', '') + '</defaultSecurityGroupId>' if vpc.get('DefaultSecurityGroupId') else ''}{'<mainRouteTableId>' + vpc.get('MainRouteTableId', '') + '</mainRouteTableId>' if vpc.get('MainRouteTableId') else ''}- <tagSet/>+ {_tag_set_xml(vpc['VpcId'])}</{tag}>"""@@ -1732,7 +1857,7 @@ def _subnet_fields_xml(subnet, tag="item"):<defaultForAz>{'true' if subnet['DefaultForAz'] else 'false'}</defaultForAz><mapPublicIpOnLaunch>{'true' if subnet['MapPublicIpOnLaunch'] else 'false'}</mapPublicIpOnLaunch><ownerId>{subnet['OwnerId']}</ownerId>- <tagSet/>+ {_tag_set_xml(subnet['SubnetId'])}</{tag}>"""@@ -1749,7 +1874,7 @@ def _igw_fields_xml(igw, tag="item"):<internetGatewayId>{igw['InternetGatewayId']}</internetGatewayId><ownerId>{igw['OwnerId']}</ownerId><attachmentSet>{attachments}</attachmentSet>- <tagSet/>+ {_tag_set_xml(igw['InternetGatewayId'])}</{tag}>"""diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 790de219..7e27bed8 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -143,7 +143,7 @@ def _ts_to_epoch(value):return valuetry:from datetime import datetime, timezone- return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())except (ValueError, TypeError):return value@@ -1002,6 +1002,16 @@ def _tag_resource(data):new_tags = data.get("tags", [])if not arn:return error_response_json("InvalidParameterException", "resourceArn is required", 400)+ # Validate the resource exists by checking all known ARN stores+ found = (+ any(c.get("clusterArn") == arn for c in _clusters.values())+ or any(td.get("taskDefinitionArn") == arn for td in _task_defs.values())+ or any(svc.get("serviceArn") == arn for svc in _services.values())+ or any(t.get("taskArn") == arn for t in _tasks.values())+ or arn in _tags+ )+ if not found:+ return error_response_json("InvalidParameterException", f"The specified resource is not valid.", 400)existing = _tags.get(arn, [])existing_keys = {t["key"]: i for i, t in enumerate(existing)}for tag in new_tags:diff --git a/ministack/services/efs.py b/ministack/services/efs.pyindex 82c2db2c..b717b580 100644--- a/ministack/services/efs.py+++ b/ministack/services/efs.py@@ -53,7 +53,7 @@ def _ap_id():return "fsap-" + "".join(random.choices(string.hexdigits[:16], k=17))def _now_iso():- return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())+ return int(time.time())# ---------------------------------------------------------------------------# File Systems@@ -105,6 +105,9 @@ def _describe_file_systems(query):creation_token = query.get("CreationToken")max_items = int(query.get("MaxItems", 100))+ if fs_id and fs_id not in _file_systems:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+results = []for fs in _file_systems.values():if fs_id and fs["FileSystemId"] != fs_id:@@ -186,6 +189,9 @@ def _describe_mount_targets(query):mt_id = query.get("MountTargetId")max_items = int(query.get("MaxItems", 100))+ if mt_id and mt_id not in _mount_targets:+ return _error(404, "MountTargetNotFound", f"Mount target '{mt_id}' does not exist.")+results = []for mt in _mount_targets.values():if fs_id and mt["FileSystemId"] != fs_id:diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex b60e1f00..33e6758a 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -580,19 +580,31 @@ def _create_subnet_group(p):def _describe_subnet_groups(p):name = _p(p, "CacheSubnetGroupName")+ if name and name not in _subnet_groups:+ return _error("CacheSubnetGroupNotFoundFault", f"Cache subnet group {name} not found.", 404)groups = [_subnet_groups[name]] if name and name in _subnet_groups else list(_subnet_groups.values())- members = "".join(- f"<member><CacheSubnetGroupName>{g['CacheSubnetGroupName']}</CacheSubnetGroupName>"- f"<CacheSubnetGroupDescription>{g.get('CacheSubnetGroupDescription', '')}</CacheSubnetGroupDescription>"- f"<ARN>{g.get('ARN', '')}</ARN></member>"- for g in groups- )+ members = ""+ for g in groups:+ subnets_xml = "".join(+ f"<member><SubnetIdentifier>{s['SubnetIdentifier']}</SubnetIdentifier>"+ f"<SubnetAvailabilityZone><Name>{s['SubnetAvailabilityZone']['Name']}</Name></SubnetAvailabilityZone></member>"+ for s in g.get("Subnets", [])+ )+ members += (+ f"<member><CacheSubnetGroupName>{g['CacheSubnetGroupName']}</CacheSubnetGroupName>"+ f"<CacheSubnetGroupDescription>{g.get('CacheSubnetGroupDescription', '')}</CacheSubnetGroupDescription>"+ f"<VpcId>{g.get('VpcId', '')}</VpcId>"+ f"<Subnets>{subnets_xml}</Subnets>"+ f"<ARN>{g.get('ARN', '')}</ARN></member>"+ )return _xml(200, "DescribeCacheSubnetGroupsResponse",f"<DescribeCacheSubnetGroupsResult><CacheSubnetGroups>{members}</CacheSubnetGroups></DescribeCacheSubnetGroupsResult>")def _delete_subnet_group(p):name = _p(p, "CacheSubnetGroupName")+ if name not in _subnet_groups:+ return _error("CacheSubnetGroupNotFoundFault", f"Cache subnet group {name} not found.", 404)sg = _subnet_groups.pop(name, None)if sg:_tags.pop(sg.get("ARN", ""), None)@@ -654,6 +666,8 @@ def _create_param_group(p):def _describe_param_groups(p):name = _p(p, "CacheParameterGroupName")+ if name and name not in _param_groups:+ return _error("CacheParameterGroupNotFound", f"Cache parameter group {name} not found.", 404)groups = [_param_groups[name]] if name and name in _param_groups else list(_param_groups.values())members = "".join(f"<member><CacheParameterGroupName>{g['CacheParameterGroupName']}</CacheParameterGroupName>"@@ -668,6 +682,8 @@ def _describe_param_groups(p):def _delete_param_group(p):name = _p(p, "CacheParameterGroupName")+ if name not in _param_groups:+ return _error("CacheParameterGroupNotFound", f"Cache parameter group {name} not found.", 404)pg = _param_groups.pop(name, None)_param_group_params.pop(name, None)if pg:diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex dda73f27..e97c342f 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -235,6 +235,8 @@ def _update_database(data):def _create_table(data):db_name = data.get("DatabaseName")+ if db_name not in _databases:+ return error_response_json("EntityNotFoundException", f"Database {db_name} not found.", 400)table_input = data.get("TableInput", {})name = table_input.get("Name")key = f"{db_name}/{name}"@@ -262,6 +264,8 @@ def _delete_table(data):db_name = data.get("DatabaseName")name = data.get("Name")key = f"{db_name}/{name}"+ if key not in _tables:+ return error_response_json("EntityNotFoundException", f"Table {name} not found.", 400)_tables.pop(key, None)_partitions.pop(key, None)_partition_indexes.pop(key, None)@@ -455,7 +459,10 @@ def _create_connection(data):def _delete_connection(data):- _connections.pop(data.get("ConnectionName"), None)+ name = data.get("ConnectionName")+ if name not in _connections:+ return error_response_json("EntityNotFoundException", f"Connection {name} not found.", 400)+ _connections.pop(name, None)return json_response({})@@ -475,6 +482,8 @@ def _get_connections(data):def _create_crawler(data):name = data.get("Name")+ if name in _crawlers:+ return error_response_json("AlreadyExistsException", f"Crawler {name} already exists", 400)schedule = data.get("Schedule", "")schedule_struct = {"ScheduleExpression": schedule} if schedule else {}_crawlers[name] = {diff --git a/ministack/services/servicediscovery.py b/ministack/services/servicediscovery.pyindex dc64f6dd..c9ee93fa 100644--- a/ministack/services/servicediscovery.py+++ b/ministack/services/servicediscovery.py@@ -155,6 +155,9 @@ async def _create_namespace(data):ns_name = data.get("Name")if not ns_name:return error_response_json("InvalidInput", "Name is required", 400)+ for existing in _namespaces.values():+ if existing["Name"] == ns_name:+ return error_response_json("NamespaceAlreadyExists", f"Namespace {ns_name} already exists", 409)ns_id = f"ns-{new_uuid()[:8]}"action = data.get("_action", "")diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 1063d799..921de48e 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -205,7 +205,7 @@ def _get_topic_attributes(params):arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(arn)if not topic:- return _error("NotFoundException", f"Topic does not exist: {arn}", 404)+ return _error("NotFound", f"Topic does not exist: {arn}", 404)_refresh_subscription_counts(topic)attrs = "".join(f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"@@ -219,7 +219,7 @@ def _set_topic_attributes(params):arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(arn)if not topic:- return _error("NotFoundException", f"Topic does not exist: {arn}", 404)+ return _error("NotFound", f"Topic does not exist: {arn}", 404)attr_name = _p(params, "AttributeName")attr_val = _p(params, "AttributeValue")if attr_name:@@ -238,7 +238,7 @@ def _subscribe(params):topic = _topics.get(topic_arn)if not topic:- return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)if not protocol:return _error("InvalidParameterException", "Protocol is required", 400)@@ -299,7 +299,7 @@ def _confirm_subscription(params):topic = _topics.get(topic_arn)if not topic:- return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)if not token:return _error("InvalidParameterException", "Token is required", 400)@@ -363,7 +363,7 @@ def _list_subscriptions_by_topic(params):topic_arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(topic_arn)if not topic:- return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)members = ""for sub in topic["subscriptions"]:members += (@@ -383,11 +383,11 @@ def _get_subscription_attributes(params):sub_arn = _p(params, "SubscriptionArn")topic_arn = _sub_arn_to_topic.get(sub_arn)if not topic_arn or topic_arn not in _topics:- return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)sub = _find_subscription(topic_arn, sub_arn)if not sub:- return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)attrs = "".join(f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"@@ -401,11 +401,11 @@ def _set_subscription_attributes(params):sub_arn = _p(params, "SubscriptionArn")topic_arn = _sub_arn_to_topic.get(sub_arn)if not topic_arn or topic_arn not in _topics:- return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)sub = _find_subscription(topic_arn, sub_arn)if not sub:- return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)+ return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)attr_name = _p(params, "AttributeName")attr_val = _p(params, "AttributeValue")@@ -448,7 +448,7 @@ def _publish(params):"TopicArn, TargetArn, or PhoneNumber is required", 400)if topic_arn not in _topics:- return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)msg_attrs = _parse_message_attributes(params)msg_id = new_uuid()@@ -477,7 +477,7 @@ def _publish_batch(params):if not topic_arn:return _error("InvalidParameterException", "TopicArn is required", 400)if topic_arn not in _topics:- return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)+ return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)entries = _parse_batch_entries(params)if not entries:@@ -765,7 +765,7 @@ def _create_platform_endpoint(params):token = _p(params, "Token")if app_arn not in _platform_applications:- return _error("NotFoundException", f"PlatformApplication does not exist: {app_arn}", 404)+ return _error("NotFound", f"PlatformApplication does not exist: {app_arn}", 404)if not token:return _error("InvalidParameterException", "Token is required", 400)diff --git a/ministack/services/waf.py b/ministack/services/waf.pyindex a5f0c2de..99bbde6f 100644--- a/ministack/services/waf.py+++ b/ministack/services/waf.py@@ -117,6 +117,10 @@ def _create_web_acl(data):name = data.get("Name", "")if not name:return _waf_err("WAFInvalidParameterException", "Name is required")+ scope = data.get("Scope", "REGIONAL")+ for existing in _web_acls.values():+ if existing["Name"] == name and existing.get("Scope") == scope:+ return _waf_err("WAFDuplicateItemException", f"A WebACL with name '{name}' already exists.")uid = new_uuid()lock_token = new_uuid()arn = _acl_arn(name, uid)@@ -153,6 +157,9 @@ def _update_web_acl(data):acl = _web_acls.get(uid)if not acl:return _waf_err("WAFNonexistentItemException", f"WebACL {uid} not found")+ lock_token = data.get("LockToken", "")+ if lock_token != acl.get("LockToken", ""):+ return _waf_err("WAFOptimisticLockException", "The resource you are trying to update has been modified by another request.")acl["Rules"] = data.get("Rules", acl["Rules"])acl["DefaultAction"] = data.get("DefaultAction", acl["DefaultAction"])acl["VisibilityConfig"] = data.get("VisibilityConfig", acl["VisibilityConfig"])diff --git a/pyproject.toml b/pyproject.tomlindex 630c0c09..ed172e54 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.2.5"+version = "1.2.6"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex d663e16b..5d9c2f14 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1169,7 +1169,9 @@ def test_cfn_elbv2_load_balancer_and_listener(cfn, elbv2):cfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)- assert elbv2.describe_load_balancers(Names=[lb_name])["LoadBalancers"] == []+ with pytest.raises(ClientError) as exc:+ elbv2.describe_load_balancers(Names=[lb_name])+ assert exc.value.response["Error"]["Code"] == "LoadBalancerNotFound"def test_cfn_cloudwatch_alarm_lifecycle(cfn, cw):diff --git a/tests/test_ebs.py b/tests/test_ebs.pyindex 1006de8c..4fc87cce 100644--- a/tests/test_ebs.py+++ b/tests/test_ebs.py@@ -45,8 +45,9 @@ def test_ebs_delete_volume(ebs):vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=5, VolumeType="gp2")vol_id = vol["VolumeId"]ebs.delete_volume(VolumeId=vol_id)- desc = ebs.describe_volumes(VolumeIds=[vol_id])- assert len(desc["Volumes"]) == 0+ with pytest.raises(ClientError) as exc:+ ebs.describe_volumes(VolumeIds=[vol_id])+ assert exc.value.response["Error"]["Code"] == "InvalidVolume.NotFound"def test_ebs_modify_volume(ebs):vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")@@ -80,8 +81,9 @@ def test_ebs_delete_snapshot(ebs):snap = ebs.create_snapshot(VolumeId=vol["VolumeId"])snap_id = snap["SnapshotId"]ebs.delete_snapshot(SnapshotId=snap_id)- desc = ebs.describe_snapshots(SnapshotIds=[snap_id])- assert len(desc["Snapshots"]) == 0+ with pytest.raises(ClientError) as exc:+ ebs.describe_snapshots(SnapshotIds=[snap_id])+ assert exc.value.response["Error"]["Code"] == "InvalidSnapshot.NotFound"def test_ebs_copy_snapshot(ebs):vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")diff --git a/tests/test_efs.py b/tests/test_efs.pyindex 570de4c9..8f9f2e38 100644--- a/tests/test_efs.py+++ b/tests/test_efs.py@@ -6,6 +6,7 @@ import zipfilefrom urllib.parse import urlparseimport pytestfrom botocore.exceptions import ClientError+from botocore.exceptions import ClientErrorimport uuid as _uuid_moddef test_efs_create_and_describe_filesystem(efs):@@ -35,8 +36,9 @@ def test_efs_delete_filesystem(efs):resp = efs.create_file_system()fs_id = resp["FileSystemId"]efs.delete_file_system(FileSystemId=fs_id)- desc = efs.describe_file_systems(FileSystemId=fs_id)- assert len(desc["FileSystems"]) == 0+ with pytest.raises(ClientError) as exc:+ efs.describe_file_systems(FileSystemId=fs_id)+ assert exc.value.response["Error"]["Code"] == "FileSystemNotFound"def test_efs_mount_target(efs):fs = efs.create_file_system()diff --git a/tests/test_sns.py b/tests/test_sns.pyindex 571e70eb..68597a40 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -104,7 +104,7 @@ def test_sns_publish_nonexistent_topic(sns):fake_arn = "arn:aws:sns:us-east-1:000000000000:intg-sns-nonexist"with pytest.raises(ClientError) as exc:sns.publish(TopicArn=fake_arn, Message="fail")- assert exc.value.response["Error"]["Code"] == "NotFoundException"+ assert exc.value.response["Error"]["Code"] == "NotFound"def test_sns_sqs_fanout(sns, sqs):topic_arn = sns.create_topic(Name="intg-sns-fanout")["TopicArn"]