Skip to content

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

feat: VPC gaps (NAT/NACL/FlowLogs/Peering/DHCP/EgressIGW) + SQS awsQueryCompatible header (#37)

Nahuel Nuceraef3f01f53b79
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3d3c89a..3b358c4a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.7] — 2026-03-30
+
+### Added
+- **Athena engine control** — new `ATHENA_ENGINE` env var (`auto` | `duckdb` | `mock`) to select the SQL backend at startup; `auto` keeps existing behaviour (DuckDB if installed, mock otherwise). New `/_ministack/config` endpoint accepts `POST {"athena.ATHENA_ENGINE": "mock"}` to switch engines at runtime without restart — useful in CI to force mock mode without DuckDB installed. Contributed by @jespinoza-shippo.
+- **VPC gap coverage** — 6 new EC2 resource types, 22 new actions, 11 new tests
+ - **NAT Gateways**: `CreateNatGateway`, `DescribeNatGateways`, `DeleteNatGateway` — supports `SubnetId`, `ConnectivityType` (public/private), state transitions, `vpc-id`/`subnet-id`/`state` filters
+ - **Network ACLs**: `CreateNetworkAcl`, `DescribeNetworkAcls`, `DeleteNetworkAcl`, `CreateNetworkAclEntry`, `DeleteNetworkAclEntry`, `ReplaceNetworkAclEntry`, `ReplaceNetworkAclAssociation` — full CRUD with rule entries and subnet associations
+ - **Flow Logs**: `CreateFlowLogs`, `DescribeFlowLogs`, `DeleteFlowLogs` — supports VPC/subnet/ENI resource targets, CloudWatch Logs and S3 destinations, `resource-id` filter
+ - **VPC Peering**: `CreateVpcPeeringConnection`, `AcceptVpcPeeringConnection`, `DescribeVpcPeeringConnections`, `DeleteVpcPeeringConnection` — full lifecycle from `pending-acceptance` → `active` → `deleted`, cross-account/cross-region params accepted
+ - **DHCP Options**: `CreateDhcpOptions`, `AssociateDhcpOptions`, `DescribeDhcpOptions`, `DeleteDhcpOptions` — arbitrary key/value configurations, association updates `VpcId.DhcpOptionsId`
+ - **Egress-Only Internet Gateways**: `CreateEgressOnlyInternetGateway`, `DescribeEgressOnlyInternetGateways`, `DeleteEgressOnlyInternetGateway` — IPv6 egress-only IGW for VPCs
+
+### Fixed
+- **SQS `awsQueryCompatible` header** — all SQS JSON error responses now include the `x-amzn-query-error: <legacy_code>;<fault>` header required by the `awsQueryCompatible` service trait. botocore reads this header and overrides `Error.Code` with the legacy `AWS.SimpleQueueService.*` namespaced code (e.g. `AWS.SimpleQueueService.NonExistentQueue` instead of `QueueDoesNotExist`). Without this header, any SDK code that matched against the legacy string worked against real AWS but silently failed against MiniStack. Full mapping of all 28 SQS error shapes sourced from `aws-sdk-go` ErrCode constants.
+
+### Tests
+- 708 integration tests — all passing
+
+---
+
## [1.1.6] — 2026-03-30
### Fixed
diff --git a/README.md b/README.md
index fd054a36..fe04e736 100644
--- a/README.md
+++ b/README.md
@@ -233,7 +233,7 @@ subnet = ec2.create_subnet(
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` |
| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |
-| **EC2** | RunInstances, DescribeInstances, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack) |
+| **EC2** | RunInstances, DescribeInstances, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack) |
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
@@ -467,7 +467,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (694 tests across all 30 services)
+# Run the full test suite (708 tests across all 30 services)
pytest tests/ -v
```
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index fa541d95..e4d9ed18 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -29,6 +29,17 @@ Supports:
EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute
EBS Snapshots: CreateSnapshot, DeleteSnapshot, DescribeSnapshots,
ModifySnapshotAttribute, DescribeSnapshotAttribute, CopySnapshot
+ NAT Gateways: CreateNatGateway, DescribeNatGateways, DeleteNatGateway
+ Network ACLs: CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl,
+ CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry,
+ ReplaceNetworkAclAssociation
+ Flow Logs: CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs
+ VPC Peering: CreateVpcPeeringConnection, AcceptVpcPeeringConnection,
+ DescribeVpcPeeringConnections, DeleteVpcPeeringConnection
+ DHCP Options: CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions,
+ DeleteDhcpOptions
+ Egress IGW: CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways,
+ DeleteEgressOnlyInternetGateway
"""
import os
@@ -62,6 +73,12 @@ _network_interfaces: dict = {} # eni_id -> ENI record
_vpc_endpoints: dict = {} # vpce_id -> endpoint record
_volumes: dict = {} # vol_id -> volume record
_snapshots: dict = {} # snap_id -> snapshot record
+_nat_gateways: dict = {} # nat_id -> NAT gateway record
+_network_acls: dict = {} # acl_id -> network ACL record
+_flow_logs: dict = {} # flow_log_id -> flow log record
+_vpc_peering: dict = {} # pcx_id -> peering connection record
+_dhcp_options: dict = {} # dopt_id -> DHCP options record
+_egress_igws: dict = {} # eigw_id -> egress-only internet gateway record
# Default VPC / subnet created at import time so DescribeVpcs always returns something
_DEFAULT_VPC_ID = "vpc-00000001"
@@ -1701,6 +1718,505 @@ def _error(code, message, status):
return status, {"Content-Type": "application/xml"}, body
+# ---------------------------------------------------------------------------
+# NAT Gateways
+# ---------------------------------------------------------------------------
+
+def _create_nat_gateway(params):
+ subnet_id = _p(params, "SubnetId")
+ alloc_id = _p(params, "AllocationId")
+ connectivity = _p(params, "ConnectivityType") or "public"
+ if not subnet_id:
+ return _error("MissingParameter", "SubnetId is required", 400)
+ nat_id = "nat-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ subnet = _subnets.get(subnet_id)
+ vpc_id = subnet["VpcId"] if subnet else _DEFAULT_VPC_ID
+ tags = _parse_tags(params)
+ record = {
+ "NatGatewayId": nat_id,
+ "SubnetId": subnet_id,
+ "VpcId": vpc_id,
+ "AllocationId": alloc_id,
+ "ConnectivityType": connectivity,
+ "State": "available",
+ "CreateTime": _now_ts(),
+ "Tags": tags,
+ }
+ _nat_gateways[nat_id] = record
+ if tags:
+ _tags[nat_id] = tags
+ inner = f"""<natGateway>
+ <natGatewayId>{nat_id}</natGatewayId>
+ <subnetId>{subnet_id}</subnetId>
+ <vpcId>{vpc_id}</vpcId>
+ <state>available</state>
+ <connectivityType>{connectivity}</connectivityType>
+ <createTime>{_now_ts()}</createTime>
+ <natGatewayAddressSet/>
+ <tagSet/>
+ </natGateway>"""
+ return _xml(200, "CreateNatGatewayResponse", inner)
+
+
+def _describe_nat_gateways(params):
+ filters = _parse_filters(params)
+ ids = _parse_member_list(params, "NatGatewayId")
+ items = ""
+ for nat in _nat_gateways.values():
+ if ids and nat["NatGatewayId"] not in ids:
+ 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"]:
+ continue
+ if filters.get("subnet-id") and nat["SubnetId"] not in filters["subnet-id"]:
+ continue
+ items += f"""<item>
+ <natGatewayId>{nat['NatGatewayId']}</natGatewayId>
+ <subnetId>{nat['SubnetId']}</subnetId>
+ <vpcId>{nat['VpcId']}</vpcId>
+ <state>{nat['State']}</state>
+ <connectivityType>{nat['ConnectivityType']}</connectivityType>
+ <createTime>{nat['CreateTime']}</createTime>
+ <natGatewayAddressSet/>
+ <tagSet/>
+ </item>"""
+ return _xml(200, "DescribeNatGatewaysResponse",
+ f"<natGatewaySet>{items}</natGatewaySet>")
+
+
+def _delete_nat_gateway(params):
+ nat_id = _p(params, "NatGatewayId")
+ if nat_id not in _nat_gateways:
+ return _error("NatGatewayNotFound", f"NatGateway {nat_id} not found", 400)
+ _nat_gateways[nat_id]["State"] = "deleted"
+ return _xml(200, "DeleteNatGatewayResponse",
+ f"<natGatewayId>{nat_id}</natGatewayId>")
+
+
+# ---------------------------------------------------------------------------
+# Network ACLs
+# ---------------------------------------------------------------------------
+
+def _create_network_acl(params):
+ vpc_id = _p(params, "VpcId")
+ if not vpc_id:
+ return _error("MissingParameter", "VpcId is required", 400)
+ acl_id = "acl-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ tags = _parse_tags(params)
+ record = {
+ "NetworkAclId": acl_id,
+ "VpcId": vpc_id,
+ "IsDefault": False,
+ "Entries": [],
+ "Associations": [],
+ "Tags": tags,
+ "OwnerId": ACCOUNT_ID,
+ }
+ _network_acls[acl_id] = record
+ if tags:
+ _tags[acl_id] = tags
+ inner = f"""<networkAcl>
+ <networkAclId>{acl_id}</networkAclId>
+ <vpcId>{vpc_id}</vpcId>
+ <default>false</default>
+ <entrySet/>
+ <associationSet/>
+ <tagSet/>
+ <ownerId>{ACCOUNT_ID}</ownerId>
+ </networkAcl>"""
+ return _xml(200, "CreateNetworkAclResponse", inner)
+
+
+def _describe_network_acls(params):
+ filters = _parse_filters(params)
+ ids = _parse_member_list(params, "NetworkAclId")
+ items = ""
+ for acl in _network_acls.values():
+ if ids and acl["NetworkAclId"] not in ids:
+ continue
+ if filters.get("vpc-id") and acl["VpcId"] not in filters["vpc-id"]:
+ continue
+ entries = "".join(f"""<item>
+ <ruleNumber>{e['RuleNumber']}</ruleNumber>
+ <protocol>{e['Protocol']}</protocol>
+ <ruleAction>{e['RuleAction']}</ruleAction>
+ <egress>{'true' if e['Egress'] else 'false'}</egress>
+ <cidrBlock>{e.get('CidrBlock','0.0.0.0/0')}</cidrBlock>
+ </item>""" for e in acl["Entries"])
+ assocs = "".join(f"""<item>
+ <networkAclAssociationId>{a['NetworkAclAssociationId']}</networkAclAssociationId>
+ <networkAclId>{acl['NetworkAclId']}</networkAclId>
+ <subnetId>{a['SubnetId']}</subnetId>
+ </item>""" for a in acl["Associations"])
+ items += f"""<item>
+ <networkAclId>{acl['NetworkAclId']}</networkAclId>
+ <vpcId>{acl['VpcId']}</vpcId>
+ <default>{'true' if acl['IsDefault'] else 'false'}</default>
+ <entrySet>{entries}</entrySet>
+ <associationSet>{assocs}</associationSet>
+ <tagSet/>
+ <ownerId>{acl['OwnerId']}</ownerId>
+ </item>"""
+ return _xml(200, "DescribeNetworkAclsResponse",
+ f"<networkAclSet>{items}</networkAclSet>")
+
+
+def _delete_network_acl(params):
+ acl_id = _p(params, "NetworkAclId")
+ if acl_id not in _network_acls:
+ return _error("InvalidNetworkAclID.NotFound", f"The network ACL '{acl_id}' does not exist", 400)
+ del _network_acls[acl_id]
+ return _xml(200, "DeleteNetworkAclResponse", "<return>true</return>")
+
+
+def _create_network_acl_entry(params):
+ acl_id = _p(params, "NetworkAclId")
+ if acl_id not in _network_acls:
+ return _error("InvalidNetworkAclID.NotFound", f"The network ACL '{acl_id}' does not exist", 400)
+ entry = {
+ "RuleNumber": int(_p(params, "RuleNumber") or 100),
+ "Protocol": _p(params, "Protocol") or "-1",
+ "RuleAction": _p(params, "RuleAction") or "allow",
+ "Egress": _p(params, "Egress") == "true",
+ "CidrBlock": _p(params, "CidrBlock") or "0.0.0.0/0",
+ }
+ _network_acls[acl_id]["Entries"].append(entry)
+ return _xml(200, "CreateNetworkAclEntryResponse", "<return>true</return>")
+
+
+def _delete_network_acl_entry(params):
+ acl_id = _p(params, "NetworkAclId")
+ rule_num = int(_p(params, "RuleNumber") or 0)
+ egress = _p(params, "Egress") == "true"
+ if acl_id not in _network_acls:
+ return _error("InvalidNetworkAclID.NotFound", f"The network ACL '{acl_id}' does not exist", 400)
+ acl = _network_acls[acl_id]
+ acl["Entries"] = [e for e in acl["Entries"]
+ if not (e["RuleNumber"] == rule_num and e["Egress"] == egress)]
+ return _xml(200, "DeleteNetworkAclEntryResponse", "<return>true</return>")
+
+
+def _replace_network_acl_entry(params):
+ acl_id = _p(params, "NetworkAclId")
+ rule_num = int(_p(params, "RuleNumber") or 0)
+ egress = _p(params, "Egress") == "true"
+ if acl_id not in _network_acls:
+ return _error("InvalidNetworkAclID.NotFound", f"The network ACL '{acl_id}' does not exist", 400)
+ acl = _network_acls[acl_id]
+ acl["Entries"] = [e for e in acl["Entries"]
+ if not (e["RuleNumber"] == rule_num and e["Egress"] == egress)]
+ acl["Entries"].append({
+ "RuleNumber": rule_num,
+ "Protocol": _p(params, "Protocol") or "-1",
+ "RuleAction": _p(params, "RuleAction") or "allow",
+ "Egress": egress,
+ "CidrBlock": _p(params, "CidrBlock") or "0.0.0.0/0",
+ })
+ return _xml(200, "ReplaceNetworkAclEntryResponse", "<return>true</return>")
+
+
+def _replace_network_acl_association(params):
+ assoc_id = _p(params, "AssociationId")
+ new_acl_id = _p(params, "NetworkAclId")
+ if new_acl_id not in _network_acls:
+ return _error("InvalidNetworkAclID.NotFound", f"The network ACL '{new_acl_id}' does not exist", 400)
+ new_assoc_id = "aclassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ # Remove old association from whichever ACL owns it
+ for acl in _network_acls.values():
+ acl["Associations"] = [a for a in acl["Associations"]
+ if a["NetworkAclAssociationId"] != assoc_id]
+ subnet_id = ""
+ _network_acls[new_acl_id]["Associations"].append({
+ "NetworkAclAssociationId": new_assoc_id,
+ "SubnetId": subnet_id,
+ })
+ return _xml(200, "ReplaceNetworkAclAssociationResponse",
+ f"<newAssociationId>{new_assoc_id}</newAssociationId>")
+
+
+# ---------------------------------------------------------------------------
+# Flow Logs
+# ---------------------------------------------------------------------------
+
+def _create_flow_logs(params):
+ resource_ids = _parse_member_list(params, "ResourceId")
+ resource_type = _p(params, "ResourceType") or "VPC"
+ traffic_type = _p(params, "TrafficType") or "ALL"
+ log_dest_type = _p(params, "LogDestinationType") or "cloud-watch-logs"
+ log_dest = _p(params, "LogDestination") or _p(params, "LogGroupName")
+ created = []
+ for rid in resource_ids:
+ fl_id = "fl-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ _flow_logs[fl_id] = {
+ "FlowLogId": fl_id,
+ "ResourceId": rid,
+ "ResourceType": resource_type,
+ "TrafficType": traffic_type,
+ "LogDestinationType": log_dest_type,
+ "LogDestination": log_dest,
+ "FlowLogStatus": "ACTIVE",
+ "CreationTime": _now_ts(),
+ }
+ created.append(fl_id)
+ ids_xml = "".join(f"<item>{fid}</item>" for fid in created)
+ return _xml(200, "CreateFlowLogsResponse",
+ f"<flowLogIdSet>{ids_xml}</flowLogIdSet><unsuccessful/>")
+
+
+def _describe_flow_logs(params):
+ ids = _parse_member_list(params, "FlowLogId")
+ filters = _parse_filters(params)
+ items = ""
+ for fl in _flow_logs.values():
+ if ids and fl["FlowLogId"] not in ids:
+ continue
+ if filters.get("resource-id") and fl["ResourceId"] not in filters["resource-id"]:
+ continue
+ items += f"""<item>
+ <flowLogId>{fl['FlowLogId']}</flowLogId>
+ <resourceId>{fl['ResourceId']}</resourceId>
+ <trafficType>{fl['TrafficType']}</trafficType>
+ <logDestinationType>{fl['LogDestinationType']}</logDestinationType>
+ <logDestination>{fl.get('LogDestination','')}</logDestination>
+ <flowLogStatus>{fl['FlowLogStatus']}</flowLogStatus>
+ <creationTime>{fl['CreationTime']}</creationTime>
+ </item>"""
+ return _xml(200, "DescribeFlowLogsResponse", f"<flowLogSet>{items}</flowLogSet>")
+
+
+def _delete_flow_logs(params):
+ ids = _parse_member_list(params, "FlowLogId")
+ for fid in ids:
+ _flow_logs.pop(fid, None)
+ return _xml(200, "DeleteFlowLogsResponse", "<unsuccessful/>")
+
+
+# ---------------------------------------------------------------------------
+# VPC Peering Connections
+# ---------------------------------------------------------------------------
+
+def _create_vpc_peering_connection(params):
+ vpc_id = _p(params, "VpcId")
+ peer_vpc_id = _p(params, "PeerVpcId")
+ peer_owner_id = _p(params, "PeerOwnerId") or ACCOUNT_ID
+ peer_region = _p(params, "PeerRegion") or REGION
+ if not vpc_id or not peer_vpc_id:
+ return _error("MissingParameter", "VpcId and PeerVpcId are required", 400)
+ pcx_id = "pcx-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ record = {
+ "VpcPeeringConnectionId": pcx_id,
+ "RequesterVpcInfo": {"VpcId": vpc_id, "OwnerId": ACCOUNT_ID, "Region": REGION},
+ "AccepterVpcInfo": {"VpcId": peer_vpc_id, "OwnerId": peer_owner_id, "Region": peer_region},
+ "Status": {"Code": "pending-acceptance", "Message": "Pending Acceptance by " + peer_owner_id},
+ "ExpirationTime": _now_ts(),
+ "Tags": [],
+ }
+ _vpc_peering[pcx_id] = record
+ inner = f"""<vpcPeeringConnection>
+ <vpcPeeringConnectionId>{pcx_id}</vpcPeeringConnectionId>
+ <requesterVpcInfo><vpcId>{vpc_id}</vpcId><ownerId>{ACCOUNT_ID}</ownerId></requesterVpcInfo>
+ <accepterVpcInfo><vpcId>{peer_vpc_id}</vpcId><ownerId>{peer_owner_id}</ownerId></accepterVpcInfo>
+ <status><code>pending-acceptance</code></status>
+ <tagSet/>
+ </vpcPeeringConnection>"""
+ return _xml(200, "CreateVpcPeeringConnectionResponse", inner)
+
+
+def _accept_vpc_peering_connection(params):
+ pcx_id = _p(params, "VpcPeeringConnectionId")
+ if pcx_id not in _vpc_peering:
+ return _error("InvalidVpcPeeringConnectionID.NotFound",
+ f"The VPC peering connection '{pcx_id}' does not exist", 400)
+ _vpc_peering[pcx_id]["Status"] = {"Code": "active", "Message": "Active"}
+ pcx = _vpc_peering[pcx_id]
+ inner = f"""<vpcPeeringConnection>
+ <vpcPeeringConnectionId>{pcx_id}</vpcPeeringConnectionId>
+ <requesterVpcInfo><vpcId>{pcx['RequesterVpcInfo']['VpcId']}</vpcId></requesterVpcInfo>
+ <accepterVpcInfo><vpcId>{pcx['AccepterVpcInfo']['VpcId']}</vpcId></accepterVpcInfo>
+ <status><code>active</code></status>
+ <tagSet/>
+ </vpcPeeringConnection>"""
+ return _xml(200, "AcceptVpcPeeringConnectionResponse", inner)
+
+
+def _describe_vpc_peering_connections(params):
+ ids = _parse_member_list(params, "VpcPeeringConnectionId")
+ filters = _parse_filters(params)
+ items = ""
+ for pcx in _vpc_peering.values():
+ if ids and pcx["VpcPeeringConnectionId"] not in ids:
+ continue
+ if filters.get("status-code") and pcx["Status"]["Code"] not in filters["status-code"]:
+ continue
+ items += f"""<item>
+ <vpcPeeringConnectionId>{pcx['VpcPeeringConnectionId']}</vpcPeeringConnectionId>
+ <requesterVpcInfo><vpcId>{pcx['RequesterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['RequesterVpcInfo']['OwnerId']}</ownerId></requesterVpcInfo>
+ <accepterVpcInfo><vpcId>{pcx['AccepterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['AccepterVpcInfo']['OwnerId']}</ownerId></accepterVpcInfo>
+ <status><code>{pcx['Status']['Code']}</code><message>{pcx['Status']['Message']}</message></status>
+ <tagSet/>
+ </item>"""
+ return _xml(200, "DescribeVpcPeeringConnectionsResponse",
+ f"<vpcPeeringConnectionSet>{items}</vpcPeeringConnectionSet>")
+
+
+def _delete_vpc_peering_connection(params):
+ pcx_id = _p(params, "VpcPeeringConnectionId")
+ if pcx_id not in _vpc_peering:
+ return _error("InvalidVpcPeeringConnectionID.NotFound",
+ f"The VPC peering connection '{pcx_id}' does not exist", 400)
+ _vpc_peering[pcx_id]["Status"] = {"Code": "deleted", "Message": "Deleted"}
+ return _xml(200, "DeleteVpcPeeringConnectionResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# DHCP Options
+# ---------------------------------------------------------------------------
+
+def _create_dhcp_options(params):
+ # Parse DhcpConfigurations: DhcpConfiguration.N.Key, DhcpConfiguration.N.Value.N
+ configs = []
+ i = 1
+ while True:
+ key = _p(params, f"DhcpConfiguration.{i}.Key")
+ if not key:
+ break
+ vals = []
+ j = 1
+ while True:
+ v = _p(params, f"DhcpConfiguration.{i}.Value.{j}")
+ if not v:
+ break
+ vals.append(v)
+ j += 1
+ configs.append({"Key": key, "Values": vals})
+ i += 1
+ dopt_id = "dopt-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ tags = _parse_tags(params)
+ record = {
+ "DhcpOptionsId": dopt_id,
+ "DhcpConfigurations": configs,
+ "OwnerId": ACCOUNT_ID,
+ "Tags": tags,
+ }
+ _dhcp_options[dopt_id] = record
+ if tags:
+ _tags[dopt_id] = tags
+ configs_xml = "".join(f"""<item>
+ <key>{c['Key']}</key>
+ <valueSet>{"".join(f'<item><value>{v}</value></item>' for v in c['Values'])}</valueSet>
+ </item>""" for c in configs)
+ inner = f"""<dhcpOptions>
+ <dhcpOptionsId>{dopt_id}</dhcpOptionsId>
+ <dhcpConfigurationSet>{configs_xml}</dhcpConfigurationSet>
+ <ownerId>{ACCOUNT_ID}</ownerId>
+ <tagSet/>
+ </dhcpOptions>"""
+ return _xml(200, "CreateDhcpOptionsResponse", inner)
+
+
+def _associate_dhcp_options(params):
+ dopt_id = _p(params, "DhcpOptionsId")
+ vpc_id = _p(params, "VpcId")
+ if vpc_id not in _vpcs:
+ return _error("InvalidVpcID.NotFound", f"The VPC '{vpc_id}' does not exist", 400)
+ # "default" is valid — resets to AWS-provided DHCP options
+ if dopt_id != "default" and dopt_id not in _dhcp_options:
+ return _error("InvalidDhcpOptionsID.NotFound",
+ f"The dhcp options '{dopt_id}' does not exist", 400)
+ _vpcs[vpc_id]["DhcpOptionsId"] = dopt_id
+ return _xml(200, "AssociateDhcpOptionsResponse", "<return>true</return>")
+
+
+def _describe_dhcp_options(params):
+ ids = _parse_member_list(params, "DhcpOptionsId")
+ items = ""
+ for dopt in _dhcp_options.values():
+ if ids and dopt["DhcpOptionsId"] not in ids:
+ continue
+ configs_xml = "".join(f"""<item>
+ <key>{c['Key']}</key>
+ <valueSet>{"".join(f'<item><value>{v}</value></item>' for v in c['Values'])}</valueSet>
+ </item>""" for c in dopt["DhcpConfigurations"])
+ items += f"""<item>
+ <dhcpOptionsId>{dopt['DhcpOptionsId']}</dhcpOptionsId>
+ <dhcpConfigurationSet>{configs_xml}</dhcpConfigurationSet>
+ <ownerId>{dopt['OwnerId']}</ownerId>
+ <tagSet/>
+ </item>"""
+ return _xml(200, "DescribeDhcpOptionsResponse", f"<dhcpOptionsSet>{items}</dhcpOptionsSet>")
+
+
+def _delete_dhcp_options(params):
+ dopt_id = _p(params, "DhcpOptionsId")
+ if dopt_id not in _dhcp_options:
+ return _error("InvalidDhcpOptionsID.NotFound",
+ f"The dhcp options '{dopt_id}' does not exist", 400)
+ del _dhcp_options[dopt_id]
+ return _xml(200, "DeleteDhcpOptionsResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Egress-Only Internet Gateways
+# ---------------------------------------------------------------------------
+
+def _create_egress_only_igw(params):
+ vpc_id = _p(params, "VpcId")
+ if not vpc_id:
+ return _error("MissingParameter", "VpcId is required", 400)
+ eigw_id = "eigw-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ tags = _parse_tags(params)
+ record = {
+ "EgressOnlyInternetGatewayId": eigw_id,
+ "VpcId": vpc_id,
+ "State": "attached",
+ "Tags": tags,
+ }
+ _egress_igws[eigw_id] = record
+ if tags:
+ _tags[eigw_id] = tags
+ inner = f"""<egressOnlyInternetGateway>
+ <egressOnlyInternetGatewayId>{eigw_id}</egressOnlyInternetGatewayId>
+ <attachmentSet>
+ <item>
+ <vpcId>{vpc_id}</vpcId>
+ <state>attached</state>
+ </item>
+ </attachmentSet>
+ <tagSet/>
+ </egressOnlyInternetGateway>"""
+ return _xml(200, "CreateEgressOnlyInternetGatewayResponse", inner)
+
+
+def _describe_egress_only_igws(params):
+ ids = _parse_member_list(params, "EgressOnlyInternetGatewayId")
+ items = ""
+ for eigw in _egress_igws.values():
+ if ids and eigw["EgressOnlyInternetGatewayId"] not in ids:
+ continue
+ items += f"""<item>
+ <egressOnlyInternetGatewayId>{eigw['EgressOnlyInternetGatewayId']}</egressOnlyInternetGatewayId>
+ <attachmentSet>
+ <item>
+ <vpcId>{eigw['VpcId']}</vpcId>
+ <state>{eigw['State']}</state>
+ </item>
+ </attachmentSet>
+ <tagSet/>
+ </item>"""
+ return _xml(200, "DescribeEgressOnlyInternetGatewaysResponse",
+ f"<egressOnlyInternetGatewaySet>{items}</egressOnlyInternetGatewaySet>")
+
+
+def _delete_egress_only_igw(params):
+ eigw_id = _p(params, "EgressOnlyInternetGatewayId")
+ if eigw_id not in _egress_igws:
+ return _error("InvalidGatewayID.NotFound",
+ f"The egress only internet gateway '{eigw_id}' does not exist", 400)
+ del _egress_igws[eigw_id]
+ return _xml(200, "DeleteEgressOnlyInternetGatewayResponse", "<returnCode>true</returnCode>")
+
+
# ---------------------------------------------------------------------------
# Reset
# ---------------------------------------------------------------------------
@@ -1719,6 +2235,12 @@ def reset():
_vpc_endpoints.clear()
_volumes.clear()
_snapshots.clear()
+ _nat_gateways.clear()
+ _network_acls.clear()
+ _flow_logs.clear()
+ _vpc_peering.clear()
+ _dhcp_options.clear()
+ _egress_igws.clear()
_init_defaults()
@@ -1802,4 +2324,34 @@ _ACTION_MAP = {
"CopySnapshot": _copy_snapshot,
"ModifySnapshotAttribute": _modify_snapshot_attribute,
"DescribeSnapshotAttribute": _describe_snapshot_attribute,
+ # NAT Gateways
+ "CreateNatGateway": _create_nat_gateway,
+ "DescribeNatGateways": _describe_nat_gateways,
+ "DeleteNatGateway": _delete_nat_gateway,
+ # Network ACLs
+ "CreateNetworkAcl": _create_network_acl,
+ "DescribeNetworkAcls": _describe_network_acls,
+ "DeleteNetworkAcl": _delete_network_acl,
+ "CreateNetworkAclEntry": _create_network_acl_entry,
+ "DeleteNetworkAclEntry": _delete_network_acl_entry,
+ "ReplaceNetworkAclEntry": _replace_network_acl_entry,
+ "ReplaceNetworkAclAssociation": _replace_network_acl_association,
+ # Flow Logs
+ "CreateFlowLogs": _create_flow_logs,
+ "DescribeFlowLogs": _describe_flow_logs,
+ "DeleteFlowLogs": _delete_flow_logs,
+ # VPC Peering
+ "CreateVpcPeeringConnection": _create_vpc_peering_connection,
+ "AcceptVpcPeeringConnection": _accept_vpc_peering_connection,
+ "DescribeVpcPeeringConnections": _describe_vpc_peering_connections,
+ "DeleteVpcPeeringConnection": _delete_vpc_peering_connection,
+ # DHCP Options
+ "CreateDhcpOptions": _create_dhcp_options,
+ "AssociateDhcpOptions": _associate_dhcp_options,
+ "DescribeDhcpOptions": _describe_dhcp_options,
+ "DeleteDhcpOptions": _delete_dhcp_options,
+ # Egress-Only Internet Gateways
+ "CreateEgressOnlyInternetGateway": _create_egress_only_igw,
+ "DescribeEgressOnlyInternetGateways": _describe_egress_only_igws,
+ "DeleteEgressOnlyInternetGateway": _delete_egress_only_igw,
}
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 73ed3a66..b24bdc96 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -75,7 +75,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
def _create_topic(params):
name = _p(params, "Name")
if not name:
- return _error("InvalidParameter", "Name is required", 400)
+ return _error("InvalidParameterException", "Name is required", 400)
arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"
if arn not in _topics:
@@ -149,7 +149,7 @@ def _get_topic_attributes(params):
arn = _p(params, "TopicArn")
topic = _topics.get(arn)
if not topic:
- return _error("NotFound", f"Topic does not exist: {arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {arn}", 404)
_refresh_subscription_counts(topic)
attrs = "".join(
f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"
@@ -163,7 +163,7 @@ def _set_topic_attributes(params):
arn = _p(params, "TopicArn")
topic = _topics.get(arn)
if not topic:
- return _error("NotFound", f"Topic does not exist: {arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {arn}", 404)
attr_name = _p(params, "AttributeName")
attr_val = _p(params, "AttributeValue")
if attr_name:
@@ -182,10 +182,10 @@ def _subscribe(params):
topic = _topics.get(topic_arn)
if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)
if not protocol:
- return _error("InvalidParameter", "Protocol is required", 400)
+ return _error("InvalidParameterException", "Protocol is required", 400)
for existing in topic["subscriptions"]:
if existing["protocol"] == protocol and existing["endpoint"] == endpoint:
@@ -233,10 +233,10 @@ def _confirm_subscription(params):
topic = _topics.get(topic_arn)
if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)
if not token:
- return _error("InvalidParameter", "Token is required", 400)
+ return _error("InvalidParameterException", "Token is required", 400)
for sub in topic["subscriptions"]:
if sub.get("token") == token:
@@ -248,7 +248,7 @@ def _confirm_subscription(params):
return _xml(200, "ConfirmSubscriptionResponse",
f"<ConfirmSubscriptionResult><SubscriptionArn>{sub['arn']}</SubscriptionArn></ConfirmSubscriptionResult>")
- return _error("InvalidParameter", "Invalid token", 400)
+ return _error("InvalidParameterException", "Invalid token", 400)
def _unsubscribe(params):
@@ -283,7 +283,7 @@ def _list_subscriptions_by_topic(params):
topic_arn = _p(params, "TopicArn")
topic = _topics.get(topic_arn)
if not topic:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)
members = ""
for sub in topic["subscriptions"]:
members += (
@@ -303,11 +303,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("NotFound", f"Subscription does not exist: {sub_arn}", 404)
+ return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)
sub = _find_subscription(topic_arn, sub_arn)
if not sub:
- return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)
+ return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)
attrs = "".join(
f"<entry><key>{k}</key><value>{_xml_escape(v)}</value></entry>"
@@ -321,11 +321,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("NotFound", f"Subscription does not exist: {sub_arn}", 404)
+ return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)
sub = _find_subscription(topic_arn, sub_arn)
if not sub:
- return _error("NotFound", f"Subscription does not exist: {sub_arn}", 404)
+ return _error("NotFoundException", f"Subscription does not exist: {sub_arn}", 404)
attr_name = _p(params, "AttributeName")
attr_val = _p(params, "AttributeValue")
@@ -333,14 +333,14 @@ def _set_subscription_attributes(params):
allowed = {"DeliveryPolicy", "FilterPolicy", "FilterPolicyScope",
"RawMessageDelivery", "RedrivePolicy"}
if attr_name not in allowed:
- return _error("InvalidParameter",
+ return _error("InvalidParameterException",
f"Invalid attribute name: {attr_name}", 400)
if attr_name == "FilterPolicy" and attr_val:
try:
json.loads(attr_val)
except json.JSONDecodeError:
- return _error("InvalidParameter", "Invalid JSON in FilterPolicy", 400)
+ return _error("InvalidParameterException", "Invalid JSON in FilterPolicy", 400)
sub["attributes"][attr_name] = attr_val
return _xml(200, "SetSubscriptionAttributesResponse", "")
@@ -364,11 +364,11 @@ def _publish(params):
f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")
if not topic_arn:
- return _error("InvalidParameter",
+ return _error("InvalidParameterException",
"TopicArn, TargetArn, or PhoneNumber is required", 400)
if topic_arn not in _topics:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)
msg_attrs = _parse_message_attributes(params)
msg_id = new_uuid()
@@ -392,13 +392,13 @@ def _publish(params):
def _publish_batch(params):
topic_arn = _p(params, "TopicArn")
if not topic_arn:
- return _error("InvalidParameter", "TopicArn is required", 400)
+ return _error("InvalidParameterException", "TopicArn is required", 400)
if topic_arn not in _topics:
- return _error("NotFound", f"Topic does not exist: {topic_arn}", 404)
+ return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)
entries = _parse_batch_entries(params)
if not entries:
- return _error("InvalidParameter",
+ return _error("InvalidParameterException",
"PublishBatchRequestEntries is required", 400)
if len(entries) > 10:
return _error("TooManyEntriesInBatchRequest",
@@ -645,7 +645,7 @@ def _create_platform_application(params):
name = _p(params, "Name")
platform = _p(params, "Platform")
if not name or not platform:
- return _error("InvalidParameter", "Name and Platform are required", 400)
+ return _error("InvalidParameterException", "Name and Platform are required", 400)
arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:app/{platform}/{name}"
attrs = {}
@@ -673,9 +673,9 @@ def _create_platform_endpoint(params):
token = _p(params, "Token")
if app_arn not in _platform_applications:
- return _error("NotFound", f"PlatformApplication does not exist: {app_arn}", 404)
+ return _error("NotFoundException", f"PlatformApplication does not exist: {app_arn}", 404)
if not token:
- return _error("InvalidParameter", "Token is required", 400)
+ return _error("InvalidParameterException", "Token is required", 400)
endpoint_arn = f"{app_arn}/{new_uuid()}"
@@ -719,10 +719,11 @@ def _xml(status, root_tag, inner):
def _error(code, message, status):
+ error_type = "Sender" if status < 500 else "Receiver"
body = (
f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
- f'<Error><Code>{code}</Code><Message>{_xml_escape(message)}</Message></Error>'
+ f'<Error><Type>{error_type}</Type><Code>{code}</Code><Message>{_xml_escape(message)}</Message></Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>'
).encode("utf-8")
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index ca3e9098..a74b7b06 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -785,10 +785,52 @@ def _json_ok(data: dict, status: int = 200) -> tuple:
json.dumps(data).encode("utf-8"))
+# Mapping from JSON protocol shape names to legacy Query-protocol error codes.
+# SQS has the awsQueryCompatible trait: botocore reads x-amzn-query-error and
+# overrides Error.Code with the legacy code so SDK callers using the old
+# namespaced strings (e.g. "AWS.SimpleQueueService.NonExistentQueue") still work.
+_QUERY_COMPAT_CODES: dict[str, str] = {
+ # Source: aws-sdk-go service/sqs/errors.go ErrCode* constants (authoritative)
+ "QueueDoesNotExist": "AWS.SimpleQueueService.NonExistentQueue",
+ "QueueNameExists": "QueueAlreadyExists",
+ "TooManyEntriesInBatchRequest": "AWS.SimpleQueueService.TooManyEntriesInBatchRequest",
+ "EmptyBatchRequest": "AWS.SimpleQueueService.EmptyBatchRequest",
+ "BatchEntryIdsNotDistinct": "AWS.SimpleQueueService.BatchEntryIdsNotDistinct",
+ "BatchRequestTooLong": "AWS.SimpleQueueService.BatchRequestTooLong",
+ "InvalidBatchEntryId": "AWS.SimpleQueueService.InvalidBatchEntryId",
+ "MessageNotInflight": "AWS.SimpleQueueService.MessageNotInflight",
+ "PurgeQueueInProgress": "AWS.SimpleQueueService.PurgeQueueInProgress",
+ "QueueDeletedRecently": "AWS.SimpleQueueService.QueueDeletedRecently",
+ "UnsupportedOperation": "AWS.SimpleQueueService.UnsupportedOperation",
+ "OverLimit": "OverLimit",
+ "InvalidIdFormat": "InvalidIdFormat",
+ "InvalidMessageContents": "InvalidMessageContents",
+ "ReceiptHandleIsInvalid": "ReceiptHandleIsInvalid",
+ "InvalidAttributeName": "InvalidAttributeName",
+ "InvalidAttributeValue": "InvalidAttributeValue",
+ "InvalidSecurity": "InvalidSecurity",
+ "InvalidAddress": "InvalidAddress",
+ "RequestThrottled": "RequestThrottled",
+ "ResourceNotFoundException": "ResourceNotFoundException",
+ # KMS errors — no namespace prefix
+ "KmsAccessDenied": "KmsAccessDenied",
+ "KmsDisabled": "KmsDisabled",
+ "KmsInvalidKeyUsage": "KmsInvalidKeyUsage",
+ "KmsInvalidState": "KmsInvalidState",
+ "KmsNotFound": "KmsNotFound",
+ "KmsOptInRequired": "KmsOptInRequired",
+ "KmsThrottled": "KmsThrottled",
+}
+
+
def _json_err_resp(code: str, msg: str, status: int = 400) -> tuple:
- return (status,
- {"Content-Type": "application/x-amz-json-1.0"},
- json.dumps({"__type": code, "message": msg}).encode("utf-8"))
+ fault = "Sender" if status < 500 else "Receiver"
+ legacy = _QUERY_COMPAT_CODES.get(code, code)
+ headers = {
+ "Content-Type": "application/x-amz-json-1.0",
+ "x-amzn-query-error": f"{legacy};{fault}",
+ }
+ return (status, headers, json.dumps({"__type": code, "message": msg}).encode("utf-8"))
# ── XML ─────────────────────────────────────────────────────
diff --git a/pyproject.toml b/pyproject.toml
index d8f5a691..a6dd9126 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.6"
+version = "1.1.7"
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 2b752213..c10e2019 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -691,7 +691,7 @@ def test_sqs_message_system_attributes(sqs):
def test_sqs_nonexistent_queue(sqs):
with pytest.raises(ClientError) as exc:
sqs.get_queue_url(QueueName="intg-sqs-does-not-exist")
- assert exc.value.response["Error"]["Code"] == "QueueDoesNotExist"
+ assert exc.value.response["Error"]["Code"] == "AWS.SimpleQueueService.NonExistentQueue"
def test_sqs_receive_empty(sqs):
@@ -805,7 +805,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"] == "NotFound"
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
def test_sns_sqs_fanout(sns, sqs):
@@ -13814,7 +13814,7 @@ def test_sqs_send_message_batch_limit(sqs):
entries = [{"Id": str(i), "MessageBody": f"msg {i}"} for i in range(11)]
with pytest.raises(ClientError) as exc_info:
sqs.send_message_batch(QueueUrl=q, Entries=entries)
- assert exc_info.value.response["Error"]["Code"] == "TooManyEntriesInBatchRequest"
+ assert exc_info.value.response["Error"]["Code"] == "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"
sqs.delete_queue(QueueUrl=q)
@@ -13855,3 +13855,270 @@ def test_sqs_typed_exception_queue_not_found(sqs):
import pytest
with pytest.raises(sqs.exceptions.QueueDoesNotExist):
sqs.get_queue_url(QueueName="queue-that-does-not-exist-typed-exc")
+
+
+# ---------------------------------------------------------------------------
+# Regression: SQS awsQueryCompatible — x-amzn-query-error header
+# botocore reads this header and overrides Error.Code with the legacy
+# AWS.SimpleQueueService.* code so callers checking the old namespaced
+# strings still work against MiniStack exactly as they do against real AWS.
+# ---------------------------------------------------------------------------
+
+def test_sqs_query_compat_header_nonexistent_queue(sqs):
+ """Error.Code must be the legacy 'AWS.SimpleQueueService.NonExistentQueue'
+ (not 'QueueDoesNotExist') when x-amzn-query-error header is present."""
+ with pytest.raises(ClientError) as exc:
+ sqs.get_queue_url(QueueName="queue-compat-header-test-xyz")
+ code = exc.value.response["Error"]["Code"]
+ assert code == "AWS.SimpleQueueService.NonExistentQueue", (
+ f"Expected legacy query-compat code, got '{code}'"
+ )
+
+
+def test_sqs_query_compat_header_batch_limit(sqs):
+ """TooManyEntriesInBatchRequest must surface as the legacy namespaced code."""
+ q = sqs.create_queue(QueueName="compat-batch-limit-q")["QueueUrl"]
+ entries = [{"Id": str(i), "MessageBody": f"m{i}"} for i in range(11)]
+ with pytest.raises(ClientError) as exc:
+ sqs.send_message_batch(QueueUrl=q, Entries=entries)
+ code = exc.value.response["Error"]["Code"]
+ assert code == "AWS.SimpleQueueService.TooManyEntriesInBatchRequest", (
+ f"Expected legacy query-compat code, got '{code}'"
+ )
+ sqs.delete_queue(QueueUrl=q)
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: NAT Gateways
+# ---------------------------------------------------------------------------
+
+def test_ec2_nat_gateway_crud(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.100.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+ subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.100.1.0/24")
+ subnet_id = subnet["Subnet"]["SubnetId"]
+
+ resp = ec2.create_nat_gateway(SubnetId=subnet_id, ConnectivityType="private")
+ nat_id = resp["NatGateway"]["NatGatewayId"]
+ assert nat_id.startswith("nat-")
+ assert resp["NatGateway"]["State"] == "available"
+
+ desc = ec2.describe_nat_gateways(NatGatewayIds=[nat_id])
+ assert len(desc["NatGateways"]) == 1
+ assert desc["NatGateways"][0]["NatGatewayId"] == nat_id
+ assert desc["NatGateways"][0]["SubnetId"] == subnet_id
+
+ ec2.delete_nat_gateway(NatGatewayId=nat_id)
+ desc2 = ec2.describe_nat_gateways(NatGatewayIds=[nat_id])
+ assert desc2["NatGateways"][0]["State"] == "deleted"
+
+
+def test_ec2_nat_gateway_filter_by_vpc(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.101.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+ subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.101.1.0/24")
+ subnet_id = subnet["Subnet"]["SubnetId"]
+ ec2.create_nat_gateway(SubnetId=subnet_id, ConnectivityType="private")
+
+ desc = ec2.describe_nat_gateways(
+ Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
+ )
+ assert all(n["VpcId"] == vpc_id for n in desc["NatGateways"])
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: Network ACLs
+# ---------------------------------------------------------------------------
+
+def test_ec2_network_acl_crud(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.102.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+
+ resp = ec2.create_network_acl(VpcId=vpc_id)
+ acl_id = resp["NetworkAcl"]["NetworkAclId"]
+ assert acl_id.startswith("acl-")
+ assert resp["NetworkAcl"]["VpcId"] == vpc_id
+ assert resp["NetworkAcl"]["IsDefault"] is False
+
+ desc = ec2.describe_network_acls(NetworkAclIds=[acl_id])
+ assert len(desc["NetworkAcls"]) == 1
+ assert desc["NetworkAcls"][0]["NetworkAclId"] == acl_id
+
+ ec2.create_network_acl_entry(
+ NetworkAclId=acl_id,
+ RuleNumber=100,
+ Protocol="-1",
+ RuleAction="allow",
+ Egress=False,
+ CidrBlock="0.0.0.0/0",
+ )
+ desc2 = ec2.describe_network_acls(NetworkAclIds=[acl_id])
+ assert len(desc2["NetworkAcls"][0]["Entries"]) == 1
+
+ ec2.delete_network_acl_entry(NetworkAclId=acl_id, RuleNumber=100, Egress=False)
+ desc3 = ec2.describe_network_acls(NetworkAclIds=[acl_id])
+ assert len(desc3["NetworkAcls"][0]["Entries"]) == 0
+
+ ec2.delete_network_acl(NetworkAclId=acl_id)
+ desc4 = ec2.describe_network_acls(NetworkAclIds=[acl_id])
+ assert len(desc4["NetworkAcls"]) == 0
+
+
+def test_ec2_network_acl_replace_entry(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.103.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+ resp = ec2.create_network_acl(VpcId=vpc_id)
+ acl_id = resp["NetworkAcl"]["NetworkAclId"]
+
+ ec2.create_network_acl_entry(
+ NetworkAclId=acl_id, RuleNumber=200, Protocol="-1",
+ RuleAction="deny", Egress=False, CidrBlock="10.0.0.0/8"
+ )
+ ec2.replace_network_acl_entry(
+ NetworkAclId=acl_id, RuleNumber=200, Protocol="-1",
+ RuleAction="allow", Egress=False, CidrBlock="10.0.0.0/8"
+ )
+ desc = ec2.describe_network_acls(NetworkAclIds=[acl_id])
+ entries = desc["NetworkAcls"][0]["Entries"]
+ assert len(entries) == 1
+ assert entries[0]["RuleAction"] == "allow"
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: Flow Logs
+# ---------------------------------------------------------------------------
+
+def test_ec2_flow_logs_crud(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.104.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+
+ resp = ec2.create_flow_logs(
+ ResourceIds=[vpc_id],
+ ResourceType="VPC",
+ TrafficType="ALL",
+ LogDestinationType="cloud-watch-logs",
+ LogGroupName="/aws/vpc/flowlogs",
+ )
+ assert resp["Unsuccessful"] == []
+ fl_ids = resp["FlowLogIds"]
+ assert len(fl_ids) == 1
+ assert fl_ids[0].startswith("fl-")
+
+ desc = ec2.describe_flow_logs(FlowLogIds=fl_ids)
+ assert len(desc["FlowLogs"]) == 1
+ assert desc["FlowLogs"][0]["FlowLogId"] == fl_ids[0]
+ assert desc["FlowLogs"][0]["FlowLogStatus"] == "ACTIVE"
+
+ ec2.delete_flow_logs(FlowLogIds=fl_ids)
+ desc2 = ec2.describe_flow_logs(FlowLogIds=fl_ids)
+ assert len(desc2["FlowLogs"]) == 0
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: VPC Peering Connections
+# ---------------------------------------------------------------------------
+
+def test_ec2_vpc_peering_crud(ec2):
+ vpc1 = ec2.create_vpc(CidrBlock="10.105.0.0/16")
+ vpc2 = ec2.create_vpc(CidrBlock="10.106.0.0/16")
+ vpc_id1 = vpc1["Vpc"]["VpcId"]
+ vpc_id2 = vpc2["Vpc"]["VpcId"]
+
+ resp = ec2.create_vpc_peering_connection(VpcId=vpc_id1, PeerVpcId=vpc_id2)
+ pcx = resp["VpcPeeringConnection"]
+ pcx_id = pcx["VpcPeeringConnectionId"]
+ assert pcx_id.startswith("pcx-")
+ assert pcx["Status"]["Code"] == "pending-acceptance"
+
+ accepted = ec2.accept_vpc_peering_connection(VpcPeeringConnectionId=pcx_id)
+ assert accepted["VpcPeeringConnection"]["Status"]["Code"] == "active"
+
+ desc = ec2.describe_vpc_peering_connections(VpcPeeringConnectionIds=[pcx_id])
+ assert len(desc["VpcPeeringConnections"]) == 1
+ assert desc["VpcPeeringConnections"][0]["Status"]["Code"] == "active"
+
+ ec2.delete_vpc_peering_connection(VpcPeeringConnectionId=pcx_id)
+ desc2 = ec2.describe_vpc_peering_connections(VpcPeeringConnectionIds=[pcx_id])
+ assert desc2["VpcPeeringConnections"][0]["Status"]["Code"] == "deleted"
+
+
+def test_ec2_vpc_peering_not_found(ec2):
+ from botocore.exceptions import ClientError
+ with pytest.raises(ClientError) as exc:
+ ec2.accept_vpc_peering_connection(VpcPeeringConnectionId="pcx-nonexistent")
+ assert "NotFound" in exc.value.response["Error"]["Code"]
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: DHCP Options
+# ---------------------------------------------------------------------------
+
+def test_ec2_dhcp_options_crud(ec2):
+ resp = ec2.create_dhcp_options(
+ DhcpConfigurations=[
+ {"Key": "domain-name", "Values": ["example.internal"]},
+ {"Key": "domain-name-servers", "Values": ["10.0.0.1", "10.0.0.2"]},
+ ]
+ )
+ dopt = resp["DhcpOptions"]
+ dopt_id = dopt["DhcpOptionsId"]
+ assert dopt_id.startswith("dopt-")
+
+ desc = ec2.describe_dhcp_options(DhcpOptionsIds=[dopt_id])
+ assert len(desc["DhcpOptions"]) == 1
+ configs = {c["Key"]: [v["Value"] for v in c["Values"]]
+ for c in desc["DhcpOptions"][0]["DhcpConfigurations"]}
+ assert configs["domain-name"] == ["example.internal"]
+ assert "10.0.0.1" in configs["domain-name-servers"]
+
+ vpc = ec2.create_vpc(CidrBlock="10.107.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+ ec2.associate_dhcp_options(DhcpOptionsId=dopt_id, VpcId=vpc_id)
+
+ ec2.delete_dhcp_options(DhcpOptionsId=dopt_id)
+ desc2 = ec2.describe_dhcp_options(DhcpOptionsIds=[dopt_id])
+ assert len(desc2["DhcpOptions"]) == 0
+
+
+def test_ec2_dhcp_options_not_found(ec2):
+ from botocore.exceptions import ClientError
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_dhcp_options(DhcpOptionsId="dopt-nonexistent")
+ assert "NotFound" in exc.value.response["Error"]["Code"]
+
+
+# ---------------------------------------------------------------------------
+# VPC gaps: Egress-Only Internet Gateways
+# ---------------------------------------------------------------------------
+
+def test_ec2_egress_only_igw_crud(ec2):
+ vpc = ec2.create_vpc(CidrBlock="10.108.0.0/16")
+ vpc_id = vpc["Vpc"]["VpcId"]
+
+ resp = ec2.create_egress_only_internet_gateway(VpcId=vpc_id)
+ eigw = resp["EgressOnlyInternetGateway"]
+ eigw_id = eigw["EgressOnlyInternetGatewayId"]
+ assert eigw_id.startswith("eigw-")
+ assert eigw["Attachments"][0]["State"] == "attached"
+ assert eigw["Attachments"][0]["VpcId"] == vpc_id
+
+ desc = ec2.describe_egress_only_internet_gateways(
+ EgressOnlyInternetGatewayIds=[eigw_id]
+ )
+ assert len(desc["EgressOnlyInternetGateways"]) == 1
+ assert desc["EgressOnlyInternetGateways"][0]["EgressOnlyInternetGatewayId"] == eigw_id
+
+ ec2.delete_egress_only_internet_gateway(EgressOnlyInternetGatewayId=eigw_id)
+ desc2 = ec2.describe_egress_only_internet_gateways(
+ EgressOnlyInternetGatewayIds=[eigw_id]
+ )
+ assert len(desc2["EgressOnlyInternetGateways"]) == 0
+
+
+def test_ec2_egress_only_igw_not_found(ec2):
+ from botocore.exceptions import ClientError
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_egress_only_internet_gateway(
+ EgressOnlyInternetGatewayId="eigw-nonexistent"
+ )
+ assert "NotFound" in exc.value.response["Error"]["Code"]