Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(iot): name the DescribeEndpoint hosts in the gateway certificate (#2036)
iot-rocket434330e71599
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8db6fe48..4e6ccf26 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **IoT — `https://<endpointAddress>` verifies under `USE_SSL=1`** — `DescribeEndpoint` hands out `<prefix>-ats.iot.<region>.<MINISTACK_HOST>` and `<prefix>.credentials.iot.<region>.<MINISTACK_HOST>`, which SDKs dial over HTTPS as on AWS, but the generated gateway certificate did not name them, so the handshake failed hostname verification. The certificate now carries `*.iot.<region>.<MINISTACK_HOST>` and `*.credentials.iot.<region>.<MINISTACK_HOST>` for every region, and a cached certificate without them is regenerated. Contributed by @iot-rocket.### Added- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 62b3c63c..ac7d717d 100644--- a/README.md+++ b/README.md@@ -948,6 +948,8 @@ Then point the issuer host at MiniStack in `/etc/hosts` (`127.0.0.1 cognito-idp.The generated certificate covers every region's issuer host. Lambda containers MiniStack starts get the hosts entries and the trust settings automatically. Remove the `/etc/hosts` line before calling the real Cognito.+The same certificate names the IoT `DescribeEndpoint` hosts, so an SDK can dial `https://<endpointAddress>`.+### Startup ScriptsMiniStack supports two types of init scripts, with LocalStack-compatible paths:diff --git a/ministack/core/tls.py b/ministack/core/tls.pyindex 6a8a43e2..51e9d5cf 100644--- a/ministack/core/tls.py+++ b/ministack/core/tls.py@@ -44,6 +44,29 @@ def cognito_idp_hosts() -> "list[str]":return list(dict.fromkeys(hosts))+def iot_endpoint_hosts() -> "list[str]":+ """Every region's IoT DescribeEndpoint hosts, which SDKs dial as https://<address>."""+ import ipaddress++ from ministack.services.account import _REGIONS_LIST++ host = os.environ.get("MINISTACK_HOST", "localhost").strip().lower()+ try:+ ipaddress.ip_address(host)+ return [] # An address under an IP literal is not a DNS name a cert can carry.+ except ValueError:+ pass+ if not host or ":" in host:+ return []+ regions = [os.environ.get("MINISTACK_REGION", "us-east-1")] + _REGIONS_LIST+ hosts = [name for r in regions for name in (f"*.iot.{r}.{host}", f"*.credentials.iot.{r}.{host}")]+ return list(dict.fromkeys(hosts))+++def _generated_cert_names() -> "list[str]":+ return cognito_idp_hosts() + iot_endpoint_hosts()++def ca_bundle_path(cert_path: str) -> "str | None":"""System roots plus `cert_path` (the *_CA_BUNDLE vars replace the store), or None."""import ssl@@ -147,8 +170,8 @@ def resolve_tls_material() -> "tuple[str, str]":cert_path = os.path.join(tls_dir, "server.crt")key_path = os.path.join(tls_dir, "server.key")if (os.path.exists(cert_path) and os.path.exists(key_path)- and not _cert_names(cert_path, cognito_idp_hosts())):- # Cached by an older build: regenerate so every issuer host is covered.+ and not _cert_names(cert_path, _generated_cert_names())):+ # Cached by an older build or another MINISTACK_HOST: regenerate so every name is covered.os.remove(cert_path)os.remove(key_path)if not (os.path.exists(cert_path) and os.path.exists(key_path)):@@ -159,7 +182,7 @@ def resolve_tls_material() -> "tuple[str, str]":"-subj", "/CN=ministack-local/O=MiniStack","-addext","subjectAltName=DNS:localhost,DNS:ministack,"- + "".join(f"DNS:{host}," for host in cognito_idp_hosts())+ + "".join(f"DNS:{host}," for host in _generated_cert_names())+ "IP:127.0.0.1,IP:0:0:0:0:0:0:0:1",], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)os.chmod(cert_path, 0o600)diff --git a/tests/test_tls.py b/tests/test_tls.pyindex e0738c7e..cf2a71d7 100644--- a/tests/test_tls.py+++ b/tests/test_tls.py@@ -205,6 +205,81 @@ def test_cached_cert_is_reused_across_regions(tmp_path, monkeypatch):assert open(second, "rb").read() == first_bytes+# ---------------------------------------------------------------------------+# The IoT endpoint hosts: DescribeEndpoint answers a bare address that SDKs+# dial as https://<address>, as on AWS, so the gateway certificate has to+# name it for that handshake to verify.+# ---------------------------------------------------------------------------+++def _checkhost(cert_path, host):+ out = subprocess.run(+ ["openssl", "x509", "-in", cert_path, "-noout", "-checkhost", host],+ capture_output=True, text=True, check=False)+ return "does match" in out.stdout+++def test_generated_cert_names_the_iot_endpoint_hosts(tmp_path, monkeypatch):+ from ministack.core import tls++ monkeypatch.setenv("TMPDIR", str(tmp_path))+ monkeypatch.setenv("MINISTACK_HOST", "localhost.localstack.cloud")+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)+ cert_path, _key = tls.resolve_tls_material()+ assert _checkhost(cert_path, "f7b11509f4d675-ats.iot.eu-central-1.localhost.localstack.cloud")+ assert _checkhost(cert_path, "f7b11509f4d675.credentials.iot.ap-southeast-2.localhost.localstack.cloud")+ assert not _checkhost(cert_path, "f7b11509f4d675-ats.iot.eu-central-1.example.com")+++def test_cached_cert_for_another_ministack_host_is_regenerated(tmp_path, monkeypatch):+ from ministack.core import tls++ monkeypatch.setenv("TMPDIR", str(tmp_path))+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)+ monkeypatch.setenv("MINISTACK_HOST", "first.test")+ tls.resolve_tls_material()+ monkeypatch.setenv("MINISTACK_HOST", "second.test")+ cert, _ = tls.resolve_tls_material()+ assert _checkhost(cert, "abc-ats.iot.us-east-1.second.test")+ assert "DNS:cognito-idp.us-east-1.amazonaws.com" in _san_of(cert)+++def test_ip_ministack_host_adds_no_iot_names(monkeypatch):+ from ministack.core import tls++ monkeypatch.setenv("MINISTACK_HOST", "192.0.2.10")+ assert tls.iot_endpoint_hosts() == []+++def test_iot_data_client_reaches_the_described_endpoint_over_https(tmp_path, monkeypatch):+ """The AWS SDK pattern: endpoint_url=f"https://{endpointAddress}", verified."""+ import boto3++ port = _free_port()+ proc = _spawn({"USE_SSL": "1", "TMPDIR": str(tmp_path), "MINISTACK_HOST": "localhost",+ "GATEWAY_PORT": str(port), "MINISTACK_SSL_CERT": "", "MINISTACK_SSL_KEY": ""}, port)+ try:+ _wait_health(f"https://127.0.0.1:{port}/_ministack/health", ctx=_ctx_no_verify())+ cert = str(tmp_path / "ministack-tls" / "server.crt")+ kw = {"region_name": "eu-central-1", "aws_access_key_id": "test",+ "aws_secret_access_key": "test", "verify": cert}+ address = boto3.client("iot", endpoint_url=f"https://localhost:{port}", **kw).describe_endpoint(+ endpointType="iot:Data-ATS")["endpointAddress"]+ host = address.rsplit(":", 1)[0]+ assert host.endswith("-ats.iot.eu-central-1.localhost")+ # *.localhost resolution varies by platform; the certificate check is what is under test.+ real_getaddrinfo = socket.getaddrinfo+ monkeypatch.setattr(socket, "getaddrinfo",+ lambda h, *a, **k: real_getaddrinfo("127.0.0.1" if h == host else h, *a, **k))+ data = boto3.client("iot-data", endpoint_url=f"https://{address}", **kw)+ assert data.publish(topic="ats/check", payload=b"{}")["ResponseMetadata"]["HTTPStatusCode"] == 200+ finally:+ _terminate(proc)++def test_byo_certificate_is_never_regenerated(tmp_path, monkeypatch):"""MINISTACK_SSL_CERT is the operator's, so the issuer host is theirbusiness and we must hand it back untouched."""