fix(test): reject unclassified route method chains

Classify the complete outer MethodRouter chain and ignore handler and middleware arguments when collecting HTTP methods.

Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
This commit is contained in:
Brad Seiler
2026-11-04 19:23:11 -05:00
committed by GitHub
parent cac5501106
commit 3f2fd75400
3 changed files with 100 additions and 16 deletions

View File

@@ -460,17 +460,10 @@ def collect_registered_routes() -> Counter:
except ValueError as error:
errors.append(f"{path.relative_to(ROOT)}::{name}: {error}")
continue
methods = {
method.upper()
for method in re.findall(
r"\b(get|head|post|put|delete|patch|options|trace|connect|any)\s*\(",
method_mask,
)
}
if not methods:
errors.append(
f"{path.relative_to(ROOT)}::{name}: no Axum HTTP method in route expression"
)
try:
methods = route_methods(method_mask)
except ValueError as error:
errors.append(f"{path.relative_to(ROOT)}::{name}: {error}")
continue
full_path = f"{prefix.rstrip('/')}{route}" if prefix else route
for method in methods:
@@ -485,6 +478,40 @@ def collect_registered_routes() -> Counter:
return registrations
def route_methods(method_mask: str) -> set[str]:
"""Classify an entire MethodRouter chain, never calls inside its arguments.
Keep this grammar deliberately small: an Axum routing helper followed by
known method helpers or non-method modifiers. Unknown chains must fail so
a newly added Axum API cannot silently expose an uninventoried method.
"""
expression = method_mask.strip().removesuffix(",").rstrip()
methods = set()
position = 0
first = True
while position < len(expression):
pattern = (
r"(?:axum::routing::)?([A-Za-z_]\w*)\s*\("
if first
else r"\s*\.\s*([A-Za-z_]\w*)\s*\("
)
call = re.compile(pattern).match(expression, position)
if call is None:
raise ValueError("unclassified route method expression")
name = call.group(1)
if name in HTTP_METHODS:
methods.add(HTTP_METHODS[name])
elif first or name not in {"with_state", "layer", "route_layer"}:
raise ValueError(f"unclassified route method expression: {name}")
# Handler and middleware arguments can themselves call functions named
# get/post/etc.; those calls do not register HTTP methods on this route.
position = matching_delimiter(expression, call.end() - 1) + 1
first = False
if not methods:
raise ValueError("unclassified route method expression: no Axum HTTP method")
return methods
def read_tsv(path: Path, expected_header: list[str]) -> list[dict[str, str]]:
with path.open(newline="") as file:
reader = csv.DictReader(file, delimiter="\t")

View File

@@ -72,6 +72,58 @@ class RouteScannerFixtures(unittest.TestCase):
with self.assertRaisesRegex(ValueError, message):
self.scan(router, admin)
def test_unclassified_method_chains_are_rejected(self):
for expression in (
"get(read).on(MethodFilter::PATCH, write)",
"get(read).on_service(MethodFilter::PATCH, svc)",
"get(read).post_service(svc)",
"on(MethodFilter::PATCH, write)",
"on_service(MethodFilter::PATCH, svc)",
"get_service(svc)",
"get(read).custom(write)",
"wrap(get(read))",
"opaque.get(read)",
):
with self.subTest(expression=expression):
self.assert_rejected(
"unclassified route method expression",
build_router(f'.route("/mixed", {expression})'),
)
def test_supported_method_chains_are_preserved(self):
for expression in (
"get(read).post(write).head(headers)",
"axum::routing::get(read).post(write).head(headers)",
"get(read).with_state(state.clone()).post(write).head(headers)",
"get(read).layer(middleware(layer_arg())).post(write).route_layer(layer).head(headers)",
"get(read) /* .on(MethodFilter::PATCH, write) */ .post(write).head(headers)",
):
with self.subTest(expression=expression):
routes = self.scan(build_router(f'.route("/mixed", {expression},)'))
self.assertEqual(
{method for listener, method, path in routes if path == "/mixed"},
{"GET", "POST", "HEAD"},
)
def test_all_known_http_helpers_are_classified(self):
for helper, method in scanner.HTTP_METHODS.items():
with self.subTest(helper=helper):
routes = self.scan(build_router(f'.route("/method", {helper}(handler))'))
self.assertEqual(
{verb for listener, verb, path in routes if path == "/method"},
{method},
)
def test_calls_inside_handler_and_layer_arguments_are_not_methods(self):
routes = self.scan(build_router(
'.route("/args", get(|| async { post(payload); "patch(fake)" })'
'.layer(make_layer(options(config))))'
))
self.assertEqual(
{method for listener, method, path in routes if path == "/args"},
{"GET"},
)
def test_nested_builder_merge_is_rejected(self):
self.assert_rejected(
r"\.merge registration is not classified",