diff --git a/aws_lambda_powertools/utilities/data_classes/vpc_lattice.py b/aws_lambda_powertools/utilities/data_classes/vpc_lattice.py index ae2fd91e829..5c1aea56e46 100644 --- a/aws_lambda_powertools/utilities/data_classes/vpc_lattice.py +++ b/aws_lambda_powertools/utilities/data_classes/vpc_lattice.py @@ -16,7 +16,7 @@ class VPCLatticeEventBase(BaseProxyEvent): - # is_base64_encoded and path are inherited from BaseProxyEvent class. + # is_base64_encoded is inherited from BaseProxyEvent class. @property def body(self) -> str: @@ -57,7 +57,7 @@ def header_serializer(self) -> BaseHeadersSerializer: class VPCLatticeEvent(VPCLatticeEventBase): @property def raw_path(self) -> str: - """The raw VPC Lattice request path.""" + """The raw VPC Lattice request path, including the query string.""" return self["raw_path"] @property @@ -69,7 +69,8 @@ def is_base64_encoded(self) -> bool: # Added here for consistency with the BaseProxyEvent class @property def path(self) -> str: - return self["raw_path"] + """The request path, without the query string that VPC Lattice includes in `raw_path`.""" + return self["raw_path"].partition("?")[0] @property def query_string_parameters(self) -> dict[str, str]: @@ -176,6 +177,11 @@ def request_context(self) -> vpcLatticeEventV2RequestContext: """The VPC Lattice v2 Event request context.""" return vpcLatticeEventV2RequestContext(self["requestContext"]) + @property + def path(self) -> str: + """The request path, without the query string that VPC Lattice includes in `path`.""" + return self["path"].partition("?")[0] + @cached_property def query_string_parameters(self) -> dict[str, str]: """The request query string parameters. diff --git a/tests/events/vpcLatticeEventWithQueryString.json b/tests/events/vpcLatticeEventWithQueryString.json new file mode 100644 index 00000000000..091f838a321 --- /dev/null +++ b/tests/events/vpcLatticeEventWithQueryString.json @@ -0,0 +1,15 @@ +{ + "raw_path": "/testpath?order-id=1", + "method": "GET", + "headers": { + "user_agent": "curl/7.64.1", + "x-forwarded-for": "10.213.229.10", + "host": "test-lambda-service-3908sdf9u3u.dkfjd93.vpc-lattice-svcs.us-east-2.on.aws", + "accept": "*/*" + }, + "query_string_parameters": { + "order-id": "1" + }, + "body": "eyJ0ZXN0IjogImV2ZW50In0=", + "is_base64_encoded": true +} diff --git a/tests/events/vpcLatticeV2EventWithQueryString.json b/tests/events/vpcLatticeV2EventWithQueryString.json new file mode 100644 index 00000000000..e5c5f4d25a0 --- /dev/null +++ b/tests/events/vpcLatticeV2EventWithQueryString.json @@ -0,0 +1,28 @@ +{ + "version": "2.0", + "path": "/echo?QS1=value1&QS1=value2&single=one", + "method": "POST", + "headers": { + "x-amzn-requestid": ["6ccfc913-b027-4fdc-be66-a07809329ee3"], + "content-type": ["application/json"], + "x-forwarded-for": ["10.42.0.189"], + "header1": ["value1", "value2"], + "host": ["my-service-0123456789abcdef0.7d67968.vpc-lattice-svcs.eu-west-1.on.aws"] + }, + "queryStringParameters": { + "QS1": ["value1", "value2"], + "single": ["one"] + }, + "body": "{\"hello\":\"world\"}", + "requestContext": { + "serviceNetworkArn": "arn:aws:vpc-lattice:eu-west-1:123456789012:servicenetwork/sn-0123456789abcdef0", + "serviceArn": "arn:aws:vpc-lattice:eu-west-1:123456789012:service/svc-0123456789abcdef0", + "targetGroupArn": "arn:aws:vpc-lattice:eu-west-1:123456789012:targetgroup/tg-0123456789abcdef0", + "identity": { + "sourceVpcArn": "arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-0123456789abcdef0" + }, + "region": "eu-west-1", + "timeEpoch": "1790935900260914" + }, + "requestId": "6ccfc913-b027-4fdc-be66-a07809329ee3" +} diff --git a/tests/functional/event_handler/_pydantic/test_openapi_validation_middleware.py b/tests/functional/event_handler/_pydantic/test_openapi_validation_middleware.py index c1484241405..0af4cdcfb0e 100644 --- a/tests/functional/event_handler/_pydantic/test_openapi_validation_middleware.py +++ b/tests/functional/event_handler/_pydantic/test_openapi_validation_middleware.py @@ -1255,6 +1255,42 @@ def handler3(): assert any(text in result["body"] for text in expected_error_text) +def test_validation_query_string_in_path_with_vpc_lattice_v1_resolver(gw_event_vpc_lattice_v1): + # GIVEN a VPCLatticeResolver with validation enabled + app = VPCLatticeResolver(enable_validation=True) + + @app.get("/orders") + def handler(order_id: Annotated[int, Query(alias="order-id")]): + return {"order_id": order_id} + + # WHEN VPC Lattice sends the query string in raw_path, and parsed in query_string_parameters + gw_event_vpc_lattice_v1["raw_path"] = "/orders?order-id=1" + gw_event_vpc_lattice_v1["query_string_parameters"] = {"order-id": "1"} + result = app(gw_event_vpc_lattice_v1, {}) + + # THEN the route matches and the query string parameter is validated + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"order_id": 1} + + +def test_validation_query_string_in_path_with_vpc_lattice_v2_resolver(gw_event_vpc_lattice): + # GIVEN a VPCLatticeV2Resolver with validation enabled + app = VPCLatticeV2Resolver(enable_validation=True) + + @app.get("/orders") + def handler(order_id: Annotated[int, Query(alias="order-id")]): + return {"order_id": order_id} + + # WHEN VPC Lattice sends the query string in path, and parsed in queryStringParameters + gw_event_vpc_lattice["path"] = "/orders?order-id=1" + gw_event_vpc_lattice["queryStringParameters"] = {"order-id": ["1"]} + result = app(gw_event_vpc_lattice, {}) + + # THEN the route matches and the query string parameter is validated + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"order_id": 1} + + ########### TEST WITH HEADER PARAMS @pytest.mark.parametrize( "handler_func, expected_status_code, expected_error_text", diff --git a/tests/functional/event_handler/required_dependencies/test_vpc_lattice.py b/tests/functional/event_handler/required_dependencies/test_vpc_lattice.py index 73168a36408..fb3c2695350 100644 --- a/tests/functional/event_handler/required_dependencies/test_vpc_lattice.py +++ b/tests/functional/event_handler/required_dependencies/test_vpc_lattice.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json + from aws_lambda_powertools.event_handler import ( Response, VPCLatticeResolver, @@ -50,6 +52,42 @@ def foo(): assert result["body"] == json_dump(expected) +def test_vpclattice_event_with_query_string(): + # GIVEN a VPC Lattice event whose raw_path carries the query string + app = VPCLatticeResolver() + + @app.get("/testpath") + def foo(): + return {"order_id": app.current_event.query_string_parameters["order-id"]} + + # WHEN calling the event handler + result = app(load_event("vpcLatticeEventWithQueryString.json"), {}) + + # THEN the route matches the path without the query string + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"order_id": "1"} + + +def test_vpclattice_dynamic_route_with_query_string(): + # GIVEN a VPC Lattice event for a dynamic route, with the query string in raw_path + app = VPCLatticeResolver() + + @app.get("/orders/") + def get_order(order_id: str): + return {"order_id": order_id, "expand": app.current_event.query_string_parameters["expand"]} + + event = load_event("vpcLatticeEvent.json") + event["raw_path"] = "/orders/42?expand=items" + event["query_string_parameters"] = {"expand": "items"} + + # WHEN calling the event handler + result = app(event, {}) + + # THEN the path parameter does not include the query string + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"order_id": "42", "expand": "items"} + + def test_cors_preflight_body_is_empty_not_null(): # GIVEN CORS is configured app = VPCLatticeResolver(cors=CORSConfig()) diff --git a/tests/functional/event_handler/required_dependencies/test_vpc_latticev2.py b/tests/functional/event_handler/required_dependencies/test_vpc_latticev2.py index a83fcb3c30d..2f032431d8f 100644 --- a/tests/functional/event_handler/required_dependencies/test_vpc_latticev2.py +++ b/tests/functional/event_handler/required_dependencies/test_vpc_latticev2.py @@ -1,5 +1,8 @@ from __future__ import annotations +import asyncio +import json + from aws_lambda_powertools.event_handler import ( Response, VPCLatticeV2Resolver, @@ -50,6 +53,61 @@ def foo(): assert result["body"] == json_dump(expected) +def test_vpclatticev2_event_with_query_string(): + # GIVEN an event captured from a VPC Lattice V2 target group, whose path carries the query string + app = VPCLatticeV2Resolver() + + @app.post("/echo") + def echo(): + return {"query": app.current_event.query_string_parameters, "body": app.current_event.json_body} + + # WHEN calling the event handler + result = app(load_event("vpcLatticeV2EventWithQueryString.json"), {}) + + # THEN the route matches the path without the query string + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == { + "query": {"QS1": "value1,value2", "single": "one"}, + "body": {"hello": "world"}, + } + + +def test_vpclatticev2_dynamic_route_with_query_string(): + # GIVEN a VPC Lattice V2 event for a dynamic route, with the query string in path + app = VPCLatticeV2Resolver() + + @app.get("/orders/") + def get_order(order_id: str): + return {"order_id": order_id, "expand": app.current_event.query_string_parameters["expand"]} + + event = load_event("vpcLatticeV2Event.json") + event["path"] = "/orders/42?expand=items" + event["queryStringParameters"] = {"expand": ["items"]} + + # WHEN calling the event handler + result = app(event, {}) + + # THEN the path parameter does not include the query string + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"order_id": "42", "expand": "items"} + + +def test_vpclatticev2_resolve_async_with_query_string(): + # GIVEN an async handler for a VPC Lattice V2 event whose path carries the query string + app = VPCLatticeV2Resolver() + + @app.post("/echo") + async def echo(): + return {"single": app.current_event.query_string_parameters["single"]} + + # WHEN resolving the event asynchronously + result = asyncio.run(app.resolve_async(load_event("vpcLatticeV2EventWithQueryString.json"), {})) + + # THEN the route matches the path without the query string + assert result["statusCode"] == 200 + assert json.loads(result["body"]) == {"single": "one"} + + def test_cors_preflight_body_is_empty_not_null(): # GIVEN CORS is configured app = VPCLatticeV2Resolver(cors=CORSConfig()) diff --git a/tests/unit/data_classes/required_dependencies/test_vpc_lattice_event.py b/tests/unit/data_classes/required_dependencies/test_vpc_lattice_event.py index 5445fcea882..56543da8a2c 100644 --- a/tests/unit/data_classes/required_dependencies/test_vpc_lattice_event.py +++ b/tests/unit/data_classes/required_dependencies/test_vpc_lattice_event.py @@ -1,5 +1,7 @@ from __future__ import annotations +import pytest + from aws_lambda_powertools.utilities.data_classes.vpc_lattice import VPCLatticeEvent from tests.functional.utils import load_event @@ -9,6 +11,7 @@ def test_vpc_lattice_event(): parsed_event = VPCLatticeEvent(raw_event) assert parsed_event.raw_path == raw_event["raw_path"] + assert parsed_event.path == raw_event["raw_path"] assert parsed_event.query_string_parameters["order-id"] == "1" assert parsed_event.headers["user_agent"] == "curl/7.64.1" assert parsed_event.decoded_body == '{"test": "event"}' @@ -18,3 +21,32 @@ def test_vpc_lattice_event(): assert parsed_event.query_string_parameters == raw_event["query_string_parameters"] assert parsed_event.body == raw_event["body"] assert parsed_event.is_base64_encoded == raw_event["is_base64_encoded"] + + +def test_vpc_lattice_event_with_query_string(): + # VPC Lattice sends the query string in raw_path, and parsed in query_string_parameters + raw_event = load_event("vpcLatticeEventWithQueryString.json") + parsed_event = VPCLatticeEvent(raw_event) + + assert parsed_event.path == "/testpath" + assert parsed_event.raw_path == "/testpath?order-id=1" + assert parsed_event.query_string_parameters == {"order-id": "1"} + + +@pytest.mark.parametrize( + "raw_path, expected_path", + [ + ("/?query1=value1&query2=value2", "/"), + ("/testpath?", "/testpath"), + ("/testpath?next=/orders?page=2", "/testpath"), + ("/files/report%3Fv2?download=true", "/files/report%3Fv2"), + ], + ids=["root_path", "empty_query", "question_mark_in_query", "encoded_question_mark_in_path"], +) +def test_vpc_lattice_event_path_excludes_query_string(raw_path, expected_path): + raw_event = load_event("vpcLatticeEvent.json") + raw_event["raw_path"] = raw_path + parsed_event = VPCLatticeEvent(raw_event) + + assert parsed_event.path == expected_path + assert parsed_event.raw_path == raw_path diff --git a/tests/unit/data_classes/required_dependencies/test_vpc_lattice_eventv2.py b/tests/unit/data_classes/required_dependencies/test_vpc_lattice_eventv2.py index 7661abea603..63ac224767d 100644 --- a/tests/unit/data_classes/required_dependencies/test_vpc_lattice_eventv2.py +++ b/tests/unit/data_classes/required_dependencies/test_vpc_lattice_eventv2.py @@ -44,3 +44,32 @@ def test_vpc_lattice_v2_event(): assert parsed_event.request_context.identity.x509_san_uri is None assert parsed_event.request_context.identity.x509_subject_cn is None assert parsed_event.request_context.identity.principal_org_id is None + + +def test_vpc_lattice_v2_event_with_query_string(): + # Event captured from a V2 target group: path carries the query string, which is also sent parsed + raw_event = load_event("vpcLatticeV2EventWithQueryString.json") + parsed_event = VPCLatticeEventV2(raw_event) + + assert parsed_event.path == "/echo" + assert parsed_event.raw_event["path"] == "/echo?QS1=value1&QS1=value2&single=one" + assert parsed_event.query_string_parameters == {"QS1": "value1,value2", "single": "one"} + + +@pytest.mark.parametrize( + "event_path, expected_path", + [ + ("/?query1=value1&query2=value2", "/"), + ("/newpath?", "/newpath"), + ("/newpath?next=/orders?page=2", "/newpath"), + ("/files/report%3Fv2?download=true", "/files/report%3Fv2"), + ], + ids=["root_path", "empty_query", "question_mark_in_query", "encoded_question_mark_in_path"], +) +def test_vpc_lattice_v2_event_path_excludes_query_string(event_path, expected_path): + raw_event = load_event("vpcLatticeV2Event.json") + raw_event["path"] = event_path + parsed_event = VPCLatticeEventV2(raw_event) + + assert parsed_event.path == expected_path + assert parsed_event.raw_event["path"] == event_path