From f9a473ce089291c9f99dd09980f824d0b6e81f35 Mon Sep 17 00:00:00 2001 From: Ajey Awasthi <115537579+dropps07@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:28:55 +0530 Subject: [PATCH] fix(event_handler): fill request context from ASGI scope in HttpResolverLocal HttpProxyEvent.from_asgi only copied method, path, headers, body and query string, so the request context fell back to a stub with only stage, requestId and http method/path, and HttpProxyEvent had no request_context property. Handlers reading source_ip or user_agent from the request context raised AttributeError under uvicorn. Fill the request context from the ASGI scope: the source IP from scope client and the user agent from the user-agent header, and expose it through a request_context property on the local event. Refs #8802 Signed-off-by: Ajey Awasthi <115537579+dropps07@users.noreply.github.com> --- .../event_handler/http_resolver.py | 58 +++++++++++++- .../test_http_resolver.py | 77 +++++++++++++++++++ 2 files changed, 133 insertions(+), 2 deletions(-) diff --git a/aws_lambda_powertools/event_handler/http_resolver.py b/aws_lambda_powertools/event_handler/http_resolver.py index 79a55e1331d..8845771f03b 100644 --- a/aws_lambda_powertools/event_handler/http_resolver.py +++ b/aws_lambda_powertools/event_handler/http_resolver.py @@ -13,7 +13,11 @@ ) from aws_lambda_powertools.shared.headers_serializer import BaseHeadersSerializer from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent, APIGatewayProxyEventV2 -from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent +from aws_lambda_powertools.utilities.data_classes.common import ( + BaseProxyEvent, + DictWrapper, + RequestContextV2Http, +) if TYPE_CHECKING: from collections.abc import Callable, Mapping, MutableMapping @@ -41,6 +45,30 @@ def serialize(self, headers: dict[str, str | list[str]], cookies: list[Cookie]) return {"headers": combined_headers, "cookies": cookie_headers} +class HttpRequestContext(DictWrapper): + """Request context for a local HTTP event. + + Local events have no API Gateway, so only the fields the ASGI scope can + provide are populated: the stage, the request id and the HTTP details + (method, path, protocol, source IP and user agent). + """ + + @property + def stage(self) -> str: + """The deployment stage of the request.""" + return self.get("stage") or "local" + + @property + def request_id(self) -> str: + """The ID assigned to the request.""" + return self.get("requestId") or "local-request-id" + + @property + def http(self) -> RequestContextV2Http: + """HTTP details of the request (method, path, protocol, source IP, user agent).""" + return RequestContextV2Http(self.get("http") or {}) + + class HttpProxyEvent(BaseProxyEvent): """ A proxy event that wraps native HTTP request data. @@ -91,7 +119,13 @@ def __init__( or { "stage": "local", "requestId": "local-request-id", - "http": {"method": method.upper(), "path": path}, + "http": { + "method": method.upper(), + "path": path, + "protocol": "HTTP/1.1", + "sourceIp": "", + "userAgent": "", + }, }, } @@ -132,14 +166,34 @@ def from_asgi(cls, scope: Mapping[str, Any], body: bytes | None = None) -> HttpP else: headers[header_name] = header_value + # The ASGI scope carries the client address as a (host, port) tuple + # and the user agent in the headers; fill the request context from them. + client = scope.get("client") + source_ip = client[0] if client and client[0] else "" + return cls( method=scope["method"], path=scope["path"], headers=headers, body=body, query_string=scope.get("query_string", b"").decode("utf-8"), + request_context={ + "stage": "local", + "requestId": "local-request-id", + "http": { + "method": scope["method"].upper(), + "path": scope["path"], + "protocol": f"HTTP/{scope.get('http_version', '1.1')}", + "sourceIp": source_ip, + "userAgent": headers.get("user-agent", ""), + }, + }, ) + @property + def request_context(self) -> HttpRequestContext: + return HttpRequestContext(self["requestContext"]) + def header_serializer(self) -> BaseHeadersSerializer: """Return the HTTP headers serializer.""" return HttpHeadersSerializer() diff --git a/tests/functional/event_handler/required_dependencies/test_http_resolver.py b/tests/functional/event_handler/required_dependencies/test_http_resolver.py index ffcc6135339..0ea56ec0475 100644 --- a/tests/functional/event_handler/required_dependencies/test_http_resolver.py +++ b/tests/functional/event_handler/required_dependencies/test_http_resolver.py @@ -603,6 +603,83 @@ def search(): assert body["query"] == "python" +@pytest.mark.asyncio +async def test_asgi_request_context_from_scope(): + # GIVEN an app with a route that reads the request context + app = HttpResolverLocal() + + @app.get("/whoami") + def whoami(): + request_context = app.current_event.request_context + return { + "source_ip": request_context.http.source_ip, + "user_agent": request_context.http.user_agent, + "stage": request_context.stage, + "method": request_context.http.method, + "path": request_context.http.path, + } + + scope = { + "type": "http", + "method": "GET", + "path": "/whoami", + "query_string": b"", + "headers": [(b"user-agent", b"TestAgent/1.0")], + "client": ("203.0.113.10", 52314), + "http_version": "1.1", + } + + receive = make_asgi_receive() + send, captured = make_asgi_send() + + # WHEN called via ASGI interface + await app(scope, receive, send) + + # THEN the request context is filled from the ASGI scope + assert captured["status_code"] == 200 + body = json.loads(captured["body"]) + assert body["source_ip"] == "203.0.113.10" + assert body["user_agent"] == "TestAgent/1.0" + assert body["stage"] == "local" + assert body["method"] == "GET" + assert body["path"] == "/whoami" + + +@pytest.mark.asyncio +async def test_asgi_request_context_without_client_or_user_agent(): + # GIVEN an app with a route that reads the request context + app = HttpResolverLocal() + + @app.get("/whoami") + def whoami(): + request_context = app.current_event.request_context + return { + "source_ip": request_context.http.source_ip, + "user_agent": request_context.http.user_agent, + } + + # No client tuple and no user-agent header in the scope + scope = { + "type": "http", + "method": "GET", + "path": "/whoami", + "query_string": b"", + "headers": [], + } + + receive = make_asgi_receive() + send, captured = make_asgi_send() + + # WHEN called via ASGI interface + await app(scope, receive, send) + + # THEN the request context still resolves with empty values + assert captured["status_code"] == 200 + body = json.loads(captured["body"]) + assert body["source_ip"] == "" + assert body["user_agent"] == "" + + # ============================================================================= # Async Handler Tests # =============================================================================