Skip to content

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

fix(rds): keep the cluster DNS endpoint across StopDBCluster/StartDBCluster (#1770)

Jay Janssene0ba93894e69
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88f237b7..9a43bbf3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **RDS — StopDBCluster/StartDBCluster no longer rewrites the cluster endpoint from its DNS name to a raw container address** — restarting a cluster's shared container reported the container's IP in place of the `*.rds.amazonaws.com` name handed out at creation, even though the name still resolved to the restarted container. Connection strings kept working by accident or broke outright once the address was reused, and hostname-verified TLS could not match the address. The restart now reports the same registered network alias the first launch does, while the internal address and readiness probe keep using the refreshed container IP. The reader endpoint, in turn, only derives its `cluster-ro-` name when that name was actually registered on the backing container.
+
- **IAM — three calls are authorized against the action and resource AWS uses** — a Lambda Function URL invoke is checked against its function ARN, alias qualifier included, and supplies `lambda:FunctionUrlAuthType`, so the policy `grantInvokeUrl` writes matches. The WebSocket `@connections` API asks for `execute-api:ManageConnections` instead of `execute-api:Invoke`. `iot-jobs-data` operations are authorized under `iotjobsdata:`, except `StartCommandExecution`, which stays on `iot:`. A policy written for the old action names stops matching, as on AWS. Contributed by @iot-rocket.
- **IoT — the registered-certificate event comes from the device connect** — `RegisterCertificate` published `$aws/events/certificates/registered/{caCertificateId}`, and an mTLS connect with an unknown certificate got CONNACK 5 with nothing created. AWS publishes the event only on the connect: a certificate signed by an ACTIVE CA with auto-registration enabled is created `PENDING_ACTIVATION`, the event carries `sourceIp`, and the connection closes without a CONNACK. The listener now does the same, and `RegisterCertificate` with status `PENDING_ACTIVATION` is `CertificateStateException` 406. Contributed by @iot-rocket.
- **IoT — `DescribeEndpoint` refuses the retired `iot:Data` and `iot:Jobs` types** — both returned a hostname, so a client could keep using an endpoint type AWS no longer serves. AWS answers `InvalidRequestException` 400 and points to `iot:Data-ATS`; both types now get the same errors and messages. Contributed by @iot-rocket.
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 7c0bffcd..539d26f0 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -1241,6 +1241,14 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
},
"_shared_internal_address": internal_host,
"_shared_internal_port": internal_port,
+ # The reader alias this container actually carries. Only a name
+ # registered as a network alias may be published as the reader
+ # endpoint; PG clusters launched with replication on carry the
+ # writer name only, and a later demotion must not invent a
+ # reader name nothing resolves.
+ "_shared_reader_alias": (
+ endpoint_aliases[1] if len(endpoint_aliases) > 1 else None
+ ),
"_shared_container_ready": False,
"_shared_container_epoch": container_epoch,
})
@@ -2113,10 +2121,16 @@ def _restart_cluster_shared_container(cluster_id, cluster):
readiness_host = "127.0.0.1"
readiness_port = host_port
if ms_network:
+ endpoint_aliases = _cluster_endpoint_aliases(cluster)
networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
container_ip = networks.get(ms_network, {}).get("IPAddress", "")
if container_ip:
- endpoint_host = container_ip
+ # Report the alias, not the address behind it — same rule as first
+ # launch. StopDBCluster/StartDBCluster must not rewrite a stored
+ # DNS name into a raw address: the name keeps resolving to the
+ # restarted container, while the address may not survive.
+ endpoint_host = (endpoint_aliases[0] if endpoint_aliases
+ else container_ip)
endpoint_port = container_port
internal_host = container_ip
internal_port = container_port
@@ -4223,7 +4237,22 @@ def _sync_cluster_endpoints(cluster):
# so the address is published as before.
if (isinstance(writer_address, str) and ".cluster-" in writer_address
and not _pg_cluster_replication_enabled(cluster)):
- reader_address = writer_address.replace(".cluster-", ".cluster-ro-", 1)
+ # Derive the ro- name only when it was registered as an alias on
+ # the backing container (recorded at launch). A cluster launched
+ # with PG replication on carries the writer name alone, so after
+ # a demotion nothing resolves the derived reader name — publish
+ # the address behind the writer instead. Clusters persisted
+ # before the field existed keep the derived-name behavior.
+ if "_shared_reader_alias" in cluster:
+ reader_address = (
+ cluster.get("_shared_reader_alias")
+ or cluster.get("_shared_internal_address")
+ or endpoint.get("Address", cluster.get("ReaderEndpoint", ""))
+ )
+ else:
+ reader_address = writer_address.replace(
+ ".cluster-", ".cluster-ro-", 1,
+ )
else:
reader_address = (
cluster.get("_shared_internal_address")
@@ -5594,6 +5623,7 @@ def _create_db_cluster_impl(p):
"Capacity": 0,
"ClusterScalabilityType": "standard",
"_shared_container_id": None,
+ "_shared_reader_alias": None,
"_shared_host_port": None,
"_shared_endpoint": None,
"_shared_volume_name": None,
diff --git a/tests/test_rds.py b/tests/test_rds.py
index fcb9d316..43cdea83 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -2665,6 +2665,147 @@ def test_rds_stop_start_cluster_compute_lifecycle(monkeypatch):
m._clusters.clear()
+def test_rds_stop_start_cluster_keeps_dns_endpoint(monkeypatch):
+ """Stop/start must not rewrite the cluster's DNS endpoint to a raw IP.
+
+ The shared container carries the cluster endpoint as a Docker network
+ alias, so the DNS name advertised at create time keeps resolving after
+ a StopDBCluster/StartDBCluster cycle. StartDBCluster must keep
+ reporting that name while refreshing the internal address that the
+ readiness probe actually dials.
+ """
+ from ministack.services import rds as m
+
+ container_ip = "172.31.77.42"
+ restarted_ip = "172.31.77.43"
+ network_name = "regression-net"
+
+ class FakeContainer:
+ id = "dns-endpoint-shared-container"
+ attrs = {
+ "NetworkSettings": {
+ "Networks": {
+ network_name: {"IPAddress": container_ip},
+ },
+ },
+ }
+
+ def __init__(self):
+ self.status = "running"
+
+ def reload(self):
+ pass
+
+ def start(self):
+ self.status = "running"
+
+ def stop(self, timeout=5):
+ self.status = "exited"
+ # A real restart lands on a fresh DHCP lease; simulate the
+ # address change so the test proves the internal wiring is
+ # refreshed rather than accidentally reusing the old value.
+ self.attrs["NetworkSettings"]["Networks"][network_name][
+ "IPAddress"
+ ] = restarted_ip
+
+ container = FakeContainer()
+
+ class FakeContainers:
+ def run(self, **_kwargs):
+ container.status = "running"
+ return container
+
+ def get(self, identifier):
+ if identifier in (
+ container.id,
+ m._rds_cluster_docker_name("dns-endpoint-cluster"),
+ ):
+ return container
+ raise Exception("not found")
+
+ class FakeDocker:
+ def __init__(self):
+ self.containers = FakeContainers()
+
+ readiness_dials = []
+
+ def _fake_wait_ready(host, port, *_args, **_kwargs):
+ readiness_dials.append((host, port))
+ return True
+
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_get_ministack_network", lambda _client: network_name)
+ monkeypatch.setattr(m, "_next_port", lambda: 16071)
+ monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)
+ monkeypatch.setattr(m, "_wait_for_database_ready", _fake_wait_ready)
+ monkeypatch.setattr(
+ m, "_ensure_mysql_compatibility", lambda *_args, **_kwargs: True,
+ )
+ monkeypatch.setattr(
+ m, "_grant_mysql_master_user_privileges", lambda *_args: None,
+ )
+
+ def _wait_for_member_status(db_id, expected, timeout=2):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if m._instances.get(db_id, {}).get("DBInstanceStatus") == expected:
+ return
+ time.sleep(0.01)
+ pytest.fail(
+ f"instance {db_id} never reached {expected}; last status: "
+ f"{m._instances.get(db_id, {}).get('DBInstanceStatus')}",
+ )
+
+ m._instances.clear()
+ m._clusters.clear()
+ try:
+ m._create_db_cluster({
+ "DBClusterIdentifier": "dns-endpoint-cluster",
+ "Engine": "aurora-mysql",
+ "MasterUsername": "admin",
+ "MasterUserPassword": "password123",
+ })
+ m._create_db_instance({
+ "DBInstanceIdentifier": "dns-endpoint-writer",
+ "DBClusterIdentifier": "dns-endpoint-cluster",
+ "DBInstanceClass": "db.r6g.large",
+ "Engine": "aurora-mysql",
+ })
+ _wait_for_member_status("dns-endpoint-writer", "available")
+ cluster = m._clusters.get("dns-endpoint-cluster")
+ assert cluster["Status"] == "available"
+
+ # Creation must publish the DNS name, not the container IP.
+ create_address = cluster["_shared_endpoint"]["Address"]
+ assert create_address.endswith(".rds.amazonaws.com")
+ assert create_address != container_ip
+
+ m._stop_db_cluster({"DBClusterIdentifier": "dns-endpoint-cluster"})
+ m._start_db_cluster({"DBClusterIdentifier": "dns-endpoint-cluster"})
+ _wait_for_member_status("dns-endpoint-writer", "available")
+ deadline = time.time() + 2
+ while time.time() < deadline and cluster["Status"] != "available":
+ time.sleep(0.01)
+ assert cluster["Status"] == "available"
+
+ # The public endpoint survives the restart unchanged.
+ assert cluster["_shared_endpoint"]["Address"] == create_address
+ assert cluster["Endpoint"] == create_address
+ # Internal wiring is refreshed to the restarted container's NEW
+ # address (the fake moves the IP in stop()), not the stale one.
+ assert cluster["_shared_internal_address"] == restarted_ip
+ # The readiness probe dials the new address directly, on the
+ # container port — never the public name or the old IP.
+ assert (restarted_ip, cluster["_shared_internal_port"]) in readiness_dials
+
+ member = m._instances.get("dns-endpoint-writer")
+ assert member["Endpoint"]["Address"] == create_address
+ assert member["_internal_address"] == restarted_ip
+ finally:
+ m._instances.clear()
+ m._clusters.clear()
+
+
def test_rds_restore_keeps_stopped_cluster_compute_stopped(monkeypatch):
"""Warm boot must not revive compute for a cluster stopped via the API."""
from ministack.services import rds as m
@@ -13353,7 +13494,10 @@ def test_rds_pg_replicating_reader_lifecycle(monkeypatch):
assert cluster["_shared_container_id"] not in removed
assert _poll_until(lambda: cluster["Status"] == "available")
assert cluster["ReaderEndpoint"] == "10.0.0.7"
- assert cluster["Endpoint"] == "10.0.0.5"
+ # The restarted shared container keeps the DNS alias it launched
+ # with; the raw container address stays internal.
+ assert cluster["Endpoint"] == cluster["_shared_endpoint"]["Address"]
+ assert cluster["Endpoint"].endswith(".rds.amazonaws.com")
# Deleting the reader removes only its own compute; the
# ReaderEndpoint falls back to the writer. The fake derives
@@ -14518,7 +14662,10 @@ def test_rds_pg_two_readers_survive_stop_start(monkeypatch):
assert _poll_until(lambda: cluster["Status"] == "available")
# Member order (reader1 first) still decides the ReaderEndpoint.
assert cluster["ReaderEndpoint"] == "10.0.0.7"
- assert cluster["Endpoint"] == "10.0.0.5"
+ # The restarted shared container keeps the DNS alias it launched
+ # with; the raw container address stays internal.
+ assert cluster["Endpoint"] == cluster["_shared_endpoint"]["Address"]
+ assert cluster["Endpoint"].endswith(".rds.amazonaws.com")
# The two racing revival workers did not re-provision the writer:
# replication access was provisioned exactly once, at creation.
shared_execs = [