Skip to content

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

fix(apigateway): invoke provided/Image Lambdas from execute-api (AWS_PROXY) (#450)

david-hay3cb831de7f4f
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 24b6225a..e75935b7 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -2382,6 +2382,52 @@ def _execute_function(func: dict, event: dict) -> dict:
return result
+def lambda_execute_result_to_api_proxy_response(exec_result: dict) -> tuple[dict | None, str | None]:
+ """Convert :func:`_execute_function` output into an API Gateway AWS_PROXY-shaped dict.
+
+ Shared by REST (v1) and HTTP API (v2) execute paths so ``provided.*`` / Image
+ Lambdas match ``lambda invoke`` instead of returning a canned mock.
+ """
+ if exec_result.get("throttle"):
+ tb = exec_result.get("body") or {}
+ body_str = json.dumps(tb) if isinstance(tb, dict) else str(tb)
+ return {
+ "statusCode": 429,
+ "headers": {"Content-Type": "application/json"},
+ "body": body_str,
+ }, None
+
+ if exec_result.get("error"):
+ err_body = exec_result.get("body")
+ if isinstance(err_body, dict) and "statusCode" in err_body:
+ return err_body, None
+ payload = json.dumps(err_body) if isinstance(err_body, dict) else str(err_body)
+ return {
+ "statusCode": 502,
+ "headers": {"Content-Type": "application/json"},
+ "body": payload,
+ }, None
+
+ payload = exec_result.get("body")
+ if payload is None:
+ return {"statusCode": 200, "body": ""}, None
+ if isinstance(payload, dict) and "statusCode" in payload:
+ return payload, None
+ if isinstance(payload, (str, bytes)):
+ if isinstance(payload, bytes):
+ payload = payload.decode("utf-8", errors="replace")
+ stripped = payload.strip()
+ if stripped.startswith("{"):
+ try:
+ obj = json.loads(stripped)
+ if isinstance(obj, dict) and "statusCode" in obj:
+ return obj, None
+ except json.JSONDecodeError:
+ pass
+ return {"statusCode": 200, "body": payload}, None
+ return {"statusCode": 200, "body": json.dumps(payload, ensure_ascii=False)}, None
+
+
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 func
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 7437f692..7b1247e0 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1,6 +1,7 @@
import io
import json
import os
+import shutil
import time
import zipfile
from urllib.parse import urlparse
@@ -466,6 +467,80 @@ def test_apigwv1_execute_lambda_proxy(apigw_v1, lam):
apigw_v1.delete_rest_api(restApiId=api_id)
lam.delete_function(FunctionName=fname)
+
[email protected](not shutil.which("curl"), reason="provided bootstrap uses curl for Runtime API")
+def test_apigwv1_execute_lambda_proxy_provided_runtime(apigw_v1, lam):
+ """execute-api AWS_PROXY must run provided.* zips via lambda_svc (Go/terraform parity)."""
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ bootstrap_script = (
+ "#!/bin/sh\n"
+ 'RUNTIME_API="${AWS_LAMBDA_RUNTIME_API}"\n'
+ "while true; do\n"
+ ' RESP=$(curl -s -D /tmp/hdr '
+ '"http://${RUNTIME_API}/2018-06-01/runtime/invocation/next")\n'
+ ' REQUEST_ID=$(grep -i "Lambda-Runtime-Aws-Request-Id" /tmp/hdr '
+ '| tr -d "\\r" | cut -d" " -f2)\n'
+ ' curl -s -X POST '
+ '"http://${RUNTIME_API}/2018-06-01/runtime/invocation/${REQUEST_ID}/response" '
+ "-d '{\"statusCode\":200,\"body\":\"from-provided-bootstrap\"}'\n"
+ "done\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ info = zipfile.ZipInfo("bootstrap")
+ info.external_attr = 0o755 << 16
+ zf.writestr(info, bootstrap_script)
+
+ fname = f"intg-v1-provided-{_uuid.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="provided.al2023",
+ Handler="bootstrap",
+ Code={"ZipFile": buf.getvalue()},
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Timeout=30,
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-provided-{fname}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id,
+ parentId=root["id"],
+ pathPart="hit",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=(
+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ f"arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations"
+ ),
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/hit"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req, timeout=60)
+ assert resp.status == 200
+ assert resp.read() == b"from-provided-bootstrap"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
def test_apigwv1_execute_path_params(apigw_v1, lam):
"""Path parameter {userId} is passed correctly in event['pathParameters']."""
import urllib.request as _urlreq