Skip to content

Commit dd46858

Browse files
fix(event_handler): make HttpResolverLocal usable as a Lambda handler (#8634)
* fix(event_handler): make HttpResolverLocal usable as a Lambda handler - __call__ dispatches (event, context) to resolve() and (scope, receive, send) to the ASGI handler. The async handler is also exposed as the instance's __call__ attribute so uvicorn and hypercorn still detect an ASGI3 application. - Map v2 payload events (HTTP API, Function URL) to APIGatewayProxyEventV2. - Base64-encode request bodies that are not valid UTF-8. Refs #8582 (item 3) * fix(event_handler): keep the REST API response shape when HttpResolverLocal handles a v1 event --------- Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent f5c304a commit dd46858

2 files changed

Lines changed: 152 additions & 14 deletions

File tree

‎aws_lambda_powertools/event_handler/http_resolver.py‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
ProxyEventType,
1313
)
1414
from aws_lambda_powertools.shared.headers_serializer import BaseHeadersSerializer
15+
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent, APIGatewayProxyEventV2
1516
from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent
1617

1718
if TYPE_CHECKING:
@@ -66,18 +67,23 @@ def __init__(
6667
multi_query_params = parsed
6768
query_params = {k: v[-1] for k, v in parsed.items()}
6869

69-
# Normalize body to string
70-
body_str = None
71-
if body is not None:
72-
body_str = body.decode("utf-8") if isinstance(body, bytes) else body
70+
# Normalize body to string, base64 if not UTF-8
71+
body_str = body
72+
is_base64_encoded = False
73+
if isinstance(body, bytes):
74+
try:
75+
body_str = body.decode("utf-8")
76+
except UnicodeDecodeError:
77+
body_str = base64.b64encode(body).decode("ascii")
78+
is_base64_encoded = True
7379

7480
# Build the internal dict structure that BaseProxyEvent expects
7581
data = {
7682
"httpMethod": method.upper(),
7783
"path": path,
7884
"headers": headers or {},
7985
"body": body_str,
80-
"isBase64Encoded": False,
86+
"isBase64Encoded": is_base64_encoded,
8187
"queryStringParameters": query_params,
8288
"multiValueQueryStringParameters": multi_query_params,
8389
"pathParameters": path_parameters or {},
@@ -226,6 +232,8 @@ def __init__(
226232
strip_prefixes=strip_prefixes,
227233
enable_validation=enable_validation,
228234
)
235+
# ASGI servers inspect app.__call__ to detect an ASGI3 app
236+
self.__call__ = self.asgi_handler # type: ignore[method-assign]
229237

230238
@property
231239
def _state(self) -> _RequestState:
@@ -268,7 +276,17 @@ def processed_stack_frames(self, value: list[str]) -> None:
268276
self._state.processed_stack_frames = value
269277

270278
def _to_proxy_event(self, event: dict) -> BaseProxyEvent:
271-
"""Convert event dict to HttpProxyEvent."""
279+
"""Map a Lambda event to its data class, or an ASGI-built dict to HttpProxyEvent.
280+
281+
The data class decides the response shape: REST API needs `multiValueHeaders` and rejects
282+
a `cookies` key, HTTP API and Function URL expect `headers` and `cookies`.
283+
"""
284+
if event.get("version") == "2.0" and "httpMethod" not in event:
285+
return APIGatewayProxyEventV2(event, self._json_body_deserializer)
286+
287+
if "resource" in event and "multiValueHeaders" in event:
288+
return APIGatewayProxyEvent(event, self._json_body_deserializer)
289+
272290
# Create HttpProxyEvent directly from the dict data
273291
# The dict already has queryStringParameters and multiValueQueryStringParameters
274292
return HttpProxyEvent._from_dict(event)
@@ -345,14 +363,11 @@ async def asgi_handler(self, scope: MutableMapping[str, Any], receive: Callable,
345363
# Send HTTP response
346364
await self._send_response(send, response)
347365

348-
async def __call__( # type: ignore[override]
349-
self,
350-
scope: MutableMapping[str, Any],
351-
receive: Callable,
352-
send: Callable,
353-
) -> None:
354-
"""ASGI interface - allows running with uvicorn/hypercorn/etc."""
355-
await self.asgi_handler(scope, receive, send)
366+
def __call__(self, *args: Any) -> Any:
367+
"""Lambda handler or ASGI app, depending on the arguments."""
368+
if len(args) == 3:
369+
return self.asgi_handler(*args)
370+
return self.resolve(*args)
356371

357372
async def _send_response(self, send: Callable, response: dict) -> None:
358373
"""Send the response via ASGI."""

‎tests/functional/event_handler/required_dependencies/test_http_resolver.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,16 @@
33
from __future__ import annotations
44

55
import asyncio
6+
import base64
7+
import inspect
68
import json
79
from typing import Any
810

911
import pytest
1012

1113
from aws_lambda_powertools.event_handler import HttpResolverLocal, Response
1214
from aws_lambda_powertools.event_handler.http_resolver import MockLambdaContext
15+
from tests.functional.utils import load_event
1316

1417
# =============================================================================
1518
# ASGI Test Helpers
@@ -1454,3 +1457,123 @@ async def send(message: dict[str, Any]) -> None:
14541457
assert "X-Not-Allowed" not in allow_headers_value
14551458
# AND the explicitly allowed header IS present
14561459
assert "X-Custom-Allowed" in allow_headers_value
1460+
1461+
1462+
# =============================================================================
1463+
# Lambda Handler Tests
1464+
# =============================================================================
1465+
1466+
1467+
def test_app_as_lambda_handler():
1468+
# GIVEN an app used directly as the Lambda handler (handler = app)
1469+
app = HttpResolverLocal()
1470+
1471+
@app.get("/my/path")
1472+
def get_path():
1473+
return {"ok": True}
1474+
1475+
# WHEN Lambda invokes it with (event, context)
1476+
result = app(load_event("apiGatewayProxyEvent.json"), MockLambdaContext())
1477+
1478+
# THEN it resolves like app.resolve()
1479+
assert result["statusCode"] == 200
1480+
assert json.loads(result["body"]) == {"ok": True}
1481+
1482+
1483+
def test_app_is_detected_as_asgi3_application():
1484+
# GIVEN an app that is also callable as a Lambda handler
1485+
app = HttpResolverLocal()
1486+
1487+
# THEN ASGI servers still detect it as an ASGI3 app
1488+
assert asyncio.iscoroutinefunction(app.__call__)
1489+
assert inspect.iscoroutinefunction(app.__call__)
1490+
1491+
1492+
@pytest.mark.parametrize(
1493+
"event_file,method,path",
1494+
[
1495+
("apiGatewayProxyV2Event.json", "POST", "/my/path"),
1496+
("lambdaFunctionUrlEvent.json", "GET", "/"),
1497+
],
1498+
)
1499+
def test_resolve_v2_payload_events(event_file: str, method: str, path: str):
1500+
# GIVEN an app with a route matching an HTTP API v2 or Function URL event
1501+
app = HttpResolverLocal()
1502+
1503+
@app.route(path, method=method)
1504+
def handler():
1505+
return {"ok": True}
1506+
1507+
# WHEN resolving the v2-shaped event
1508+
result = app.resolve(load_event(event_file), MockLambdaContext())
1509+
1510+
# THEN it is mapped to the matching event contract and resolved
1511+
assert result["statusCode"] == 200
1512+
assert json.loads(result["body"]) == {"ok": True}
1513+
1514+
1515+
@pytest.mark.asyncio
1516+
async def test_asgi_binary_request_body():
1517+
# GIVEN an app that echoes the raw request body back
1518+
app = HttpResolverLocal()
1519+
binary_data = b"\x89PNG\r\n\x1a\n\x00\x00\x00" # not valid UTF-8
1520+
1521+
@app.post("/upload")
1522+
def upload():
1523+
assert app.current_event.is_base64_encoded
1524+
return {"size": len(base64.b64decode(app.current_event.body))}
1525+
1526+
scope = {
1527+
"type": "http",
1528+
"method": "POST",
1529+
"path": "/upload",
1530+
"query_string": b"",
1531+
"headers": [(b"content-type", b"application/octet-stream")],
1532+
}
1533+
1534+
receive = make_asgi_receive(binary_data)
1535+
send, captured = make_asgi_send()
1536+
1537+
# WHEN a non-UTF-8 body is sent via ASGI
1538+
await app(scope, receive, send)
1539+
1540+
# THEN the body is base64-encoded instead of failing to decode
1541+
assert captured["status_code"] == 200
1542+
assert json.loads(captured["body"]) == {"size": len(binary_data)}
1543+
1544+
1545+
def test_lambda_handler_rest_event_uses_rest_response_shape():
1546+
# GIVEN an HttpResolver used directly as the Lambda handler behind a REST API
1547+
app = HttpResolverLocal()
1548+
1549+
@app.get("/my/path")
1550+
def handler():
1551+
return {"ok": True}
1552+
1553+
# WHEN a REST API (v1) event is resolved
1554+
result = app(load_event("apiGatewayProxyEvent.json"), {})
1555+
1556+
# THEN the response uses the v1 shape; REST API returns 502 when a `cookies` key is present
1557+
assert result["statusCode"] == 200
1558+
assert "multiValueHeaders" in result
1559+
assert "cookies" not in result
1560+
1561+
1562+
def test_lambda_handler_http_api_event_uses_v2_response_shape():
1563+
# GIVEN an HttpResolver used directly as the Lambda handler behind an HTTP API
1564+
app = HttpResolverLocal()
1565+
event = load_event("apiGatewayProxyV2Event.json")
1566+
event["rawPath"] = event["requestContext"]["http"]["path"] = "/my/path"
1567+
event["requestContext"]["http"]["method"] = "GET"
1568+
1569+
@app.get("/my/path")
1570+
def handler():
1571+
return {"ok": True}
1572+
1573+
# WHEN an HTTP API (v2) event is resolved
1574+
result = app(event, {})
1575+
1576+
# THEN the response uses the v2 shape
1577+
assert result["statusCode"] == 200
1578+
assert "cookies" in result
1579+
assert "multiValueHeaders" not in result

0 commit comments

Comments
 (0)