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
Lets users back languages AWS doesn't ship a runtime for (PHP, Deno, (#600)
Nahuel Nucera1d1a9be35993
diff --git a/README.md b/README.mdindex 27126a6a..c5dd9a75 100644--- a/README.md+++ b/README.md@@ -891,6 +891,53 @@ Layers that ship npm packages work too — MiniStack resolves the `nodejs/node_mMiniStack also sets the standard Lambda runtime environment before the handler module is loaded, including `LAMBDA_TASK_ROOT`, `AWS_LAMBDA_FUNCTION_NAME`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE`, and `_LAMBDA_FUNCTION_ARN`. That keeps import-time Lambda detection and conditional handler setup aligned with AWS warm runtime behaviour.+### Lambda Proxy (BYO container)++For languages AWS doesn't ship a runtime for (PHP, Deno, Bun, custom builds), point a function at your own running container instead of having MiniStack execute a deployment package. MiniStack forwards the Lambda event to that container as an HTTP POST and returns its JSON response as the function result.++The function is a real Lambda in MiniStack's registry — it has an ARN, shows up in `list-functions`, and works as a target for API Gateway `AWS_PROXY` integrations, EventBridge rules, SQS event sources, Step Functions tasks, and any other Lambda trigger. Only the execute hop is redirected.++Configure it per-function via the standard `CreateFunction` API:++```python+import boto3+lam = boto3.client("lambda", endpoint_url="http://localhost:4566", region_name="us-east-1",+ aws_access_key_id="test", aws_secret_access_key="test")++lam.create_function(+ FunctionName="phpapi",+ Runtime="provided", # any value; ignored in proxy mode+ Role="arn:aws:iam::000000000000:role/r",+ Handler="index.handler", # any value; ignored in proxy mode+ Code={"ZipFile": b"PK\x05\x06" + b"\x00" * 18}, # empty zip stub+ Environment={"Variables": {+ "MINISTACK_LAMBDA_PROXY_URL": "http://host.docker.internal:9000/invoke",+ }},+)+```++Or globally via env var at startup: `MINISTACK_LAMBDA_PROXY_<func-name>=http://...`.++Your container receives the Lambda event JSON as the request body. Reply with the function's response as JSON (or a Lambda Proxy response shape `{"statusCode", "headers", "body"}` if it sits behind API Gateway). MiniStack passes these context headers on every forward:++| Header | Value |+|---|---|+| `X-Amzn-Lambda-Function-Name` | `phpapi` |+| `X-Amzn-Lambda-Function-Version` | `$LATEST` |+| `X-Amzn-Lambda-Function-Arn` | `arn:aws:lambda:us-east-1:000000000000:function:phpapi` |+| `X-Amzn-Lambda-Request-Id` | per-invocation UUID |+| `X-Amzn-Lambda-Deadline-Ms` | epoch-ms when the function timeout expires |++Errors map to Lambda's standard error shape so async-invoke retry, DLQ, destinations, and CloudWatch error metrics behave the same as for any other executor:++| What happened | `errorType` | `errorMessage` |+|---|---|---|+| Container unreachable | `Runtime.HandlerError` | `Proxy target … unreachable: …` |+| Took longer than the function `Timeout` | `Sandbox.Timedout` | `Task timed out after N.00 seconds` |+| Container returned non-2xx | `Runtime.HandlerError` | `Proxy target returned HTTP <code>: <body…>` |++**What this is not:** AWS Lambda doesn't have a feature called "register an externally-running container as my function." If you want byte-for-byte parity in production, ship the same container as a Lambda container image (`PackageType=Image`) and use the AWS Lambda Runtime Interface inside it. Proxy mode is a local-dev shortcut for the inner-loop case; what your production code sees from MiniStack at the SDK boundary is identical to AWS, but the handler signature inside your container differs from a real Lambda runtime contract.+---## Architecturediff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 905264b3..f105f356 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -34,10 +34,13 @@ import jsonimport loggingimport osimport re+import socketimport subprocessimport tempfileimport threadingimport time+import urllib.error+import urllib.requestimport zipfilefrom datetime import datetime, timezonefrom typing import Any@@ -86,6 +89,29 @@ LAMBDA_DOCKER_FLAGS = os.environ.get("LAMBDA_DOCKER_FLAGS", "")# real AWS semantics.LAMBDA_STRICT = os.environ.get("LAMBDA_STRICT", "0").lower() in ("1", "true", "yes")+# Lambda proxy mode: invocations are forwarded to a user-managed HTTP+# container instead of running in ministack's worker pool. The container+# receives the Lambda event JSON as the request body and replies with the+# response JSON. Lets users back languages AWS doesn't ship a runtime for+# (PHP, Deno, etc.) with their existing dev container, without bloating+# ministack's image with per-language runtimes.+#+# Configured per-function via the standard CreateFunction API by setting+# Environment.Variables.MINISTACK_LAMBDA_PROXY_URL, or globally per name via+# the env var MINISTACK_LAMBDA_PROXY_<func_name>.+_PROXY_ENV_VAR = "MINISTACK_LAMBDA_PROXY_URL"+_PROXY_PREFIX = "MINISTACK_LAMBDA_PROXY_"+++def _proxy_url_for(config: dict) -> str | None:+ env = (config.get("Environment") or {}).get("Variables") or {}+ url = env.get(_PROXY_ENV_VAR)+ if url:+ return url+ name = config.get("FunctionName") or ""+ return os.environ.get(_PROXY_PREFIX + name) or None++try:docker_lib: Any = importlib.import_module("docker")_docker_available = True@@ -2532,11 +2558,12 @@ def _execute_function(func: dict, event: dict) -> dict:request_id = new_uuid()started = time.time()- # LAMBDA_STRICT=1 forces ALL runtimes through the Docker RIE pool, matching- # real AWS ("every invocation runs in a container"). Without it, only- # Image-type and LAMBDA_EXECUTOR=docker go through Docker; everything else- # uses the in-process fallbacks below.- if LAMBDA_STRICT:+ # Proxy mode wins over every other executor: the function is bound to a+ # user-managed container, ministack only forwards the event.+ proxy_url = _proxy_url_for(config)+ if proxy_url:+ result = _execute_function_proxy(func, event, proxy_url, request_id)+ elif LAMBDA_STRICT:result = _execute_function_docker(func, event)elif config.get("PackageType") == "Image" and config.get("ImageUri"):result = _execute_function_docker(func, event)@@ -2607,6 +2634,74 @@ def lambda_execute_result_to_api_proxy_response(exec_result: dict) -> tuple[dictreturn {"statusCode": 200, "body": json.dumps(payload, ensure_ascii=False)}, None+def _execute_function_proxy(func: dict, event: dict, url: str, request_id: str) -> dict:+ """Forward a Lambda invocation to a user-managed HTTP container.++ The container receives the Lambda event JSON as the request body and is+ expected to reply with the response JSON. Errors (timeout, connection+ refused, non-2xx, malformed JSON) are returned in Lambda's standard+ {"errorMessage", "errorType"} shape so async-invoke retry, DLQ,+ destinations, and CloudWatch error metrics behave the same as for any+ other executor.+ """+ config = func.get("config") or func+ func_name = config.get("FunctionName", "")+ timeout = int(config.get("Timeout") or 3)++ payload = json.dumps(event, ensure_ascii=False).encode("utf-8")+ headers = {+ "Content-Type": "application/json",+ "X-Amzn-Lambda-Function-Name": func_name,+ "X-Amzn-Lambda-Function-Version": config.get("Version", "$LATEST"),+ "X-Amzn-Lambda-Function-Arn": config.get("FunctionArn", ""),+ "X-Amzn-Lambda-Request-Id": request_id,+ "X-Amzn-Lambda-Deadline-Ms": str(int((time.time() + timeout) * 1000)),+ }+ req = urllib.request.Request(url, data=payload, headers=headers, method="POST")+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ body_bytes = resp.read()+ status = resp.getcode()+ except urllib.error.HTTPError as e:+ body_bytes = e.read() or b""+ status = e.code+ except (urllib.error.URLError, TimeoutError, socket.timeout) as e:+ is_timeout = isinstance(e, (TimeoutError, socket.timeout)) or (+ isinstance(e, urllib.error.URLError) and isinstance(e.reason, (TimeoutError, socket.timeout))+ )+ return {+ "body": {+ "errorMessage": f"Task timed out after {timeout}.00 seconds" if is_timeout+ else f"Proxy target {url} unreachable: {e}",+ "errorType": "Sandbox.Timedout" if is_timeout else "Runtime.HandlerError",+ },+ "error": True,+ }+ except Exception as e: # pragma: no cover - defensive+ return {+ "body": {"errorMessage": str(e), "errorType": "Runtime.HandlerError"},+ "error": True,+ }++ if status < 200 or status >= 300:+ return {+ "body": {+ "errorMessage": f"Proxy target returned HTTP {status}: "+ f"{body_bytes[:512].decode('utf-8', 'replace')}",+ "errorType": "Runtime.HandlerError",+ },+ "error": True,+ }++ text = body_bytes.decode("utf-8", "replace")+ if not text:+ return {"body": None}+ try:+ return {"body": json.loads(text)}+ except json.JSONDecodeError:+ return {"body": text}++def _execute_function_warm(func: dict, event: dict) -> dict:"""Execute a Lambda function using the warm worker pool (Python + Node.js)."""config = func.get("config") or funcdiff --git a/tests/test_lambda_proxy.py b/tests/test_lambda_proxy.pynew file mode 100644index 00000000..d2df2d10--- /dev/null+++ b/tests/test_lambda_proxy.py@@ -0,0 +1,203 @@+"""BYO-container Lambda proxy: forward Invoke to a user-managed HTTP server.++The proxy URL is configured per-function via Environment.Variables.MINISTACK_LAMBDA_PROXY_URL,+which means tests don't need to restart the server — they create a function with+the proxy URL in its environment and invoke it.+"""+import io+import json+import os+import threading+import time+import zipfile+from http.server import BaseHTTPRequestHandler, HTTPServer++import boto3+import pytest++_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+++def _make_zip(code: str = "def handler(event,context):\n return event\n") -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++class _ProxyHandler(BaseHTTPRequestHandler):+ received: list[dict] = []+ response: tuple[int, bytes, dict] = (200, b'{"ok":true}', {"Content-Type": "application/json"})+ sleep_seconds: float = 0.0++ def do_POST(self): # noqa: N802+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length) if length else b""+ type(self).received.append({+ "path": self.path,+ "headers": {k: v for k, v in self.headers.items()},+ "body": body,+ })+ if type(self).sleep_seconds:+ time.sleep(type(self).sleep_seconds)+ status, payload, headers = type(self).response+ self.send_response(status)+ for k, v in headers.items():+ self.send_header(k, v)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, *_args, **_kwargs):+ pass+++def proxy_server():+ server = HTTPServer(("127.0.0.1", 0), _ProxyHandler)+ port = server.server_address[1]+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ _ProxyHandler.received = []+ _ProxyHandler.response = (200, b'{"ok":true}', {"Content-Type": "application/json"})+ _ProxyHandler.sleep_seconds = 0.0+ try:+ yield port+ finally:+ server.shutdown()+++def _make_client():+ return boto3.client(+ "lambda",+ endpoint_url=_endpoint,+ region_name="us-east-1",+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+++def _create_proxy_function(client, name: str, url: str | None):+ env = {"Variables": {"MINISTACK_LAMBDA_PROXY_URL": url}} if url else None+ kwargs = dict(+ FunctionName=name,+ Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/x",+ Handler="index.handler",+ Code={"ZipFile": _make_zip()},+ )+ if env is not None:+ kwargs["Environment"] = env+ client.create_function(**kwargs)+++def test_proxy_invoke_forwards_event_and_returns_response(proxy_server):+ name = "proxy_echo"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")++ event = {"hello": "world", "n": 42}+ resp = client.invoke(FunctionName=name, Payload=json.dumps(event).encode())+ body = json.loads(resp["Payload"].read())++ assert body == {"ok": True}+ assert _ProxyHandler.received, "container never received the invocation"+ forwarded = _ProxyHandler.received[-1]+ assert forwarded["path"] == "/invoke"+ assert json.loads(forwarded["body"]) == event+ h = forwarded["headers"]+ assert h.get("X-Amzn-Lambda-Function-Name") == name+ assert h.get("X-Amzn-Lambda-Request-Id")+ assert h.get("X-Amzn-Lambda-Function-Arn", "").endswith(f":function:{name}")+++def test_proxy_invoke_passes_through_response_payload(proxy_server):+ name = "proxy_payload"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")+ _ProxyHandler.response = (200, b'{"statusCode":201,"body":"created"}', {"Content-Type": "application/json"})++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ body = json.loads(resp["Payload"].read())+ assert body == {"statusCode": 201, "body": "created"}+++def test_proxy_invoke_non_2xx_returns_lambda_error_shape(proxy_server):+ name = "proxy_500"+ client = _make_client()+ _create_proxy_function(client, name, f"http://127.0.0.1:{proxy_server}/invoke")+ _ProxyHandler.response = (500, b"boom", {"Content-Type": "text/plain"})++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ assert resp.get("FunctionError") == "Unhandled"+ body = json.loads(resp["Payload"].read())+ assert body.get("errorType") == "Runtime.HandlerError"+ assert "HTTP 500" in body.get("errorMessage", "")+++def test_proxy_invoke_unreachable_returns_lambda_error_shape():+ name = "proxy_unreachable"+ client = _make_client()+ _create_proxy_function(client, name, "http://127.0.0.1:1/invoke")++ resp = client.invoke(FunctionName=name, Payload=b"{}")+ assert resp.get("FunctionError") == "Unhandled"+ body = json.loads(resp["Payload"].read())+ assert body.get("errorType") in ("Runtime.HandlerError", "Sandbox.Timedout")+ assert "errorMessage" in body+++def test_proxy_unset_falls_back_to_normal_executor():+ name = "proxy_unset"+ client = _make_client()+ _create_proxy_function(client, name, None)+ resp = client.invoke(FunctionName=name, Payload=b'{"a":1}')+ body = json.loads(resp["Payload"].read())+ assert body == {"a": 1}+++def test_proxy_via_apigw_aws_proxy_integration(proxy_server):+ """API Gateway HTTP API routes through to a proxy Lambda's container and returns its response."""+ import urllib.request as _urlreq+ from urllib.parse import urlparse++ name = "proxy_apigw_fn"+ lam = _make_client()+ _create_proxy_function(lam, name, f"http://127.0.0.1:{proxy_server}/invoke")++ # Container replies with a Lambda Proxy response shape, which APIGW unwraps.+ _ProxyHandler.response = (+ 200,+ b'{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\\"hi\\":\\"from-php\\"}"}',+ {"Content-Type": "application/json"},+ )++ apigw = boto3.client(+ "apigatewayv2",+ endpoint_url=_endpoint,+ region_name="us-east-1",+ aws_access_key_id="test",+ aws_secret_access_key="test",+ )+ api_id = apigw.create_api(Name=f"proxy-api-{name}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{name}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /hello", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ port = urlparse(_endpoint).port or 4566+ url = f"http://{api_id}.execute-api.localhost:{port}/$default/hello"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:{port}")+ resp = _urlreq.urlopen(req)+ assert resp.status == 200+ assert json.loads(resp.read()) == {"hi": "from-php"}++ # The container should have received an APIGW v2 event JSON, not a raw HTTP request.+ forwarded = json.loads(_ProxyHandler.received[-1]["body"])+ assert forwarded.get("rawPath") == "/hello"+ assert forwarded.get("requestContext", {}).get("http", {}).get("method") == "GET"