Skip to content

fix(event_handler): prioritize static over dynamic route to prevent order of route registration mismatch #2458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 14, 2023
Merged
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
17 changes: 14 additions & 3 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,8 @@ def __init__(
with api gateways with multiple custom mappings.
"""
self._proxy_type = proxy_type
self._routes: List[Route] = []
self._dynamic_routes: List[Route] = []
self._static_routes: List[Route] = []
self._route_keys: List[str] = []
self._exception_handlers: Dict[Type, Callable] = {}
self._cors = cors
Expand Down Expand Up @@ -515,7 +516,17 @@ def register_resolver(func: Callable):
cors_enabled = cors

for item in methods:
self._routes.append(Route(item, self._compile_regex(rule), func, cors_enabled, compress, cache_control))
_route = Route(item, self._compile_regex(rule), func, cors_enabled, compress, cache_control)

# The more specific route wins.
# 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).
if _route.rule.groups > 0:
self._dynamic_routes.append(_route)
else:
self._static_routes.append(_route)

route_key = item + rule
if route_key in self._route_keys:
warnings.warn(
Expand Down Expand Up @@ -624,7 +635,7 @@ def _resolve(self) -> ResponseBuilder:
"""Resolves the response or return the not found response"""
method = self.current_event.http_method.upper()
path = self._remove_prefix(self.current_event.path)
for route in self._routes:
for route in self._static_routes + self._dynamic_routes:
if method != route.method:
continue
match_results: Optional[Match] = route.rule.match(path)
Expand Down
27 changes: 25 additions & 2 deletions tests/functional/event_handler/test_api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def handler(event, context):
return app.resolve(event, context)

# Also check the route configurations
routes = app._routes
routes = app._static_routes
assert len(routes) == 5
for route in routes:
if route.func == get_func:
Expand Down Expand Up @@ -1205,7 +1205,7 @@ def patch_func():
app.include_router(router)

# Also check check the route configurations
routes = app._routes
routes = app._static_routes
assert len(routes) == 5
for route in routes:
if route.func == get_func:
Expand Down Expand Up @@ -1647,3 +1647,26 @@ def get_message():
assert response["multiValueHeaders"]["Content-Type"] == [content_types.APPLICATION_JSON]
response_body = json.loads(response["body"])
assert response_body["message"] == "success"


def test_route_match_prioritize_full_match():
# GIVEN a Http API V1, with a function registered with two routes
app = APIGatewayRestResolver()
router = Router()

@router.get("/my/{path}")
def dynamic_handler() -> Response:
return Response(200, content_types.APPLICATION_JSON, json.dumps({"hello": "dynamic"}))

@router.get("/my/path")
def static_handler() -> Response:
return Response(200, content_types.APPLICATION_JSON, json.dumps({"hello": "static"}))

app.include_router(router)

# WHEN calling the event handler with /foo/dynamic
response = app(LOAD_GW_EVENT, {})

# THEN the static_handler should have been called, because it fully matches the path directly
response_body = json.loads(response["body"])
assert response_body["hello"] == "static"