diff --git a/TESTING.md b/TESTING.md index 128c8ab3d1..135801beee 100644 --- a/TESTING.md +++ b/TESTING.md @@ -46,8 +46,13 @@ registrations, each pinned to its builder and exact argument and allowed once), `.nest` outside `build_router`, a nest target that does not resolve to exactly one router builder, or a builder nested more than once. New or repeated `.merge(...)` registrations also fail; existing root aliases and the Git -settings merge are pinned to their exact builder and argument. `scripts/check-community-ban-route-inventory.test.py` -pins each of those shapes with a fixture. Run both directly with: +settings merge are pinned to their exact builder and argument. +`scripts/check-community-ban-route-inventory.test.py` pins each of those shapes +with a fixture. Route method expressions must start with a known HTTP helper +and contain only known method helpers or `.with_state`, `.layer`, and +`.route_layer` modifiers. Unclassified chains, including `on`, `on_service`, +and `*_service` helpers, fail even when mixed with a known method. +Run both directly with: ```bash python3 scripts/check-community-ban-route-inventory.py @@ -103,9 +108,9 @@ This scanner is a source-level guard, not a Rust router interpreter. It reads direct `.route(...)` calls inside production functions named `router` or ending in `_router`; a `.route(...)` elsewhere is a scanner error. It resolves a `.nest(...)` prefix only when the relay's `build_router` passes a literal -or a resolved string constant and a direct call to another recognized router function. It does not -expand macros or interpret dynamic paths, prefixes or arbitrary router -composition. Service-style calls and unsupported nesting or merging are errors, +or a resolved string constant and a direct call to another recognized router +function. It does not expand macros or interpret dynamic paths, prefixes or +arbitrary router composition. Service-style calls and unsupported nesting or merging are errors, rather than silently omitted registrations. The existing root merge aliases and Git settings merge are explicit, single-use exceptions; their builders' direct routes remain inventoried. It also does not derive auth or diff --git a/scripts/check-community-ban-route-inventory.py b/scripts/check-community-ban-route-inventory.py index 7c942ee83c..be7a3a498f 100644 --- a/scripts/check-community-ban-route-inventory.py +++ b/scripts/check-community-ban-route-inventory.py @@ -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") diff --git a/scripts/check-community-ban-route-inventory.test.py b/scripts/check-community-ban-route-inventory.test.py index 50ca1430ec..0a6fbd8889 100644 --- a/scripts/check-community-ban-route-inventory.test.py +++ b/scripts/check-community-ban-route-inventory.test.py @@ -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",