Skip to content

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

fix(route53): keep VPC associations on private hosted zones (#2303)

Kacper Harabasz0943582c9230
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f51a58b2..82692a83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.
+
+### Fixed
+- **Route 53 — private hosted zones keep their VPC** — `CreateHostedZone` with a `VPC` made a public zone and dropped the VPC, so Terraform's `aws_route53_zone` with a `vpc` block planned to add it again on every run; the zone is now private, the response carries the `VPC` instead of a delegation set, also on a `CallerReference` replay, and `GetHostedZone` returns its `VPCs`. Contributed by @kharabasz.
## [1.5.30] — 2026-10-20
### Added
diff --git a/README.md b/README.md
index 9bc933b8..2f6ebf99 100644
--- a/README.md
+++ b/README.md
@@ -639,7 +639,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation, RenameTable, GetTableBucketEncryption, PutTableBucketEncryption, DeleteTableBucketEncryption, GetTableBucketMaintenanceConfiguration, PutTableBucketMaintenanceConfiguration, GetTableBucketPolicy, PutTableBucketPolicy, DeleteTableBucketPolicy, GetTableBucketStorageClass, PutTableBucketStorageClass, GetTableBucketMetricsConfiguration, PutTableBucketMetricsConfiguration, DeleteTableBucketMetricsConfiguration, GetTableEncryption, GetTableStorageClass, GetTableMaintenanceConfiguration, PutTableMaintenanceConfiguration, GetTableMaintenanceJobStatus, GetTablePolicy, PutTablePolicy, DeleteTablePolicy, TagResource, UntagResource, ListTagsForResource | Iceberg-format tables; unset encryption, storage class and maintenance return the documented defaults; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog, each catalog scoped to the table bucket ARN in its prefix and commits checked against their update requirements; data files in S3, metadata in memory |
| **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, GetDatabase, ListDatabases, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; databases and tables come from the Glue Data Catalog, and `CREATE EXTERNAL TABLE` / `DROP TABLE` change it; S3 Tables are queryable as `"s3tablescatalog/<bucket>".<namespace>.<table>`; partitioned Glue tables keep their Glue partition types; 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`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp`; `ProcessingConfiguration.Processors[].Type=Lambda` invoked per-batch with the AWS-shape event (`{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`) — `Ok` records ship the transformed data downstream, `Dropped`/`ProcessingFailed` are omitted, Lambda failures pass records through unchanged (best-effort per AWS); S3 prefixes evaluate timestamp, random-string, error-output-type and dynamic partition keys (JQ `MetadataExtraction` or Lambda `partitionKeys`); `DataFormatConversionConfiguration` writes Parquet from the Glue schema (DuckDB, full image) |
-| **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 |
+| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; private zones with VPC associations; alias records, weighted/failover/latency routing; marker-based pagination |
| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, AssociateIamInstanceProfile, DescribeIamInstanceProfileAssociations, DisassociateIamInstanceProfile, ReplaceIamInstanceProfileAssociation, DescribeImages, RegisterImage, DeregisterImage, ModifyImageAttribute, DescribeImageAttribute, ResetImageAttribute, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreatePlacementGroup, DeletePlacementGroup, DescribePlacementGroups, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, ModifyVpcEndpoint, DescribePrefixLists, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, DescribeAddressesAttribute, 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, CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList, DeleteManagedPrefixList, CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway, DetachVpnGateway, DeleteVpnGateway, EnableVgwRoutePropagation, DisableVgwRoutePropagation, CreateCustomerGateway, DescribeCustomerGateways, DeleteCustomerGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations, DescribeInstanceStatus, DescribeVpcClassicLink, DescribeVpcClassicLinkDnsSupport, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate, CreateFleet, DescribeFleets | 133 actions; EC2 Fleet (`CreateFleet` / `DescribeFleets`) with `instant`-type synchronous launch and `maintain` / `request` async fulfillment, multi-config × multi-override round-robin capacity distribution, and `DefaultTargetCapacityType`-driven spot/on-demand selection — unblocks Karpenter / Cluster Autoscaler local validation; IAM instance profile association lifecycle is persisted (`Associate*`, `Describe*`, `Replace*`, `Disassociate*`) so Terraform `aws_instance.iam_instance_profile` round-trips without drift; `AuthorizeSecurityGroupIngress` is idempotent on duplicate rules (same behavior as egress; avoids Terraform re-apply failures); metadata-only instance records by default — `RegisterImage` with a container reference makes an AMI whose launches get a real box, so SSM Run Command returns a real exit code (see *Instances with a real box*); CreateVpc provisions per-VPC default route table, network ACL, and security group; cross-account AMI sharing via launch permissions (`ModifyImageAttribute` add/remove, `Group=all` makes the image public, `DescribeImages` shows shared images with the owner's `OwnerId`, `ExecutableUsers` honored, shared AMIs launch); full Terraform VPC module v6.6.0 compatible; VPN/Customer gateways, managed prefix lists, VPC endpoints with modify support; launch templates with versioning ($Latest/$Default) |
| **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, PutFileSystemPolicy, DescribeFileSystemPolicy, DeleteFileSystemPolicy, UpdateFileSystemProtection, CreateReplicationConfiguration, DescribeReplicationConfigurations, DeleteReplicationConfiguration, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist or it is in a replication configuration; `CreateMountTarget` checks the subnet, security groups, zone and address; replication creates records only, nothing is copied; CFN `AWS::EFS::FileSystem`, `MountTarget` and `AccessPoint` supported |
diff --git a/ministack/services/route53.py b/ministack/services/route53.py
index 222280c8..7e1eb513 100644
--- a/ministack/services/route53.py
+++ b/ministack/services/route53.py
@@ -8,6 +8,8 @@ Supports:
Hosted Zones: CreateHostedZone, GetHostedZone, DeleteHostedZone,
ListHostedZones, ListHostedZonesByName,
UpdateHostedZoneComment
+ Private zones: AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone,
+ ListHostedZonesByVPC
Record Sets: ChangeResourceRecordSets, ListResourceRecordSets
Changes: GetChange
Health Checks: CreateHealthCheck, GetHealthCheck, DeleteHealthCheck,
@@ -31,7 +33,7 @@ from xml.etree.ElementTree import Element, SubElement, tostring
from defusedxml.ElementTree import fromstring
-from ministack.core.responses import AccountScopedDict, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
logger = logging.getLogger("route53")
@@ -103,6 +105,9 @@ def reset():
_ID_CHARS = string.ascii_uppercase + string.digits
+_zone_id_re = re.compile(r"^Z[A-Z0-9]+$")
+
+
def _zone_id() -> str:
return "Z" + "".join(random.choices(_ID_CHARS, k=13))
@@ -115,6 +120,13 @@ def _hc_id() -> str:
return new_uuid()
+def _new_change(comment: str = "") -> dict:
+ """Record a PENDING change so GetChange can find it. Call under _lock."""
+ change = {"id": _change_id(), "status": "PENDING", "submitted_at": _now_iso(), "comment": comment}
+ _changes[change["id"]] = change
+ return change
+
+
# ─── XML helpers ─────────────────────────────────────────────────────────────
def _now_iso() -> str:
@@ -241,6 +253,52 @@ def _build_hosted_zone_el(parent: Element, zone: dict):
)
+def _build_vpc_el(parent: Element, vpc: dict):
+ el = SubElement(parent, "VPC")
+ SubElement(el, "VPCRegion").text = vpc["VPCRegion"]
+ SubElement(el, "VPCId").text = vpc["VPCId"]
+
+
+def _parse_vpc(root):
+ """The request's <VPC> element as ({VPCRegion, VPCId}, None), (None, None)
+ when absent, or (None, error response) when incomplete."""
+ vpc_el = _find(root, "VPC")
+ if vpc_el is None:
+ return None, None
+ vpc_id = _text(vpc_el, "VPCId")
+ if not vpc_id.startswith("vpc-"):
+ return None, _error_response("InvalidVPCId", f"The VPC ID '{vpc_id}' is not valid.")
+ # Route 53 is a global endpoint, so the request region says nothing about
+ # where the VPC lives; the VPC element needs both members.
+ vpc_region = _text(vpc_el, "VPCRegion")
+ if not vpc_region:
+ return None, _error_response("InvalidInput", "VPCRegion is required with VPCId.")
+ return {"VPCRegion": vpc_region, "VPCId": vpc_id}, None
+
+
+def _vpc_key(vpc: dict) -> tuple:
+ return (vpc["VPCRegion"], vpc["VPCId"])
+
+
+def _zone_has_vpc(zone: dict, vpc: dict) -> bool:
+ return any(_vpc_key(v) == _vpc_key(vpc) for v in zone.get("vpcs", []))
+
+
+def _same_name_zone_with_vpc(name: str, vpc: dict, exclude_id: str = ""):
+ """Another private zone of this name already associated with the VPC. Call under _lock."""
+ return next((z for z in _zones.values()
+ if z["id"] != exclude_id and z.get("private") and z["name"] == name
+ and _zone_has_vpc(z, vpc)), None)
+
+
+def _build_zone_location_el(parent: Element, zone: dict):
+ """CreateHostedZone answers a private zone with its VPC, a public one with its delegation set."""
+ if zone.get("private") and zone.get("vpcs"):
+ _build_vpc_el(parent, zone["vpcs"][0])
+ else:
+ _build_delegation_set_el(parent, zone["name"])
+
+
def _build_delegation_set_el(parent: Element, zone_name: str):
ds = SubElement(parent, "DelegationSet")
SubElement(ds, "NameServers")
@@ -429,38 +487,41 @@ def _create_hosted_zone(body: bytes, query_params: dict):
cfg_el = _find(root, "HostedZoneConfig")
comment = _text(cfg_el, "Comment") if cfg_el is not None else ""
private = _text(cfg_el, "PrivateZone", "false").lower() == "true" if cfg_el is not None else False
+ # A VPC in the request makes the zone private and is its first association.
+ vpc, err = _parse_vpc(root)
+ if err:
+ return err
+ if vpc:
+ private = True
with _lock:
if caller_ref in _caller_refs:
- existing_id = _caller_refs[caller_ref]
- zone = _zones[existing_id]
- change = {"id": _change_id(), "status": "PENDING", "submitted_at": _now_iso(), "comment": ""}
- def build(root):
- _build_hosted_zone_el(root, zone)
- _build_change_info_el(root, change)
- _build_delegation_set_el(root, zone["name"])
- return _xml_response("CreateHostedZoneResponse", build, 201)
-
- zone_id = _zone_id()
- zone = {
- "id": zone_id,
- "name": name,
- "caller_reference": caller_ref,
- "comment": comment,
- "private": private,
- }
- _zones[zone_id] = zone
- _records[zone_id] = _default_records(name)
- _caller_refs[caller_ref] = zone_id
-
- change_id = _change_id()
- change = {"id": change_id, "status": "PENDING", "submitted_at": _now_iso(), "comment": ""}
- _changes[change_id] = change
+ # Idempotent replay: answer with the stored zone, private or public.
+ zone = _zones[_caller_refs[caller_ref]]
+ else:
+ if vpc and _same_name_zone_with_vpc(name, vpc):
+ return _error_response(
+ "ConflictingDomainExists",
+ f"A private hosted zone named {name} is already associated with "
+ f"VPC {vpc['VPCId']} in {vpc['VPCRegion']}.")
+ zone_id = _zone_id()
+ zone = {
+ "id": zone_id,
+ "name": name,
+ "caller_reference": caller_ref,
+ "comment": comment,
+ "private": private,
+ "vpcs": [vpc] if vpc else [],
+ }
+ _zones[zone_id] = zone
+ _records[zone_id] = _default_records(name)
+ _caller_refs[caller_ref] = zone_id
+ change = _new_change()
def build(root):
_build_hosted_zone_el(root, zone)
_build_change_info_el(root, change)
- _build_delegation_set_el(root, name)
+ _build_zone_location_el(root, zone)
return _xml_response("CreateHostedZoneResponse", build, 201)
@@ -473,7 +534,12 @@ def _get_hosted_zone(zone_id: str):
def build(root):
_build_hosted_zone_el(root, zone)
- _build_delegation_set_el(root, zone["name"])
+ if zone.get("private"):
+ vpcs_el = SubElement(root, "VPCs")
+ for vpc in zone.get("vpcs", []):
+ _build_vpc_el(vpcs_el, vpc)
+ else:
+ _build_delegation_set_el(root, zone["name"])
return _xml_response("GetHostedZoneResponse", build)
@@ -493,9 +559,7 @@ def _delete_hosted_zone(zone_id: str):
del _zones[zone_id]
del _records[zone_id]
_caller_refs.pop(zone.get("caller_reference", ""), None)
- change_id = _change_id()
- change = {"id": change_id, "status": "PENDING", "submitted_at": _now_iso(), "comment": ""}
- _changes[change_id] = change
+ change = _new_change()
def build(root):
_build_change_info_el(root, change)
@@ -654,9 +718,7 @@ def _change_resource_record_sets(zone_id: str, body: bytes):
return _error_response("InvalidInput", f"Unknown action: {action}")
_records[zone_id] = current
- change_id = _change_id()
- change = {"id": change_id, "status": "PENDING", "submitted_at": _now_iso(), "comment": comment}
- _changes[change_id] = change
+ change = _new_change(comment)
def build(root):
_build_change_info_el(root, change)
@@ -747,6 +809,103 @@ def _get_change(change_id: str):
return _xml_response("GetChangeResponse", build)
+# ─── private zone VPC associations ────────────────────────────────────────────
+
+def _parse_vpc_request(body: bytes):
+ """The VPC and optional Comment of an associate/disassociate request."""
+ root = _parse_body(body)
+ if root is None:
+ return None, "", _error_response("InvalidInput", "Missing or invalid request body.")
+ vpc, err = _parse_vpc(root)
+ if err:
+ return None, "", err
+ if not vpc:
+ return None, "", _error_response("InvalidInput", "VPC is required.")
+ return vpc, _text(root, "Comment"), None
+
+
+def _associate_vpc(zone_id: str, body: bytes):
+ vpc, comment, err = _parse_vpc_request(body)
+ if err:
+ return err
+ with _lock:
+ zone = _zones.get(zone_id)
+ if not zone:
+ return _error_response("NoSuchHostedZone", f"No hosted zone found with ID: {zone_id}", 404)
+ if not zone.get("private"):
+ return _error_response("PublicZoneVPCAssociation",
+ "You can't associate a VPC with a public hosted zone.")
+ if _zone_has_vpc(zone, vpc) or _same_name_zone_with_vpc(zone["name"], vpc, exclude_id=zone_id):
+ return _error_response(
+ "ConflictingDomainExists",
+ f"The VPC {vpc['VPCId']} in {vpc['VPCRegion']} is already associated with "
+ f"a hosted zone named {zone['name']}.")
+ zone.setdefault("vpcs", []).append(vpc)
+ change = _new_change(comment)
+ return _xml_response("AssociateVPCWithHostedZoneResponse",
+ lambda root: _build_change_info_el(root, change))
+
+
+def _disassociate_vpc(zone_id: str, body: bytes):
+ vpc, comment, err = _parse_vpc_request(body)
+ if err:
+ return err
+ with _lock:
+ zone = _zones.get(zone_id)
+ if not zone:
+ return _error_response("NoSuchHostedZone", f"No hosted zone found with ID: {zone_id}", 404)
+ if not _zone_has_vpc(zone, vpc):
+ return _error_response(
+ "VPCAssociationNotFound",
+ f"The VPC {vpc['VPCId']} in {vpc['VPCRegion']} is not associated with the hosted zone.", 404)
+ if len(zone["vpcs"]) == 1:
+ return _error_response("LastVPCAssociation",
+ "A private hosted zone must stay associated with at least one VPC.")
+ zone["vpcs"] = [v for v in zone["vpcs"] if _vpc_key(v) != _vpc_key(vpc)]
+ change = _new_change(comment)
+ return _xml_response("DisassociateVPCFromHostedZoneResponse",
+ lambda root: _build_change_info_el(root, change))
+
+
+def _list_hosted_zones_by_vpc(query_params: dict):
+ def q(name):
+ v = query_params.get(name, "")
+ return (v[0] if isinstance(v, list) else v) or ""
+ vpc_id, vpc_region, next_token = q("vpcid"), q("vpcregion"), q("nexttoken")
+ if not vpc_id or not vpc_region:
+ return _error_response("InvalidInput", "vpcid and vpcregion are required.")
+ try:
+ max_items = min(int(q("maxitems") or 100), 100)
+ except ValueError:
+ return _error_response("InvalidInput", "maxitems must be an integer.")
+ if max_items < 1:
+ return _error_response("InvalidInput", "maxitems must be at least 1.")
+ target = {"VPCRegion": vpc_region, "VPCId": vpc_id}
+ with _lock:
+ zones = sorted((z for z in _zones.values() if _zone_has_vpc(z, target)), key=lambda z: z["id"])
+ # NextToken is the id of the first zone on the next page.
+ if next_token:
+ if not _zone_id_re.match(next_token):
+ return _error_response("InvalidPaginationToken", "The NextToken value is not valid.")
+ zones = [z for z in zones if z["id"] >= next_token]
+ page = zones[:max_items]
+ token = zones[max_items]["id"] if len(zones) > max_items else None
+
+ def build(root):
+ summaries = SubElement(root, "HostedZoneSummaries")
+ for zone in page:
+ item = SubElement(summaries, "HostedZoneSummary")
+ SubElement(item, "HostedZoneId").text = zone["id"]
+ SubElement(item, "Name").text = zone["name"]
+ owner = SubElement(item, "Owner")
+ SubElement(owner, "OwningAccount").text = get_account_id()
+ SubElement(root, "MaxItems").text = str(max_items)
+ if token:
+ SubElement(root, "NextToken").text = token
+
+ return _xml_response("ListHostedZonesByVPCResponse", build)
+
+
# ─── health checks ────────────────────────────────────────────────────────────
def _create_health_check(body: bytes):
@@ -924,6 +1083,17 @@ async def handle_request(method, path, headers, body, query_params):
if method == "GET" and p == "/hostedzonesbyname":
return _list_hosted_zones_by_name(query_params)
+ # GET /hostedzonesbyvpc
+ if method == "GET" and p == "/hostedzonesbyvpc":
+ return _list_hosted_zones_by_vpc(query_params)
+
+ # POST /hostedzone/{id}/associatevpc | /disassociatevpc
+ m = re.match(r"^/hostedzone/([^/]+)/(associatevpc|disassociatevpc)$", p)
+ if m and method == "POST":
+ if m.group(2) == "associatevpc":
+ return _associate_vpc(m.group(1), body)
+ return _disassociate_vpc(m.group(1), body)
+
# GET|DELETE|POST /hostedzone/{id}
m = re.match(r"^/hostedzone/([^/]+)$", p)
if m:
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 569b0353..053405fb 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -639,6 +639,36 @@ def test_backup_round_trip():
_round_trip("backup", "backup", populate, observe)
+def test_route53_private_zone_vpcs_round_trip():
+ vpc = {"VPCRegion": "us-west-2", "VPCId": "vpc-0123456789abcdef0"}
+ body = (
+ '<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">'
+ "<Name>persisted.example.internal</Name><CallerReference>persist-1</CallerReference>"
+ f"<VPC><VPCRegion>{vpc['VPCRegion']}</VPCRegion><VPCId>{vpc['VPCId']}</VPCId></VPC>"
+ "</CreateHostedZoneRequest>"
+ ).encode()
+ zone_ids = []
+
+ def populate(mod):
+ status, _, _ = mod._create_hosted_zone(body, {})
+ assert status == 201
+ zone_ids.extend(mod._zones.keys())
+ # A zone persisted before VPC associations existed has no "vpcs" key.
+ mod._zones["ZLEGACYPRIVATE1"] = {
+ "id": "ZLEGACYPRIVATE1", "name": "legacy.example.internal.",
+ "caller_reference": "legacy", "comment": "", "private": True,
+ }
+
+ def observe(mod):
+ assert mod._zones[zone_ids[0]]["vpcs"] == [vpc]
+ status, _, out = mod._list_hosted_zones_by_vpc({"vpcid": vpc["VPCId"], "vpcregion": vpc["VPCRegion"]})
+ assert status == 200 and zone_ids[0].encode() in out
+ status, _, out = mod._get_hosted_zone("ZLEGACYPRIVATE1")
+ assert status == 200 and b"<VPCs />" in out
+
+ _round_trip("route53", "route53", populate, observe)
+
+
def test_s3_mrap_round_trip():
"""A multi-region access point outlives a restart. Its alias is baked into
client configuration, so member buckets coming back without the alias
diff --git a/tests/test_route53.py b/tests/test_route53.py
index 11057c7b..5eda037c 100644
--- a/tests/test_route53.py
+++ b/tests/test_route53.py
@@ -1,7 +1,11 @@
+import os
import time
+import uuid
+import boto3
import pytest
from botocore.exceptions import ClientError
+from conftest import make_client
def test_route53_create_and_get_hosted_zone(r53):
@@ -686,3 +690,246 @@ def test_unicode_route53_zone_comment(r53):
zone_id = resp["HostedZone"]["Id"].split("/")[-1]
get = r53.get_hosted_zone(Id=zone_id)
assert get["HostedZone"]["Config"]["Comment"] == "zona en español — Ünïcödé"
+
+
+
+# ─── private hosted zones ─────────────────────────────────────────────────────
+
+_VPC_A = {"VPCRegion": "us-east-1", "VPCId": "vpc-0123456789abcdef0"}
+_VPC_B = {"VPCRegion": "us-west-2", "VPCId": "vpc-0fedcba9876543210"}
+
+
+def _assert_error(exc, code, status):
+ assert exc.value.response["Error"]["Code"] == code
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == status
+
+
+def private_zone(r53):
+ """Factory for private zones, deleted after the test even when it fails."""
+ created = []
+
+ def create(name=None, vpc=_VPC_A, caller_ref=None):
+ resp = r53.create_hosted_zone(
+ Name=name or f"pz-{uuid.uuid4().hex[:8]}.example.internal",
+ CallerReference=caller_ref or str(uuid.uuid4()), VPC=vpc)
+ created.append(resp["HostedZone"]["Id"].split("/")[-1])
+ return resp
+
+ yield create
+ for zone_id in created:
+ try:
+ r53.delete_hosted_zone(Id=zone_id)
+ except ClientError:
+ pass
+
+
+def test_route53_private_zone_create_returns_vpc(r53, private_zone):
+ created = private_zone()
+ assert created["ResponseMetadata"]["HTTPStatusCode"] == 201
+ assert created["HostedZone"]["Config"]["PrivateZone"] is True
+ assert created["VPC"] == _VPC_A
+ assert "DelegationSet" not in created
+
+ got = r53.get_hosted_zone(Id=created["HostedZone"]["Id"].split("/")[-1])
+ assert got["HostedZone"]["Config"]["PrivateZone"] is True
+ assert got["VPCs"] == [_VPC_A]
+ assert "DelegationSet" not in got
+
+
+def test_route53_private_zone_caller_reference_replay(r53, private_zone):
+ ref = str(uuid.uuid4())
+ first = private_zone(caller_ref=ref)
+ replay = r53.create_hosted_zone(
+ Name=first["HostedZone"]["Name"], CallerReference=ref, VPC=_VPC_A)
+ assert replay["ResponseMetadata"]["HTTPStatusCode"] == 201
+ assert replay["HostedZone"]["Id"] == first["HostedZone"]["Id"]
+ assert replay["VPC"] == _VPC_A
+ assert "DelegationSet" not in replay
+ change_id = replay["ChangeInfo"]["Id"].split("/")[-1]
+ assert r53.get_change(Id=change_id)["ChangeInfo"]["Id"] == replay["ChangeInfo"]["Id"]
+
+
+def test_route53_public_zone_has_no_vpcs(r53):
+ created = r53.create_hosted_zone(Name="public-assoc.example.com", CallerReference=str(uuid.uuid4()))
+ zone_id = created["HostedZone"]["Id"].split("/")[-1]
+ try:
+ assert "DelegationSet" in created and "VPC" not in created
+ got = r53.get_hosted_zone(Id=zone_id)
+ assert got["HostedZone"]["Config"]["PrivateZone"] is False
+ assert "VPCs" not in got and "DelegationSet" in got
+ with pytest.raises(ClientError) as exc:
+ r53.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_A)
+ _assert_error(exc, "PublicZoneVPCAssociation", 400)
+ with pytest.raises(ClientError) as exc:
+ r53.disassociate_vpc_from_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_A)
+ _assert_error(exc, "VPCAssociationNotFound", 404)
+ finally:
+ r53.delete_hosted_zone(Id=zone_id)
+
+
+def test_route53_private_zone_associate_and_disassociate(r53, private_zone):
+ zone_id = private_zone()["HostedZone"]["Id"].split("/")[-1]
+ resp = r53.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B, Comment="second")
+ assert resp["ChangeInfo"]["Comment"] == "second"
+ assert r53.get_change(Id=resp["ChangeInfo"]["Id"].split("/")[-1])["ChangeInfo"]["Status"] in (
+ "PENDING", "INSYNC")
+ assert r53.get_hosted_zone(Id=zone_id)["VPCs"] == [_VPC_A, _VPC_B]
+
+ with pytest.raises(ClientError) as exc:
+ r53.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ _assert_error(exc, "ConflictingDomainExists", 400)
+
+ r53.disassociate_vpc_from_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ assert r53.get_hosted_zone(Id=zone_id)["VPCs"] == [_VPC_A]
+ with pytest.raises(ClientError) as exc:
+ r53.disassociate_vpc_from_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ _assert_error(exc, "VPCAssociationNotFound", 404)
+ with pytest.raises(ClientError) as exc:
+ r53.disassociate_vpc_from_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_A)
+ _assert_error(exc, "LastVPCAssociation", 400)
+ # The same VPC id in another region is a different VPC.
+ with pytest.raises(ClientError) as exc:
+ r53.disassociate_vpc_from_hosted_zone(
+ HostedZoneId=zone_id, VPC={"VPCRegion": "eu-west-1", "VPCId": _VPC_A["VPCId"]})
+ _assert_error(exc, "VPCAssociationNotFound", 404)
+
+
+def test_route53_private_zone_same_name_conflicts_on_shared_vpc(r53, private_zone):
+ name = f"dup-{uuid.uuid4().hex[:8]}.example.internal"
+ private_zone(name=name)
+ with pytest.raises(ClientError) as exc:
+ r53.create_hosted_zone(Name=name, CallerReference=str(uuid.uuid4()), VPC=_VPC_A)
+ _assert_error(exc, "ConflictingDomainExists", 400)
+
+ other_id = private_zone(name=name, vpc=_VPC_B)["HostedZone"]["Id"].split("/")[-1]
+ with pytest.raises(ClientError) as exc:
+ r53.associate_vpc_with_hosted_zone(HostedZoneId=other_id, VPC=_VPC_A)
+ _assert_error(exc, "ConflictingDomainExists", 400)
+
+
[email protected]("operation", ["associate_vpc_with_hosted_zone", "disassociate_vpc_from_hosted_zone"])
+def test_route53_vpc_association_unknown_zone(r53, operation):
+ with pytest.raises(ClientError) as exc:
+ getattr(r53, operation)(HostedZoneId="ZNOSUCHZONE0001", VPC=_VPC_A)
+ _assert_error(exc, "NoSuchHostedZone", 404)
+
+
[email protected]("vpc,code", [
+ ({"VPCRegion": "us-east-1", "VPCId": "not-a-vpc"}, "InvalidVPCId"),
+ ({"VPCRegion": "us-east-1"}, "InvalidVPCId"),
+ ({"VPCId": "vpc-0123456789abcdef0"}, "InvalidInput"),
+])
+def test_route53_private_zone_rejects_incomplete_vpc(r53, private_zone, vpc, code):
+ with pytest.raises(ClientError) as exc:
+ r53.create_hosted_zone(Name="bad-vpc.example.internal", CallerReference=str(uuid.uuid4()), VPC=vpc)
+ _assert_error(exc, code, 400)
+ zone_id = private_zone()["HostedZone"]["Id"].split("/")[-1]
+ with pytest.raises(ClientError) as exc:
+ r53.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=vpc)
+ _assert_error(exc, code, 400)
+
+
+def test_route53_private_zone_flag_without_vpc_is_accepted(r53):
+ """MiniStack keeps accepting PrivateZone=true with no VPC (Cloud Map relies on it)."""
+ created = r53.create_hosted_zone(
+ Name="flag-only.example.internal", CallerReference=str(uuid.uuid4()),
+ HostedZoneConfig={"PrivateZone": True})
+ zone_id = created["HostedZone"]["Id"].split("/")[-1]
+ try:
+ assert created["HostedZone"]["Config"]["PrivateZone"] is True
+ assert r53.get_hosted_zone(Id=zone_id)["VPCs"] == []
+ finally:
+ r53.delete_hosted_zone(Id=zone_id)
+
+
+def test_route53_private_zone_delete(r53):
+ zone_id = r53.create_hosted_zone(
+ Name="delete-private.example.internal", CallerReference=str(uuid.uuid4()),
+ VPC=_VPC_A)["HostedZone"]["Id"].split("/")[-1]
+ r53.delete_hosted_zone(Id=zone_id)
+ with pytest.raises(ClientError) as exc:
+ r53.get_hosted_zone(Id=zone_id)
+ _assert_error(exc, "NoSuchHostedZone", 404)
+ assert zone_id not in [
+ s["HostedZoneId"] for s in r53.list_hosted_zones_by_vpc(**_VPC_A)["HostedZoneSummaries"]]
+
+
+def test_route53_list_hosted_zones_by_vpc_paginates(r53, private_zone):
+ vpc = {"VPCRegion": "eu-central-1", "VPCId": f"vpc-{uuid.uuid4().hex[:17]}"}
+ ids = sorted(private_zone(vpc=vpc)["HostedZone"]["Id"].split("/")[-1] for _ in range(3))
+ first = r53.list_hosted_zones_by_vpc(VPCId=vpc["VPCId"], VPCRegion=vpc["VPCRegion"], MaxItems="2")
+ assert [s["HostedZoneId"] for s in first["HostedZoneSummaries"]] == ids[:2]
+ assert first["MaxItems"] == "2"
+ assert first["HostedZoneSummaries"][0]["Owner"]["OwningAccount"]
+ second = r53.list_hosted_zones_by_vpc(
+ VPCId=vpc["VPCId"], VPCRegion=vpc["VPCRegion"], MaxItems="2", NextToken=first["NextToken"])
+ assert [s["HostedZoneId"] for s in second["HostedZoneSummaries"]] == ids[2:]
+ assert "NextToken" not in second
+
+
+def test_route53_list_hosted_zones_by_vpc_filters_and_validates(r53, private_zone):
+ vpc = {"VPCRegion": "ap-south-1", "VPCId": f"vpc-{uuid.uuid4().hex[:17]}"}
+ zone_id = private_zone(vpc=vpc)["HostedZone"]["Id"].split("/")[-1]
+ match = r53.list_hosted_zones_by_vpc(VPCId=vpc["VPCId"], VPCRegion=vpc["VPCRegion"])
+ assert [s["HostedZoneId"] for s in match["HostedZoneSummaries"]] == [zone_id]
+ # Same VPC id, other region: no match.
+ other = r53.list_hosted_zones_by_vpc(VPCId=vpc["VPCId"], VPCRegion="us-east-2")
+ assert other["HostedZoneSummaries"] == []
+ assert "NextToken" not in other
+ with pytest.raises(ClientError) as exc:
+ r53.list_hosted_zones_by_vpc(VPCId=vpc["VPCId"], VPCRegion=vpc["VPCRegion"], NextToken="bogus")
+ _assert_error(exc, "InvalidPaginationToken", 400)
+
+
+def test_route53_list_hosted_zones_by_vpc_requires_region():
+ # botocore enforces VPCRegion client-side; turn that off to reach the server.
+ client = make_client("route53", {"parameter_validation": False})
+ with pytest.raises(ClientError) as exc:
+ client.list_hosted_zones_by_vpc(VPCId=_VPC_A["VPCId"])
+ _assert_error(exc, "InvalidInput", 400)
+
+
+def test_route53_private_zones_are_account_scoped(r53, private_zone):
+ vpc = {"VPCRegion": "us-east-1", "VPCId": f"vpc-{uuid.uuid4().hex[:17]}"}
+ zone_id = private_zone(vpc=vpc)["HostedZone"]["Id"].split("/")[-1]
+ other = boto3.client(
+ "route53", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name="us-east-1", aws_access_key_id="222233334444", aws_secret_access_key="test")
+ assert other.list_hosted_zones_by_vpc(**vpc)["HostedZoneSummaries"] == []
+ with pytest.raises(ClientError) as exc:
+ other.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ _assert_error(exc, "NoSuchHostedZone", 404)
+ assert r53.get_hosted_zone(Id=zone_id)["VPCs"] == [vpc]
+
+
[email protected]("permission", ["none", "allow", "other-zone"])
+def test_route53_associate_vpc_permission_contract(auth_enabled, iam_user, private_zone, permission):
+ zone_id = private_zone()["HostedZone"]["Id"].split("/")[-1]
+ statements = []
+ if permission != "none":
+ resource_zone = "ZOTHERZONE0001" if permission == "other-zone" else zone_id
+ statements.append({"Effect": "Allow", "Action": "route53:AssociateVPCWithHostedZone",
+ "Resource": f"arn:aws:route53:::hostedzone/{resource_zone}"})
+ policy = {"Version": "2012-10-17", "Statement": statements} if statements else None
+ client = iam_user(policy=policy).client("route53")
+ if auth_enabled and permission != "allow":
+ with pytest.raises(ClientError) as exc:
+ client.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ else:
+ resp = client.associate_vpc_with_hosted_zone(HostedZoneId=zone_id, VPC=_VPC_B)
+ assert resp["ChangeInfo"]["Status"] in ("PENDING", "INSYNC")
+
+
+def test_route53_list_hosted_zones_by_vpc_permission_contract(auth_enabled, iam_user):
+ client = iam_user().client("route53")
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ client.list_hosted_zones_by_vpc(**_VPC_A)
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+ else:
+ assert "HostedZoneSummaries" in client.list_hosted_zones_by_vpc(**_VPC_A)