Skip to content

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

fix(apigateway): emit Set-Cookie and multiValueHeaders from Lambda-proxy responses (#750)

rmlasseter1f7fa25106a3
diff --git a/ministack/app.py b/ministack/app.py
index 9b080f37..0aef5570 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -474,7 +474,17 @@ async def _send_response(send, status, headers, body):
body_bytes = body if isinstance(body, bytes) else body.encode("utf-8")
if "content-length" not in {k.lower() for k in headers}:
headers["Content-Length"] = str(len(body_bytes))
- header_list = [(k.encode("latin-1"), _encode_header_value(str(v))) for k, v in headers.items()]
+ # A list/tuple header value expands to one header line per item. This is
+ # required for Set-Cookie, which RFC 6265 §3 forbids folding into a single
+ # comma-joined header; APIGW Lambda-proxy responses surface multiple
+ # cookies this way. Scalar values keep their existing single-line behavior.
+ header_list = []
+ for k, v in headers.items():
+ if isinstance(v, (list, tuple)):
+ for item in v:
+ header_list.append((k.encode("latin-1"), _encode_header_value(str(item))))
+ else:
+ header_list.append((k.encode("latin-1"), _encode_header_value(str(v))))
await send(
{
"type": "http.response.start",
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index e1d79139..8891a324 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -1005,6 +1005,12 @@ async def _invoke_lambda_proxy(
status = lambda_response.get("statusCode", 200)
resp_headers = {"Content-Type": "application/json"}
resp_headers.update(lambda_response.get("headers", {}))
+ # Payload format 2.0 emits multiple Set-Cookie headers via the top-level
+ # `cookies` array, not the headers map. The list value is expanded into one
+ # Set-Cookie line per entry by _send_response.
+ cookies = lambda_response.get("cookies")
+ if cookies:
+ resp_headers["Set-Cookie"] = list(cookies)
resp_body = lambda_response.get("body", "")
if isinstance(resp_body, str):
resp_body = resp_body.encode("utf-8")
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index f6b9c7c4..b08ee7ca 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -977,6 +977,13 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
status = lambda_response.get("statusCode", 200)
resp_headers = {"Content-Type": "application/json"}
resp_headers.update(lambda_response.get("headers", {}))
+ # Payload format 1.0 carries multi-value headers (notably Set-Cookie) in
+ # `multiValueHeaders`. AWS merges these over `headers`, with multiValueHeaders
+ # winning on key collision. Each list value is expanded into one header line
+ # per entry by _send_response.
+ for k, v in (lambda_response.get("multiValueHeaders") or {}).items():
+ if v:
+ resp_headers[k] = list(v)
resp_body = lambda_response.get("body", "")
if isinstance(resp_body, str):
resp_body = resp_body.encode("utf-8")
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 5c952af1..50d0279a 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -498,6 +498,70 @@ def test_apigwv1_execute_lambda_proxy(apigw_v1, lam):
lam.delete_function(FunctionName=fname)
+def test_apigwv1_execute_lambda_proxy_multi_value_headers(apigw_v1, lam):
+ """Payload format 1.0 `multiValueHeaders` yields one header line per value.
+
+ Real APIGW v1 carries multi-value headers (notably Set-Cookie) in
+ `multiValueHeaders`; each value must reach the wire as a separate header.
+ """
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-v1-mvh-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {\n"
+ b" 'statusCode': 200,\n"
+ b" 'multiValueHeaders': {'Set-Cookie': ['a=1; Path=/', 'b=2; Path=/']},\n"
+ b" 'body': 'ok',\n"
+ b" }\n"
+ )
+ 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-mvh-{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="cookie",
+ )["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=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/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/cookie"
+ 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 (resp.headers.get_all("Set-Cookie") or []) == ["a=1; Path=/", "b=2; Path=/"]
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
@pytest.mark.skipif(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)."""
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 7066d6d6..e747036c 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -349,6 +349,118 @@ def test_apigw_execute_lambda_proxy(apigw, lam):
apigw.delete_api(ApiId=api_id)
lam.delete_function(FunctionName=fname)
+def test_apigw_execute_lambda_proxy_cookies(apigw, lam):
+ """Payload format 2.0 `cookies` array yields one Set-Cookie header per entry.
+
+ Real APIGW v2 emits each `cookies` entry as a separate Set-Cookie response
+ header (RFC 6265 §3 forbids comma-folding them). A regular header returned
+ alongside must still pass through.
+ """
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-apigw-cookie-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {\n"
+ b" 'statusCode': 200,\n"
+ b" 'headers': {'X-App': 'yes'},\n"
+ b" 'cookies': ['session=abc123; Path=/; HttpOnly', 'flag=on; Path=/; SameSite=Lax'],\n"
+ b" 'body': 'ok',\n"
+ b" }\n"
+ )
+ 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.create_api(Name=f"cookie-api-{fname}", ProtocolType="HTTP")["ApiId"]
+ int_id = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
+ PayloadFormatVersion="2.0",
+ )["IntegrationId"]
+ route_id = apigw.create_route(
+ ApiId=api_id,
+ RouteKey="GET /cookie",
+ Target=f"integrations/{int_id}",
+ )["RouteId"]
+ apigw.create_stage(ApiId=api_id, StageName="$default")
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/cookie"
+ 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
+ set_cookies = resp.headers.get_all("Set-Cookie") or []
+ assert set_cookies == [
+ "session=abc123; Path=/; HttpOnly",
+ "flag=on; Path=/; SameSite=Lax",
+ ]
+ # A normal header returned alongside the cookies still passes through.
+ assert resp.headers.get("X-App") == "yes"
+
+ # Cleanup
+ apigw.delete_route(ApiId=api_id, RouteId=route_id)
+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)
+ apigw.delete_api(ApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+def test_apigw_execute_lambda_proxy_empty_cookies(apigw, lam):
+ """An empty `cookies` array emits zero Set-Cookie headers (no empty header)."""
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-apigw-nocookie-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 200, 'cookies': [], 'body': 'ok'}\n"
+ )
+ 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.create_api(Name=f"nocookie-api-{fname}", ProtocolType="HTTP")["ApiId"]
+ int_id = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
+ PayloadFormatVersion="2.0",
+ )["IntegrationId"]
+ route_id = apigw.create_route(
+ ApiId=api_id,
+ RouteKey="GET /nocookie",
+ Target=f"integrations/{int_id}",
+ )["RouteId"]
+ apigw.create_stage(ApiId=api_id, StageName="$default")
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/nocookie"
+ 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 (resp.headers.get_all("Set-Cookie") or []) == []
+
+ # Cleanup
+ apigw.delete_route(ApiId=api_id, RouteId=route_id)
+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)
+ apigw.delete_api(ApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
def test_apigw_execute_no_route(apigw):
"""execute-api returns 404 when no matching route exists."""
import urllib.error as _urlerr