diff --git a/aws_lambda_powertools/event_handler/api_gateway.py b/aws_lambda_powertools/event_handler/api_gateway.py index ec9b6b0011c..9a8467010f8 100644 --- a/aws_lambda_powertools/event_handler/api_gateway.py +++ b/aws_lambda_powertools/event_handler/api_gateway.py @@ -74,6 +74,10 @@ _UNSAFE_URI = r"%<> \[\]{}|^" _NAMED_GROUP_BOUNDARY_PATTERN = rf"(?P\1[{_SAFE_URI}{_UNSAFE_URI}\\w]+)" _ROUTE_REGEX = "^{}$" +# A static rule with any of these is a regex (/proxy/.+), not an exact path (/proxy/health). +# "." is left out: a rule whose only metacharacter is "." (/files/readme.txt, /v1.0/health) +# still matches one fixed-length path shape, so it can go before rules with quantifiers or groups. +_REGEX_METACHARACTERS = frozenset("^$*+?{}[]\\|()") _JSON_DUMP_CALL = partial(json.dumps, separators=(",", ":"), cls=Encoder) _ALB_MAX_RESPONSE_SIZE = 1024 * 1024 @@ -2589,8 +2593,20 @@ def register_resolver(func: AnyCallableT) -> AnyCallableT: # We store dynamic (/studies/{studyid}) and static routes (/studies/fetch) separately. # Then attempt a match for static routes before dynamic routes. # This ensures that the most specific route is prioritized and processed first (studies/fetch). + # Within static routes, exact paths (/proxy/health) also go before regex rules + # without named groups (/proxy/.+), whatever the registration order. if _route.rule.groups > 0: self._dynamic_routes.append(_route) + elif _REGEX_METACHARACTERS.isdisjoint(rule): + first_regex = next( + ( + i + for i, static in enumerate(self._static_routes) + if not _REGEX_METACHARACTERS.isdisjoint(static.path) + ), + len(self._static_routes), + ) + self._static_routes.insert(first_regex, _route) else: self._static_routes.append(_route) diff --git a/tests/functional/event_handler/required_dependencies/test_api_gateway.py b/tests/functional/event_handler/required_dependencies/test_api_gateway.py index 4f8d49d2a10..fff834939f9 100644 --- a/tests/functional/event_handler/required_dependencies/test_api_gateway.py +++ b/tests/functional/event_handler/required_dependencies/test_api_gateway.py @@ -1329,6 +1329,85 @@ def handler(**route_keys): assert json.loads(result["body"]) == expected_route_keys +@pytest.mark.parametrize("catch_all_first", [True, False], ids=["catch-all registered first", "exact registered first"]) +def test_exact_route_takes_precedence_over_catch_all_regex(catch_all_first: bool): + # GIVEN an exact route and a catch-all regex route under the same prefix + app = APIGatewayRestResolver() + + def catch_all(): + return {"route": "catch-all"} + + def health(): + return {"route": "health"} + + routes = [("/proxy/.+", catch_all), ("/proxy/health", health)] + for rule, func in routes if catch_all_first else reversed(routes): + app.get(rule)(func) + + # WHEN calling the event handler with the exact path and with another path + exact = app({"httpMethod": "GET", "path": "/proxy/health"}, None) + other = app({"httpMethod": "GET", "path": "/proxy/other"}, None) + + # THEN the exact route wins whatever the registration order, as the "Catch-all routes" docs say + assert json.loads(exact["body"]) == {"route": "health"} + assert json.loads(other["body"]) == {"route": "catch-all"} + + +@pytest.mark.parametrize( + "catch_all_rule, exact_path, other_path", + [ + pytest.param("/.well-known/.+", "/.well-known/jwks.json", "/.well-known/other", id="dot in file name"), + pytest.param("/files/.+", "/files/readme.txt", "/files/other", id="file extension"), + pytest.param("/v1.0/.+", "/v1.0/health", "/v1.0/other", id="versioned prefix"), + ], +) +def test_exact_route_with_dot_takes_precedence_over_catch_all_regex( + catch_all_rule: str, + exact_path: str, + other_path: str, +): + # GIVEN a catch-all regex route registered before an exact route whose path contains a dot + app = APIGatewayRestResolver() + + @app.get(catch_all_rule) + def catch_all(): + return {"route": "catch-all"} + + @app.get(exact_path) + def exact(): + return {"route": "exact"} + + # WHEN calling the event handler with the exact path and with another path + exact_result = app({"httpMethod": "GET", "path": exact_path}, None) + other_result = app({"httpMethod": "GET", "path": other_path}, None) + + # THEN the exact route wins, and other paths still go to the catch-all + assert json.loads(exact_result["body"]) == {"route": "exact"} + assert json.loads(other_result["body"]) == {"route": "catch-all"} + + +def test_exact_route_from_router_takes_precedence_over_catch_all_regex(): + # GIVEN a catch-all regex route on the app, and an exact route included later from a prefixed router + app = APIGatewayRestResolver() + router = Router() + + @app.get("/proxy/.+") + def catch_all(): + return {"route": "catch-all"} + + @router.get("/health") + def health(): + return {"route": "health"} + + app.include_router(router, prefix="/proxy") + + # WHEN calling the event handler with the exact path + result = app({"httpMethod": "GET", "path": "/proxy/health"}, None) + + # THEN the exact route from the router wins + assert json.loads(result["body"]) == {"route": "health"} + + def test_similar_dynamic_routes(): # GIVEN app = ApiGatewayResolver()