Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions aws_lambda_powertools/event_handler/http_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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": "",
},
},
}

Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
# =============================================================================
Expand Down