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
feat(lambda): inject @aws-sdk/client-* stubs into Node.js worker for CDK Provider Framework compatibility (#604)
Michael Smith8b4688e40080
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 0b434791..34332feb 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -103,6 +103,7 @@ const path = require("path");const http = require("http");const https = require("https");const url = require("url");+const Module = require("module");// Redirect stdout to stderr so stdout stays clean for JSON-line protocolconst _realStdoutWrite = process.stdout.write.bind(process.stdout);@@ -111,6 +112,222 @@ process.stdout.write = function(chunk, encoding, callback) {return _stderrWrite(chunk, encoding, callback);};+// Synthetic AWS SDK v3 stubs — real AWS Lambda (Node.js 18+) ships these+// built-in, but the host runtime does not. Try the real package first so+// a Lambda Layer with the actual SDK takes precedence; fall back to a stub+// that routes through AWS_ENDPOINT_URL (Ministack).+(function _installAwsSdkV3Stubs() {+ // ── Lambda stub (REST-based, not JSON-RPC) ─────────────────────────────+ function _lambdaInvoke(params) {+ const ep = new URL(process.env.AWS_ENDPOINT_URL || "http://127.0.0.1:4566");+ const fn = encodeURIComponent(params.FunctionName || "");+ const qs = params.Qualifier+ ? "?Qualifier=" + encodeURIComponent(params.Qualifier)+ : "";+ const body = params.Payload instanceof Uint8Array+ ? Buffer.from(params.Payload)+ : (params.Payload || "");+ return new Promise((resolve, reject) => {+ const req = http.request(+ {+ hostname: ep.hostname,+ port: parseInt(ep.port || "4566", 10),+ method: "POST",+ path: "/2015-03-31/functions/" + fn + "/invocations" + qs,+ headers: { "Content-Type": "application/json" },+ },+ (res) => {+ const chunks = [];+ res.on("data", (c) => chunks.push(c));+ res.on("end", () =>+ resolve({+ StatusCode: res.statusCode,+ Payload: Buffer.concat(chunks),+ FunctionError: res.headers["x-amz-function-error"],+ })+ );+ }+ );+ req.on("error", reject);+ if (body) req.write(body);+ req.end();+ });+ }++ function _makeLambdaClientModule() {+ class Lambda {+ constructor(_cfg) {}+ invoke(params) { return _lambdaInvoke(params); }+ }+ class LambdaClient {+ constructor(_cfg) {}+ send(cmd) { return cmd._run(); }+ }+ class InvokeCommand {+ constructor(params) { this._p = params; }+ _run() { return _lambdaInvoke(this._p); }+ }+ async function waitUntilFunctionActiveV2() { return { state: "SUCCESS" }; }+ return { Lambda, LambdaClient, InvokeCommand, waitUntilFunctionActiveV2 };+ }++ // ── Generic JSON-RPC stub (covers SSM, SFN, STS, CloudWatch, Logs, etc.) ─+ // Most AWS SDK v3 packages use awsJson1.x: POST / with X-Amz-Target header.+ // Ministack's router maps target prefixes to service modules.+ const _JSON_RPC_TARGETS = {+ // JSON-RPC (awsJson1.x) services — keyed by @aws-sdk/client-{key} suffix.+ // Target prefixes match Ministack's router.py SERVICE_PATTERNS target_prefixes.+ "ssm": "AmazonSSM",+ "sfn": "AWSStepFunctions",+ // sts, sns: query protocol — @aws-sdk/client-{sts,sns} sends Action= form-encoded POST+ // cloudwatch: smithy-rpc-v2-cbor — @aws-sdk/client-cloudwatch sends path-based requests+ // All three are handled by Ministack's native query/path routing when the real SDK is present+ "cloudwatch-logs": "Logs_20140328",+ "logs": "Logs_20140328",+ "secretsmanager": "secretsmanager",+ "events": "AmazonEventBridge",+ "eventbridge": "AmazonEventBridge",+ "kinesis": "Kinesis_20131202",+ "ecs": "AmazonEC2ContainerServiceV20141113",+ "dynamodb": "DynamoDB_20120810",+ "dynamodb-streams": "DynamoDBStreams_20120810",+ "sqs": "AmazonSQS",+ "glue": "AWSGlue",+ "athena": "AmazonAthena",+ "firehose": "Firehose_20150804",+ "cognito-identity-provider": "AWSCognitoIdentityProviderService",+ "cognito-identity": "AWSCognitoIdentityService",+ "emr": "ElasticMapReduce",+ "ecr": "AmazonEC2ContainerRegistry_V20150921",+ "acm": "CertificateManager",+ "wafv2": "AWSWAF_20190729",+ "waf": "AWSWAF_20150824",+ "waf-regional": "AWSWAF_Regional_20161128",+ "organizations": "AWSOrganizationsV20161128",+ "kms": "TrentService",+ "codebuild": "CodeBuild_20161006",+ "transfer": "TransferService",+ "servicediscovery": "Route53AutoNaming_v20170314",+ "resource-groups-tagging-api": "ResourceGroupsTaggingAPI_20170126",+ "cloudtrail": "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101",+ };++ function _jsonRpcRequest(targetPrefix, opName, params) {+ 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(+ {+ hostname: ep.hostname,+ port: parseInt(ep.port || "4566", 10),+ method: "POST",+ path: "/",+ headers: {+ "Content-Type": "application/x-amz-json-1.1",+ "X-Amz-Target": targetPrefix + "." + opName,+ "Content-Length": Buffer.byteLength(body),+ },+ },+ (res) => {+ const chunks = [];+ res.on("data", (c) => chunks.push(c));+ res.on("end", () => {+ const text = Buffer.concat(chunks).toString();+ let parsed;+ try { parsed = JSON.parse(text); } catch (_) { parsed = {}; }+ if (res.statusCode >= 400) {+ const err = new Error(+ parsed.Message || parsed.message || text || "Service error"+ );+ err.statusCode = res.statusCode;+ err.code = parsed.__type || parsed.Code || "ServiceError";+ err.name = err.code;+ reject(err);+ } else {+ resolve(parsed);+ }+ });+ }+ );+ req.on("error", reject);+ req.write(body);+ req.end();+ });+ }++ function _makeGenericJsonServiceModule(targetPrefix) {+ // Command class factory: new PutParameterCommand(params) → has _run()+ function _cmdClass(opName) {+ return class {+ constructor(params) { this._params = params; }+ _run() { return _jsonRpcRequest(targetPrefix, opName, this._params); }+ };+ }++ // v3-style client: new SSMClient({}).send(new PutParameterCommand({}))+ class GenericClient {+ constructor(_cfg) {}+ send(cmd) { return cmd._run(); }+ }++ // Bare client: new SSM({}).putParameter(params) (any method → operation)+ const BareClient = new Proxy(function() {}, {+ construct(_target, _args) {+ return new Proxy({}, {+ get(_, prop) {+ if (typeof prop !== "string") return undefined;+ const opName = prop[0].toUpperCase() + prop.slice(1);+ return (params) => _jsonRpcRequest(targetPrefix, opName, params);+ },+ });+ },+ });++ // Module proxy: any named export resolves on demand.+ // *Client → GenericClient (v3 style)+ // *Command → command class (strip "Command" suffix → op name)+ // other uppercase name → BareClient (bare/convenience style)+ return new Proxy(+ {},+ {+ get(_, prop) {+ if (typeof prop !== "string") return undefined;+ if (prop.endsWith("Client")) return GenericClient;+ if (prop.endsWith("Command")) {+ return _cmdClass(prop.slice(0, -7));+ }+ if (/^[A-Z]/.test(prop)) return BareClient;+ return undefined;+ },+ }+ );+ }++ // ── require() intercept ────────────────────────────────────────────────+ const _SPECIFIC_STUBS = {+ "@aws-sdk/client-lambda": _makeLambdaClientModule(),+ };+ const _SDK_CLIENT_RE = /^@aws-sdk\/client-(.+)$/;++ const _origRequire = Module.prototype.require;+ Module.prototype.require = function (id) {+ // 1. Specific stubs (Lambda uses REST, not JSON-RPC)+ const specific = _SPECIFIC_STUBS[id];+ if (specific) {+ try { return _origRequire.apply(this, arguments); } catch (_) {}+ return specific;+ }+ // 2. Generic JSON-RPC stubs for known @aws-sdk/client-* packages+ const m = id.match(_SDK_CLIENT_RE);+ if (m) {+ try { return _origRequire.apply(this, arguments); } catch (_) {}+ const prefix = _JSON_RPC_TARGETS[m[1]];+ if (prefix) return _makeGenericJsonServiceModule(prefix);+ }+ return _origRequire.apply(this, arguments);+ };+}());+function patchAwsSdk() {const endpoint = process.env.AWS_ENDPOINT_URL|| process.env.LOCALSTACK_ENDPOINT@@ -165,6 +382,19 @@ function patchAwsSdk() {return http.request(options, callback);}+ // 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.+ if (host === "127.0.0.1" || host === "localhost" || host === msHost) {+ options.protocol = "http:";+ options.port = options.port || msPort;+ options.host = host + ":" + options.port;+ options.agent = new http.Agent({ keepAlive: true });+ delete options._defaultAgent;+ return http.request(options, callback);+ }+// Downgrade ES HTTPS to HTTP for local Elasticsearchvar esHost = process.env.ES_ENDPOINT ? process.env.ES_ENDPOINT.split(":")[0] : null;if (esHost && (host === esHost || host.startsWith(esHost + ":"))) {@@ -174,11 +404,7 @@ function patchAwsSdk() {options.host = esHost + ":" + esPort;options.port = esPort;options.rejectUnauthorized = false;- if (options.agent instanceof https.Agent) {- options.agent = new http.Agent({ keepAlive: true });- } else if (options.agent === undefined) {- options.agent = new http.Agent({ keepAlive: true });- }+ options.agent = new http.Agent({ keepAlive: true });delete options._defaultAgent;return http.request(options, callback);}diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex ce6d9515..400bb817 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -3364,6 +3364,258 @@ def test_account_from_arn_lambda_runtime_helper_matches():assert runtime_helper("arn:aws:lambda") == "fallback_key"+def _run_nodejs_worker(handler_js, event_payload=None, env_extra=None):+ """Spin up a Node.js Lambda worker with the given handler, return invoke result."""+ import io+ import json+ import os+ import shutil+ import subprocess+ import tempfile+ import zipfile++ from ministack.core.lambda_runtime import _NODEJS_WORKER_SCRIPT++ node = shutil.which("node")+ if not node:+ pytest.skip("node not found on PATH")++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.js", handler_js)+ code_zip = buf.getvalue()++ tmpdir = tempfile.mkdtemp(prefix="test-node-worker-")+ try:+ worker_path = os.path.join(tmpdir, "_worker.js")+ with open(worker_path, "w") as f:+ f.write(_NODEJS_WORKER_SCRIPT)++ code_dir = os.path.join(tmpdir, "code")+ os.makedirs(code_dir)+ zip_path = os.path.join(tmpdir, "code.zip")+ with open(zip_path, "wb") as f:+ f.write(code_zip)+ with zipfile.ZipFile(zip_path) as zf:+ zf.extractall(code_dir)++ env = {**os.environ, "AWS_ENDPOINT_URL": "http://127.0.0.1:4566"}+ if env_extra:+ env.update(env_extra)++ proc = subprocess.Popen(+ [node, worker_path],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ bufsize=1,+ env=env,+ )++ init = json.dumps({+ "code_dir": code_dir,+ "module": "index",+ "handler": "handler",+ "env": {},+ "function_name": "test-worker",+ "memory": 128,+ "arn": "arn:aws:lambda:us-east-1:000000000000:function:test-worker",+ })+ proc.stdin.write(init + "\n")+ proc.stdin.flush()++ init_resp = json.loads(proc.stdout.readline())+ assert init_resp.get("status") == "ready", (+ f"Worker init failed: {init_resp}; stderr: {proc.stderr.read(2048)}"+ )++ event = json.dumps({**(event_payload or {}), "_request_id": "test-req-1"})+ proc.stdin.write(event + "\n")+ proc.stdin.flush()++ invoke_resp = json.loads(proc.stdout.readline())+ proc.terminate()+ return invoke_resp+ finally:+ shutil.rmtree(tmpdir, ignore_errors=True)+++def test_nodejs_worker_aws_sdk_v3_stub_resolves():+ """@aws-sdk/client-lambda, @aws-sdk/client-sfn, @aws-sdk/client-ssm resolve.++ Real AWS Lambda (Node.js 18+) ships these built-in. Ministack injects+ stubs: Lambda uses a dedicated REST stub; sfn/ssm use the generic JSON-RPC+ stub backed by Ministack's own service implementations.+ """+ handler_js = """\+const { Lambda, LambdaClient, InvokeCommand, waitUntilFunctionActiveV2 } = require("@aws-sdk/client-lambda");+const { SFN, SFNClient } = require("@aws-sdk/client-sfn");+const { SSM, SSMClient, PutParameterCommand, GetParameterCommand } = require("@aws-sdk/client-ssm");+exports.handler = async (_event, _ctx) => ({+ hasLambda: typeof Lambda === "function",+ hasLambdaClient: typeof LambdaClient === "function",+ hasInvokeCommand: typeof InvokeCommand === "function",+ hasWaiter: typeof waitUntilFunctionActiveV2 === "function",+ hasSFN: typeof SFN === "function",+ hasSFNClient: typeof SFNClient === "function",+ hasSSM: typeof SSM === "function",+ hasSSMClient: typeof SSMClient === "function",+ hasPutParameterCommand: typeof PutParameterCommand === "function",+ hasGetParameterCommand: typeof GetParameterCommand === "function",+});+"""+ result = _run_nodejs_worker(handler_js)+ assert result.get("status") == "ok", f"Invocation failed: {result}"+ r = result["result"]+ assert r["hasLambda"] is True+ assert r["hasLambdaClient"] is True+ assert r["hasInvokeCommand"] is True+ assert r["hasWaiter"] is True+ assert r["hasSFN"] is True+ assert r["hasSFNClient"] is True+ assert r["hasSSM"] is True+ assert r["hasSSMClient"] is True+ assert r["hasPutParameterCommand"] is True+ assert r["hasGetParameterCommand"] is True+++def test_nodejs_worker_json_rpc_error_has_name():+ """Service errors from the JSON-RPC stub expose err.name (not just err.code).++ AWS SDK v3 handlers typically catch errors by name, e.g.:+ if (e.name !== 'ParameterNotFound') throw e;+ The stub must set both .name and .code so that pattern works.+ """+ handler_js = """\+const http = require("http");+// Spin up a tiny server that returns a ParameterNotFound error body.+const srv = http.createServer((req, res) => {+ res.writeHead(400, { "Content-Type": "application/x-amz-json-1.1" });+ res.end(JSON.stringify({ __type: "ParameterNotFound", Message: "param not found" }));+});+srv.listen(0, "127.0.0.1", () => {+ const port = srv.address().port;+ process.env.AWS_ENDPOINT_URL = "http://127.0.0.1:" + port;+ const { SSMClient, GetParameterCommand } = require("@aws-sdk/client-ssm");+ const client = new SSMClient({});+ client.send(new GetParameterCommand({ Name: "/does/not/exist" }))+ .catch((e) => {+ srv.close();+ exports._result = { name: e.name, code: e.code };+ });+});+exports.handler = () => new Promise((res) => {+ const wait = () => exports._result ? res(exports._result) : setTimeout(wait, 10);+ wait();+});+"""+ result = _run_nodejs_worker(handler_js)+ assert result.get("status") == "ok", f"Invocation failed: {result}"+ r = result["result"]+ assert r["name"] == "ParameterNotFound", f"err.name was {r['name']!r}, expected 'ParameterNotFound'"+ assert r["code"] == "ParameterNotFound", f"err.code was {r['code']!r}"+++def test_nodejs_worker_aws_sdk_v3_stub_resolves_extended():+ """JSON-RPC service stubs resolve for all awsJson1.x services.++ sts, sns, cloudwatch are intentionally excluded: they use query/smithy-rpc-v2-cbor+ protocols, not awsJson1.x, so their real SDK packages format requests correctly+ without a stub.+ """+ handler_js = """\+const { SQSClient, SendMessageCommand } = require("@aws-sdk/client-sqs");+const { KMSClient, EncryptCommand } = require("@aws-sdk/client-kms");+const { CognitoIdentityProviderClient, AdminGetUserCommand } = require("@aws-sdk/client-cognito-identity-provider");+const { CognitoIdentityClient } = require("@aws-sdk/client-cognito-identity");+const { ECRClient, DescribeRepositoriesCommand } = require("@aws-sdk/client-ecr");+const { GlueClient, GetDatabaseCommand } = require("@aws-sdk/client-glue");+const { AthenaClient, StartQueryExecutionCommand } = require("@aws-sdk/client-athena");+const { FirehoseClient, PutRecordCommand } = require("@aws-sdk/client-firehose");+const { ACMClient, ListCertificatesCommand } = require("@aws-sdk/client-acm");+const { OrganizationsClient, ListAccountsCommand } = require("@aws-sdk/client-organizations");+const { CodeBuildClient, ListProjectsCommand } = require("@aws-sdk/client-codebuild");+const { CloudTrailClient, LookupEventsCommand } = require("@aws-sdk/client-cloudtrail");+const { ServiceDiscoveryClient, ListServicesCommand } = require("@aws-sdk/client-servicediscovery");+exports.handler = async () => ({+ sqs: typeof SQSClient === "function" && typeof SendMessageCommand === "function",+ kms: typeof KMSClient === "function" && typeof EncryptCommand === "function",+ cidp: typeof CognitoIdentityProviderClient === "function" && typeof AdminGetUserCommand === "function",+ ci: typeof CognitoIdentityClient === "function",+ ecr: typeof ECRClient === "function" && typeof DescribeRepositoriesCommand === "function",+ glue: typeof GlueClient === "function" && typeof GetDatabaseCommand === "function",+ ath: typeof AthenaClient === "function" && typeof StartQueryExecutionCommand === "function",+ fh: typeof FirehoseClient === "function" && typeof PutRecordCommand === "function",+ acm: typeof ACMClient === "function" && typeof ListCertificatesCommand === "function",+ org: typeof OrganizationsClient === "function" && typeof ListAccountsCommand === "function",+ cb: typeof CodeBuildClient === "function" && typeof ListProjectsCommand === "function",+ ct: typeof CloudTrailClient === "function" && typeof LookupEventsCommand === "function",+ sd: typeof ServiceDiscoveryClient === "function" && typeof ListServicesCommand === "function",+});+"""+ result = _run_nodejs_worker(handler_js)+ assert result.get("status") == "ok", f"Invocation failed: {result}"+ r = result["result"]+ for svc, ok in r.items():+ assert ok is True, f"Stub not resolved for service key: {svc!r}"+++def test_nodejs_worker_https_localhost_downgraded_to_http():+ """https.request to localhost is downgraded to HTTP so cfn-response.js works.++ The CDK Provider Framework's cfn-response.js calls https.request+ unconditionally for the ResponseURL PUT and drops the port from the URL.+ patchAwsSdk() intercepts this and redirects to HTTP on the Ministack port.+ """+ import http.server+ import threading++ # Start a tiny HTTP server to catch the PUT+ received = {}++ class _Handler(http.server.BaseHTTPRequestHandler):+ def do_PUT(self):+ length = int(self.headers.get("Content-Length", 0))+ received["body"] = self.rfile.read(length).decode()+ received["path"] = self.path+ self.send_response(200)+ self.end_headers()++ def log_message(self, *args):+ pass++ srv = http.server.HTTPServer(("127.0.0.1", 0), _Handler)+ port = srv.server_address[1]+ t = threading.Thread(target=srv.handle_request, daemon=True)+ t.start()++ handler_js = f"""\+const https = require("https");+exports.handler = (event, ctx, cb) => {{+ // Simulate cfn-response.js: https.request with no port (port dropped from URL)+ const req = https.request({{+ hostname: "127.0.0.1",+ port: {port},+ path: "/test-cfn-response",+ method: "PUT",+ headers: {{"content-type": "", "content-length": 4}},+ }}, (res) => {{+ res.resume();+ cb(null, {{ statusCode: res.statusCode }});+ }});+ req.on("error", (e) => cb(e.message));+ req.write("test");+ req.end();+}};+"""+ result = _run_nodejs_worker(handler_js)+ t.join(timeout=5)+ srv.server_close()++ assert result.get("status") == "ok", f"Handler failed: {result}"+ assert received.get("path") == "/test-cfn-response", "PUT not received by HTTP server"+ assert received.get("body") == "test"def test_lambda_ruby_4_0_runtime_maps_to_official_image():"""Lambda Ruby 4.0 runtime support (botocore 1.42.94 added the runtime).Maps to AWS's official Lambda Ruby 4.0 base image."""