Skip to content

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

fix(lambda): keep TLS to the gateway in the local Node executor (#2341)

iot-rocket85803190e7d9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24c6d145..3d7aa268 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 HTTPS to a TLS gateway in the local executor** — with `USE_SSL=1` a Node function's `https` requests to the gateway went out as plain HTTP to its TLS port and the built-in SDK v3 clients always spoke HTTP, so custom resource callbacks and SDK calls failed with `socket hang up`; they now keep TLS on the gateway port, and `https.request` or `https.get` with a URL plus options no longer throws `ERR_INVALID_ARG_TYPE`. Contributed by @iot-rocket.
- **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.
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 7b2946f0..5eee9ddf 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -388,7 +388,7 @@ fs.write = function(fd, ...args) {
headers["__DEPTH_HEADER__"] = process.env.__DEPTH_ENV__;
}
return new Promise((resolve, reject) => {
- const req = http.request(
+ const req = (ep.protocol === "https:" ? https : http).request(
{
hostname: ep.hostname,
port: parseInt(ep.port || "4566", 10),
@@ -531,7 +531,7 @@ fs.write = function(fd, ...args) {
headers["Content-Type"] = "application/json";
headers["Content-Length"] = Buffer.byteLength(encodedBody);
}
- const req = http.request(
+ const req = (ep.protocol === "https:" ? https : http).request(
{
hostname: ep.hostname,
port: parseInt(ep.port || "4566", 10),
@@ -661,7 +661,7 @@ fs.write = function(fd, ...args) {
const ep = new URL(process.env.AWS_ENDPOINT_URL || "http://127.0.0.1:4566");
const body = JSON.stringify(params || {});
return new Promise((resolve, reject) => {
- const req = http.request(
+ const req = (ep.protocol === "https:" ? https : http).request(
{
hostname: ep.hostname,
port: parseInt(ep.port || "4566", 10),
@@ -819,20 +819,31 @@ function patchAwsSdk() {
};
} catch (_) {}
- // Patch https.request for bundled SDK
+ // Patch https.request for bundled SDK. Under USE_SSL the gateway serves only
+ // HTTPS, so requests to it keep TLS and only their port is rewritten.
+ const msTls = parsed.protocol === "https:";
const origHttpsReq = https.request;
- https.request = function(options, callback) {
- if (typeof options === "string") options = url.parse(options);
- else if (options instanceof url.URL) options = url.parse(options.toString());
- else options = Object.assign({}, options);
+ https.request = function(input, options, callback) {
+ // Node takes (url[, options][, callback]) and (options[, callback]).
+ const original = Array.prototype.slice.call(arguments);
+ if (typeof options === "function") { callback = options; options = undefined; }
+ if (typeof input === "string") input = url.parse(input);
+ else if (input instanceof url.URL) input = url.parse(input.toString());
+ options = Object.assign({}, input, options);
const host = options.hostname || options.host || "";
if (host.endsWith(".amazonaws.com") || host.endsWith(".amazonaws.com.cn")) {
- options.protocol = "http:";
options.hostname = msHost;
options.host = msHost + ":" + msPort;
options.port = msPort;
options.path = options.path || "/";
+ if (msTls) {
+ // Verify the gateway's name, not the AWS host the Host header carries.
+ options.protocol = "https:";
+ options.servername = require("net").isIP(msHost) ? "" : msHost;
+ return origHttpsReq.call(https, options, callback);
+ }
+ options.protocol = "http:";
if (options.agent instanceof https.Agent) {
options.agent = new http.Agent({ keepAlive: true });
} else if (options.agent === undefined) {
@@ -845,13 +856,18 @@ function patchAwsSdk() {
// Downgrade HTTPS to HTTP for localhost — CDK Provider Framework's
// cfn-response.js calls https.request unconditionally for the ResponseURL
// PUT, and also drops the port when constructing options. Intercept here
- // so the PUT reaches Ministack's HTTP server on msPort, not port 443.
+ // so the PUT reaches Ministack on msPort, not port 443 (over TLS under USE_SSL).
const advertised = (process.env.MINISTACK_HOST || "").split(":")[0];
if (host === "127.0.0.1" || host === "localhost" || host === msHost
|| (advertised && host === advertised)) {
- options.protocol = "http:";
// The https default port means the gateway port here, as in the container shim.
options.port = options.port && String(options.port) !== "443" ? options.port : msPort;
+ if (msTls) {
+ options.protocol = "https:";
+ options.hostname = host;
+ return origHttpsReq.call(https, options, callback);
+ }
+ options.protocol = "http:";
options.host = host + ":" + options.port;
options.agent = new http.Agent({ keepAlive: true });
delete options._defaultAgent;
@@ -872,10 +888,10 @@ function patchAwsSdk() {
return http.request(options, callback);
}
- return origHttpsReq.call(https, options, callback);
+ return origHttpsReq.apply(https, original);
};
- https.get = function(options, callback) {
- var req = https.request(options, callback);
+ https.get = function() {
+ var req = https.request.apply(https, arguments);
req.end();
return req;
};
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 872bc5f4..bf0498c1 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -8720,6 +8720,89 @@ exports.handler = (event, ctx, cb) => {{
assert received.get("body") == "test"
[email protected]("use_ssl", [False, True], ids=["plain", "use_ssl"])
+def test_nodejs_worker_https_call_forms_reach_the_gateway(tmp_path, use_ssl):
+ """Every https.request/https.get form and the SDK stubs reach the gateway, over TLS when its endpoint is https."""
+ import ssl
+ import subprocess
+ from http.server import ThreadingHTTPServer
+
+ seen = []
+
+ class _Handler(BaseHTTPRequestHandler):
+ def _answer(self):
+ self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ seen.append((self.command, self.path, self.headers.get("X-Amz-Target")))
+ body = b"{}"
+ self.send_response(200)
+ self.send_header("Content-Type", "application/x-amz-json-1.1")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ do_GET = do_PUT = do_POST = _answer
+
+ def log_message(self, *args):
+ pass
+
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ port = srv.server_address[1]
+ env = {"AWS_ENDPOINT_URL": f"http://127.0.0.1:{port}"}
+ if use_ssl:
+ 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))
+ # A TLS-only listener, like the gateway under USE_SSL: a plain request fails the handshake.
+ srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
+ env = {"AWS_ENDPOINT_URL": f"https://127.0.0.1:{port}", "NODE_EXTRA_CA_CERTS": str(cert)}
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+
+ handler_js = f"""\
+const https = require("https");
+const {{ SSMClient, DescribeParametersCommand }} = require("@aws-sdk/client-ssm");
+const base = "https://127.0.0.1:{port}";
+const call = (start) => new Promise((resolve) => {{
+ let req;
+ try {{
+ req = start((res) => {{ res.resume(); res.on("end", () => resolve(res.statusCode)); }});
+ }} catch (e) {{
+ return resolve(e.code || String(e));
+ }}
+ req.on("error", (e) => resolve(e.code || e.message));
+ if (!req.writableEnded) req.end();
+}});
+exports.handler = async () => ({{
+ urlOptions: await call((cb) => https.request(base + "/url-options", {{ method: "PUT" }}, cb)),
+ urlObject: await call((cb) => https.request(new URL(base + "/url-object"), cb)),
+ noPort: await call((cb) => https.request({{ hostname: "127.0.0.1", path: "/no-port", method: "PUT" }}, cb)),
+ port443: await call((cb) => https.request({{ hostname: "127.0.0.1", port: 443, path: "/port-443",
+ method: "PUT" }}, cb)),
+ getUrlOptions: await call((cb) => https.get(base + "/get", {{ headers: {{ "x-probe": "1" }} }}, cb)),
+ awsHost: await call((cb) => https.request({{ hostname: "ssm.us-east-1.amazonaws.com", path: "/aws-host",
+ method: "POST", headers: {{ host: "ssm.us-east-1.amazonaws.com" }} }}, cb)),
+ sdkStub: await new SSMClient({{}}).send(new DescribeParametersCommand({{}}))
+ .then(() => 200, (e) => e.code || String(e)),
+}});
+"""
+ try:
+ result = _run_nodejs_worker(handler_js, env_extra=env)
+ finally:
+ srv.shutdown()
+ srv.server_close()
+
+ assert result.get("status") == "ok", f"Handler failed: {result}"
+ assert set(result["result"].values()) == {200}, result["result"]
+ assert sorted(seen) == sorted([
+ ("PUT", "/url-options", None), ("GET", "/url-object", None), ("PUT", "/no-port", None),
+ ("PUT", "/port-443", None), ("GET", "/get", None), ("POST", "/aws-host", None),
+ ("POST", "/", "AmazonSSM.DescribeParameters"),
+ ])
+
+
def test_nodejs_worker_aws_sdk_v3_stub_wire_roundtrip(lam, ssm):
"""End-to-end: a Node.js Lambda using @aws-sdk/client-ssm's
PutParameterCommand actually creates a parameter on MiniStack's SSM