Skip to content

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

fix(lambda): send Node https callbacks to the TLS gateway in docker (#2340)

iot-rocket040a4349a606
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 180945f0..24c6d145 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **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
+- **Lambda — Node.js custom resource callbacks in the Docker executor under `USE_SSL`** — the Node shim kept the port of an https request to the gateway when `USE_SSL=1`, so a `cfn-response` or CDK style `ResponseURL` PUT (no port, or 443) went to port 443 and the stack waited out `ServiceTimeout`; it now goes to the gateway port over TLS, and other explicit ports are kept. Contributed by @iot-rocket.
- **TLS — the generated certificate names `host.docker.internal`** — with `USE_SSL=1` and the Docker Lambda executor, functions reach the gateway as `https://host.docker.internal:<port>`, a name the generated certificate lacked, so every SDK call and callback from a container failed hostname verification; the certificate now carries it, and a cached one without it is regenerated. Contributed by @iot-rocket.
- **SQS — FIFO dedup hit returns the current request's MD5s** — a `SendMessage` (or `SendMessageBatch` entry) whose `MessageDeduplicationId` was already in the 5-minute window answered with the first message's `MD5OfMessageBody` and `MD5OfMessageAttributes`; AWS keeps the first message but reports the digests of the request just sent, and SDKs that verify them (.NET, Java) threw `MD5 hash mismatch` on every replay whose body or attributes differed. The response now carries the current request's digests; `MessageId` and `SequenceNumber` are still the first message's. Contributed by @vanessah07.
- **S3 — `EU` location constraint** — since 1.5.28, `CreateBucket` from an eu-west-1 endpoint refused the legacy `EU` constraint with `IllegalLocationConstraintException`, and a bucket created with it elsewhere was homed in a region called `EU`. As on AWS, eu-west-1 now accepts `EU` and homes the bucket in eu-west-1, `GetBucketLocation` answers `EU` for it, and other regional endpoints still refuse it. The AWS SDK for .NET sends `EU` for eu-west-1 by default.
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index c28cb419..1c202ad7 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -4322,7 +4322,7 @@ def handler(event, context):
_JS_CTX_ARN_SHIM = '''\
// MiniStack shim: hand user code the control-plane ARN in its context, and
-// reach the gateway over plain HTTP (without USE_SSL) when a library insists on HTTPS.
+// reach the gateway port when a library insists on HTTPS (over plain HTTP without USE_SSL).
const path = require("path");
const fs = require("fs");
const http = require("http");
@@ -4372,8 +4372,15 @@ try {
if (!PLAIN_HOSTS.has(host) || (rawPort && rawPort !== "443" && rawPort !== EP_PORT)) {
return origHttpsRequest.apply(https, original);
}
- // USE_SSL: the gateway serves only HTTPS, so a request to it keeps TLS.
- if (EP.protocol === "https:") return origHttpsRequest.apply(https, original);
+ // USE_SSL: the gateway serves only HTTPS, so a request to it keeps TLS and
+ // only the https default port becomes the gateway port.
+ if (EP.protocol === "https:") {
+ if (rawPort && rawPort !== "443") return origHttpsRequest.apply(https, original);
+ opts.protocol = "https:";
+ opts.hostname = host;
+ opts.port = EP_PORT;
+ return origHttpsRequest.call(https, opts, callback);
+ }
opts.protocol = "http:";
opts.hostname = host;
opts.host = host + ":" + EP_PORT;
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 1d5c52ef..872bc5f4 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -12751,6 +12751,76 @@ def test_node_context_shim_keeps_https_to_a_tls_gateway(tmp_path):
server.server_close()
[email protected](not shutil.which("node"), reason="node not installed")
+def test_node_context_shim_sends_the_https_default_port_to_a_tls_gateway(tmp_path):
+ """Under USE_SSL a CDK or cfn-response style PUT (no port, or 443) reaches the gateway port over TLS."""
+ import http.server
+ import ssl
+ import subprocess
+ import threading
+
+ seen = []
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_PUT(self):
+ seen.append((self.path, self.headers.get("Host")))
+ self.send_response(200)
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+ cert, key = tmp_path / "gw.crt", tmp_path / "gw.key"
+ subprocess.run([
+ "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(cert),
+ "-days", "1", "-subj", "/CN=gateway", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
+ ], check=True, capture_output=True)
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ ctx.load_cert_chain(str(cert), str(key))
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.socket = ctx.wrap_socket(server.socket, server_side=True)
+ port = server.server_address[1]
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ code_dir = tmp_path / "task"
+ code_dir.mkdir()
+ (code_dir / "index.js").write_text(
+ "const https = require('https');\n"
+ "exports.handler = (event) => new Promise((resolve) => {\n"
+ " const opts = {hostname: '127.0.0.1', path: '/_ministack/cfn-response/tok', method: 'PUT'};\n"
+ " if (event.port) opts.port = event.port;\n"
+ " const req = event.url ? https.request(event.url, {method: 'PUT'}) : https.request(opts);\n"
+ " req.on('response', (res) => resolve({status: res.statusCode}));\n"
+ " req.on('error', (e) => resolve({error: e.code || String(e)}));\n"
+ " req.end('{}');\n"
+ "});\n"
+ )
+ assert lsvc._write_context_arn_shim(str(code_dir), "nodejs20.x", "index.handler") == "_msctx_shim.handler"
+ env = {**os.environ, "LAMBDA_TASK_ROOT": str(code_dir), "_MS_REAL_HANDLER": "index.handler",
+ "AWS_ENDPOINT_URL": f"https://127.0.0.1:{port}", "NODE_EXTRA_CA_CERTS": str(cert)}
+ script = ("require(process.argv[1]).handler(JSON.parse(process.argv[2]), {})"
+ ".then((r) => process.stdout.write(JSON.stringify(r)));")
+
+ def run(event):
+ proc = subprocess.run(["node", "-e", script, str(code_dir / "_msctx_shim.js"), json.dumps(event)],
+ env=env, capture_output=True, text=True, timeout=30)
+ assert proc.returncode == 0, proc.stderr
+ return json.loads(proc.stdout)
+
+ # The CDK shape (no port), the cfn-response shape (443) and a URL without a port.
+ assert run({}) == {"status": 200}
+ assert run({"port": 443}) == {"status": 200}
+ assert run({"url": "https://127.0.0.1/_ministack/cfn-response/tok"}) == {"status": 200}
+ assert [path for path, _host in seen] == ["/_ministack/cfn-response/tok"] * 3
+ assert all(host == f"127.0.0.1:{port}" for _path, host in seen)
+ # Any other explicit port is left alone.
+ assert "error" in run({"port": port + 1})
+ assert len(seen) == 3
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
def test_extract_cache_sweep_is_reference_based(monkeypatch, tmp_path):
"""The sweep drops extracted trees whose blob no longer backs any
function, version, or layer version — and only those. References are read