Skip to content

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

fix(apigateway): non-proxy lambda integrations return raw output (#1376)

iot-rocketaa5ec6c3daa1
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 58432cd1..5387e3ad 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -618,6 +618,13 @@ def _match_recursive(resources, parent_id, segments, params):
def _extract_lambda_ref_from_integration_uri(uri: str) -> str:
+ """Pull the Lambda reference out of an integration URI.
+
+ Supported URI formats:
+ 1. arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]/invocations
+ 2. arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]
+ 3. plain function name: MyFunction[:{qualifier}]
+ """
if not uri:
return ""
if "/functions/" in uri:
@@ -630,12 +637,22 @@ def _extract_lambda_ref_from_integration_uri(uri: str) -> str:
return uri
-async def _call_lambda(function_ref, event, *, account_id=None, region=None):
- """Invoke a Lambda function and return the parsed response dict.
+async def _call_lambda_raw(function_ref, event, *, account_id=None, region=None):
+ """Invoke a Lambda function and return its uninterpreted execution record.
- ``function_ref`` may be a name, partial ARN, or full ARN. Full ARNs are
- resolved through Lambda's scoped lookup so region-qualified integration URIs
- invoke the function named in the ARN instead of the request/default region."""
+ Returns ``(result, error_msg)`` where ``result["body"]`` is the payload
+ exactly as the function returned it. ``function_ref`` may be a name, partial
+ ARN, or full ARN; full ARNs are resolved through Lambda's scoped lookup so
+ region-qualified integration URIs invoke the function named in the ARN
+ instead of the request/default region.
+
+ Routed through the central ``_execute_function`` dispatcher so CloudWatch
+ Logs emission and Docker log output work for API Gateway invocations.
+
+ Non-proxy (custom) integrations need the raw payload; :func:`_call_lambda`
+ is this plus the AWS_PROXY response shaper, which would rewrite a handler's
+ ``statusCode`` key into the HTTP status.
+ """
from ministack.services import lambda_svc
func_data, func_config, func_name = lambda_svc._get_func_record_for_ref_in_scope(
@@ -647,12 +664,25 @@ async def _call_lambda(function_ref, event, *, account_id=None, region=None):
label = function_ref or func_name
return None, f"Lambda function '{label}' not found"
- # Route through the central _execute_function dispatcher so CloudWatch
- # Logs emission and Docker log output work for API Gateway invocations.
- # Response shaping (throttle→429, error→502, body→envelope) goes through
- # the shared helper so v1/v2 stay consistent.
exec_record = lambda_svc._execution_record_for_config(func_data, func_config)
result = await asyncio.to_thread(lambda_svc._execute_function_with_config_scope, exec_record, event)
+ return result, None
+
+
+async def _call_lambda(function_ref, event, *, account_id=None, region=None):
+ """Invoke a Lambda function and return the parsed AWS_PROXY response dict.
+
+ :func:`_call_lambda_raw` plus the shared response shaper (throttle→429,
+ error→502, body→envelope), which is what keeps v1 and v2 consistent.
+ """
+ from ministack.services import lambda_svc
+
+ result, err = await _call_lambda_raw(
+ function_ref, event, account_id=account_id, region=region
+ )
+ if err:
+ return None, err
+
lambda_response, _ = lambda_svc.lambda_execute_result_to_api_proxy_response(result)
# On error the helper returns {statusCode: 502, body: <msg>}; preserve
# the _call_lambda contract of (None, error_msg) so callers that check
@@ -1590,7 +1620,12 @@ async def _handle_execute_in_scope(
int_type = integration.get("type", "")
if int_type in ("AWS_PROXY", "AWS"):
- return await _invoke_lambda_proxy_v1(
+ # AWS_PROXY hands the function a response envelope to interpret; the
+ # non-proxy `AWS` (custom / "lambda") integration returns the handler's
+ # output as the body verbatim. Same event in, different response
+ # contract out.
+ invoke = _invoke_lambda_proxy_v1 if int_type == "AWS_PROXY" else _invoke_lambda_custom_v1
+ return await invoke(
integration, api_id, stage_name, stage, resource, path, method,
headers, body, query_params, path_params,
owner_account_id=owner_account_id,
@@ -1627,8 +1662,7 @@ def _media_type_matches(media_type, binary_media_types):
return False
-async def _invoke_lambda_proxy_v1(
- integration,
+def _build_lambda_event_v1(
api_id,
stage_name,
stage,
@@ -1640,19 +1674,17 @@ async def _invoke_lambda_proxy_v1(
query_params,
path_params,
*,
- owner_account_id=None,
- owner_region=None,
binary_media_types=None,
authorizer_context=None,
):
- """Invoke Lambda with API Gateway v1 payload format 1.0."""
- uri = integration.get("uri", "")
- # Supported URI formats:
- # 1. arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]/invocations
- # 2. arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]
- # 3. plain function name: MyFunction[:{qualifier}]
- lambda_ref = _extract_lambda_ref_from_integration_uri(uri)
+ """Build the API Gateway v1 payload format 1.0 event handed to Lambda.
+ Shared by the AWS_PROXY and the non-proxy (custom) AWS integration paths.
+ The two differ in how the *response* is interpreted, not in what the
+ function is invoked with: a non-proxy integration would normally reshape the
+ request through a `requestTemplates` mapping template, which is not modeled
+ here — the function receives the same synthesized event either way.
+ """
qs_params = {k: v[0] for k, v in query_params.items()} if query_params else None
mv_qs_params = {k: list(v) for k, v in query_params.items()} if query_params else None
@@ -1715,6 +1747,38 @@ async def _invoke_lambda_proxy_v1(
if authorizer_context is not None:
event["requestContext"]["authorizer"] = authorizer_context
+ return event
+
+
+async def _invoke_lambda_proxy_v1(
+ integration,
+ api_id,
+ stage_name,
+ stage,
+ resource,
+ request_path,
+ method,
+ headers,
+ body,
+ query_params,
+ path_params,
+ *,
+ owner_account_id=None,
+ owner_region=None,
+ binary_media_types=None,
+ authorizer_context=None,
+):
+ """Invoke Lambda through an AWS_PROXY integration and interpret its
+ `{statusCode, headers, body}` response envelope."""
+ lambda_ref = _extract_lambda_ref_from_integration_uri(integration.get("uri", ""))
+
+ event = _build_lambda_event_v1(
+ api_id, stage_name, stage, resource, request_path, method,
+ headers, body, query_params, path_params,
+ binary_media_types=binary_media_types,
+ authorizer_context=authorizer_context,
+ )
+
lambda_response, err = await _call_lambda(
lambda_ref,
event,
@@ -1768,6 +1832,92 @@ async def _invoke_lambda_proxy_v1(
return status, resp_headers, resp_body
+def _default_integration_response_status_v1(integration):
+ """The status code a successful non-proxy integration answers with.
+
+ AWS selects the integration response whose ``selectionPattern`` is empty —
+ the default mapping, which handles every invocation that did not fail — and
+ falls back to 200 when the method has no integration responses configured.
+ ``responseTemplates`` / ``responseParameters`` are not modeled; the payload
+ is passed through verbatim.
+ """
+ for code, resp in sorted((integration.get("integrationResponses") or {}).items()):
+ if not (resp or {}).get("selectionPattern"):
+ try:
+ return int((resp or {}).get("statusCode") or code)
+ except (TypeError, ValueError):
+ return 200
+ return 200
+
+
+async def _invoke_lambda_custom_v1(
+ integration,
+ api_id,
+ stage_name,
+ stage,
+ resource,
+ request_path,
+ method,
+ headers,
+ body,
+ query_params,
+ path_params,
+ *,
+ owner_account_id=None,
+ owner_region=None,
+ binary_media_types=None,
+ authorizer_context=None,
+):
+ """Invoke Lambda through a non-proxy (custom) ``AWS`` integration.
+
+ Unlike AWS_PROXY there is no ``{statusCode, headers, body}`` envelope: the
+ function's return value IS the response body, serialized as JSON and sent
+ with the integration response's status code (200 by default). A handler that
+ happens to return a ``statusCode`` key therefore ships that key to the client
+ inside the body instead of having it promoted to the HTTP status.
+
+ A function error answers 502 ``{"message": "Internal server error"}`` —
+ the error payload is never surfaced to the caller.
+ """
+ lambda_ref = _extract_lambda_ref_from_integration_uri(integration.get("uri", ""))
+
+ event = _build_lambda_event_v1(
+ api_id, stage_name, stage, resource, request_path, method,
+ headers, body, query_params, path_params,
+ binary_media_types=binary_media_types,
+ authorizer_context=authorizer_context,
+ )
+
+ result, err = await _call_lambda_raw(
+ lambda_ref,
+ event,
+ account_id=owner_account_id,
+ region=owner_region,
+ )
+ if err:
+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": err}).encode()
+
+ resp_headers = {"Content-Type": "application/json"}
+ if result.get("throttle"):
+ throttle_body = result.get("body") or {}
+ payload = throttle_body if isinstance(throttle_body, dict) else {"message": str(throttle_body)}
+ return 429, resp_headers, json.dumps(payload).encode()
+ if result.get("error"):
+ return 502, resp_headers, json.dumps({"message": "Internal server error"}).encode()
+
+ payload = result.get("body")
+ if payload is None:
+ resp_body = b""
+ elif isinstance(payload, (bytes, bytearray)):
+ resp_body = bytes(payload)
+ else:
+ # The payload is a JSON document, so a bare string comes back quoted —
+ # matching what `lambda invoke` writes and what AWS passes through.
+ resp_body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+
+ return _default_integration_response_status_v1(integration), resp_headers, resp_body
+
+
async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_params, path_params=None):
"""Forward a request to an HTTP backend."""
uri = integration.get("uri", "")
diff --git a/tests/conftest.py b/tests/conftest.py
index eac1d7ad..a3ac0831 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -83,6 +83,12 @@ _SERIAL_TESTS = {
"tests/test_apigatewayv2.py::test_apigwv1_path_based_restapi_legacy_user_request",
"tests/test_apigatewayv2.py::test_apigwv2_named_stage_still_requires_prefix",
"tests/test_apigatewayv2.py::test_apigwv2_integration_wrapped_function_arn",
+ # Non-proxy (custom) AWS integration tests: same execute-api → Lambda
+ # cold-start shape as the ones above, one function created per test.
+ "tests/test_apigatewayv1.py::test_apigwv1_execute_lambda_custom_returns_raw_output",
+ "tests/test_apigatewayv1.py::test_apigwv1_execute_lambda_custom_function_error_is_502",
+ "tests/test_apigatewayv1.py::test_apigwv1_execute_lambda_custom_without_integration_responses_is_200",
+ "tests/test_apigatewayv1.py::test_apigwv1_execute_lambda_proxy_envelope_still_interpreted",
# v1 Lambda-authorizer cache tests. Same cold-start-burst sensitivity as the
# apigw tests above, doubled: every guarded request cold-starts TWO Lambdas
# (the authorizer and the backend), and the invocation-count assertions that
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 08c1cff8..35424d34 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1413,6 +1413,185 @@ def test_apigwv1_execute_lambda_proxy_header_case_override(apigw_v1, lam):
lam.delete_function(FunctionName=fname)
+def _deploy_custom_integration_api(
+ apigw_v1, lam, fname, code, path_part,
+ *, integration_type="AWS", with_integration_response=True,
+):
+ """Deploy a REST API whose GET method integrates a freshly created Lambda.
+
+ Defaults to the non-proxy `AWS` integration with the default (empty
+ selectionPattern) integration response. `integration_type="AWS_PROXY"` and
+ `with_integration_response=False` cover the two contrasting cases.
+ Returns (api_id, url)."""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-custom-{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=path_part,
+ )["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=integration_type,
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ if with_integration_response:
+ apigw_v1.put_integration_response(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ statusCode="200",
+ selectionPattern="",
+ )
+ 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/{path_part}"
+ return api_id, url
+
+
+def test_apigwv1_execute_lambda_custom_returns_raw_output(apigw_v1, lam):
+ """A non-proxy (custom) `AWS` integration returns the handler output verbatim.
+
+ Unlike AWS_PROXY there is no `{statusCode, headers, body}` envelope to
+ interpret: the return value IS the response body, serialized as JSON, and
+ the status comes from the integration response (200). A handler that
+ happens to return a `statusCode` key ships that key to the client inside
+ the body — it must NOT be promoted to the HTTP status.
+ """
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-v1-custom-raw-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 418, 'body': 'x', 'nested': {'ok': True}}\n"
+ )
+ api_id, url = _deploy_custom_integration_api(apigw_v1, lam, fname, code, "custom")
+ try:
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ # The handler's `statusCode` is data, not the HTTP status.
+ assert resp.status == 200
+ assert resp.headers.get("Content-Type") == "application/json"
+ assert json.loads(resp.read()) == {"statusCode": 418, "body": "x", "nested": {"ok": True}}
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_lambda_custom_function_error_is_502(apigw_v1, lam):
+ """A function error on a non-proxy integration is a 502 with the generic
+ gateway body — AWS never leaks the error payload to the caller."""
+ import urllib.error as _urlerr
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-v1-custom-err-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" raise RuntimeError('kaboom')\n"
+ )
+ api_id, url = _deploy_custom_integration_api(apigw_v1, lam, fname, code, "boom")
+ try:
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(req)
+ assert exc.value.code == 502
+ body = json.loads(exc.value.read())
+ assert body == {"message": "Internal server error"}
+ assert "kaboom" not in json.dumps(body)
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_lambda_custom_without_integration_responses_is_200(
+ apigw_v1, lam
+):
+ """A method with no integrationResponses at all still answers 200.
+
+ put_integration_response is optional, and a method that never called it has
+ nothing to select a status from. AWS answers 200; the status lookup must
+ fall back rather than fail or invent one from the payload.
+ """
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-v1-custom-noresp-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 418, 'body': 'x'}\n"
+ )
+ api_id, url = _deploy_custom_integration_api(
+ apigw_v1, lam, fname, code, "noresp", with_integration_response=False,
+ )
+ try:
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ assert json.loads(resp.read()) == {"statusCode": 418, "body": "x"}
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_lambda_proxy_envelope_still_interpreted(apigw_v1, lam):
+ """The AWS_PROXY contract is untouched by the non-proxy split.
+
+ The same handler payload that a custom integration must return verbatim is
+ a response envelope here: `statusCode` becomes the HTTP status and `body`
+ becomes the body. Pinned against the identical handler so a future change
+ to the shared event builder or the type dispatch cannot quietly swap the
+ two contracts.
+ """
+ import urllib.error as _urlerr
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-v1-proxy-pin-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 418, 'body': 'x'}\n"
+ )
+ api_id, url = _deploy_custom_integration_api(
+ apigw_v1, lam, fname, code, "proxypin", integration_type="AWS_PROXY",
+ )
+ try:
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(req)
+ assert exc.value.code == 418
+ assert exc.value.read() == b"x"
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
def test_apigwv1_execute_lambda_proxy_binary_media_types(apigw_v1, lam):
"""REST API (v1) binary support keyed off `binaryMediaTypes`.