Skip to content

Commit e695afa

Browse files
committed
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 aws-powertools#8582 (item 3)
1 parent 0f64f28 commit e695afa

2 files changed

Lines changed: 111 additions & 14 deletions

File tree

‎aws_lambda_powertools/event_handler/http_resolver.py‎

Lines changed: 24 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 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-encoding bodies that are not valid 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,10 @@ def __init__(
226232
strip_prefixes=strip_prefixes,
227233
enable_validation=enable_validation,
228234
)
235+
# ASGI servers pick the interface by inspecting `app.__call__` (uvicorn: ASGI3 vs ASGI2,
236+
# hypercorn: ASGI vs WSGI), while `app(...)` always uses the class-level __call__.
237+
# Exposing the async handler here keeps ASGI3 detection now that __call__ is sync.
238+
self.__call__ = self.asgi_handler # type: ignore[method-assign]
229239

230240
@property
231241
def _state(self) -> _RequestState:
@@ -268,7 +278,10 @@ def processed_stack_frames(self, value: list[str]) -> None:
268278
self._state.processed_stack_frames = value
269279

270280
def _to_proxy_event(self, event: dict) -> BaseProxyEvent:
271-
"""Convert event dict to HttpProxyEvent."""
281+
"""Convert event dict to HttpProxyEvent, or to the v2 contract for HTTP API and Function URL events."""
282+
if event.get("version") == "2.0" and "httpMethod" not in event:
283+
return APIGatewayProxyEventV2(event, self._json_body_deserializer)
284+
272285
# Create HttpProxyEvent directly from the dict data
273286
# The dict already has queryStringParameters and multiValueQueryStringParameters
274287
return HttpProxyEvent._from_dict(event)
@@ -345,14 +358,11 @@ async def asgi_handler(self, scope: MutableMapping[str, Any], receive: Callable,
345358
# Send HTTP response
346359
await self._send_response(send, response)
347360

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)
361+
def __call__(self, *args: Any) -> Any:
362+
"""Lambda handler for (event, context), ASGI application for (scope, receive, send)."""
363+
if len(args) == 3:
364+
return self.asgi_handler(*args)
365+
return self.resolve(*args)
356366

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

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

Lines changed: 87 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,87 @@ 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 __call__ as a coroutine function (ASGI3, not ASGI2/WSGI)
1488+
# uvicorn uses asyncio.iscoroutinefunction (< 3.14), hypercorn uses inspect.iscoroutinefunction
1489+
assert asyncio.iscoroutinefunction(app.__call__)
1490+
assert inspect.iscoroutinefunction(app.__call__)
1491+
1492+
1493+
@pytest.mark.parametrize(
1494+
"event_file,method,path",
1495+
[
1496+
("apiGatewayProxyV2Event.json", "POST", "/my/path"),
1497+
("lambdaFunctionUrlEvent.json", "GET", "/"),
1498+
],
1499+
)
1500+
def test_resolve_v2_payload_events(event_file: str, method: str, path: str):
1501+
# GIVEN an app with a route matching an HTTP API v2 or Function URL event
1502+
app = HttpResolverLocal()
1503+
1504+
@app.route(path, method=method)
1505+
def handler():
1506+
return {"ok": True}
1507+
1508+
# WHEN resolving the v2-shaped event
1509+
result = app.resolve(load_event(event_file), MockLambdaContext())
1510+
1511+
# THEN it is mapped to the matching event contract and resolved
1512+
assert result["statusCode"] == 200
1513+
assert json.loads(result["body"]) == {"ok": True}
1514+
1515+
1516+
@pytest.mark.asyncio
1517+
async def test_asgi_binary_request_body():
1518+
# GIVEN an app that echoes the raw request body back
1519+
app = HttpResolverLocal()
1520+
binary_data = b"\x89PNG\r\n\x1a\n\x00\x00\x00" # not valid UTF-8
1521+
1522+
@app.post("/upload")
1523+
def upload():
1524+
assert app.current_event.is_base64_encoded
1525+
return {"size": len(base64.b64decode(app.current_event.body))}
1526+
1527+
scope = {
1528+
"type": "http",
1529+
"method": "POST",
1530+
"path": "/upload",
1531+
"query_string": b"",
1532+
"headers": [(b"content-type", b"application/octet-stream")],
1533+
}
1534+
1535+
receive = make_asgi_receive(binary_data)
1536+
send, captured = make_asgi_send()
1537+
1538+
# WHEN a non-UTF-8 body is sent via ASGI
1539+
await app(scope, receive, send)
1540+
1541+
# THEN the body is base64-encoded instead of failing to decode
1542+
assert captured["status_code"] == 200
1543+
assert json.loads(captured["body"]) == {"size": len(binary_data)}

0 commit comments

Comments
 (0)