From 0101c2a2405b966c31218aa6bf4189ec982ed9c8 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sun, 28 Dec 2025 19:30:54 +0100 Subject: [PATCH] Use Result for validate_nest_path (#3606) --- axum/src/routing/path_router.rs | 21 ++++++++++++--------- axum/src/routing/tests/nest.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/axum/src/routing/path_router.rs b/axum/src/routing/path_router.rs index 89e54d6d..b1abe82c 100644 --- a/axum/src/routing/path_router.rs +++ b/axum/src/routing/path_router.rs @@ -174,7 +174,7 @@ where path_to_nest_at: &str, router: Self, ) -> Result<(), Cow<'static, str>> { - let prefix = validate_nest_path(self.v7_checks, path_to_nest_at); + let prefix = validate_nest_path(self.v7_checks, path_to_nest_at)?; let Self { routes, @@ -219,7 +219,7 @@ where T::Response: IntoResponse, T::Future: Send + 'static, { - let path = validate_nest_path(self.v7_checks, path_to_nest_at); + let path = validate_nest_path(self.v7_checks, path_to_nest_at)?; let prefix = path; let path = if path.ends_with('/') { @@ -442,22 +442,25 @@ impl fmt::Debug for Node { } } -#[track_caller] -fn validate_nest_path(v7_checks: bool, path: &str) -> &str { - assert!(path.starts_with('/')); - assert!(path.len() > 1); +fn validate_nest_path(v7_checks: bool, path: &str) -> Result<&str, &'static str> { + if !path.starts_with('/') { + return Err("Nesting paths must start with a `/`."); + } + if path.len() < 2 { + return Err("Nesting at `/` is not supported."); + } if path.split('/').any(|segment| { segment.starts_with("{*") && segment.ends_with('}') && !segment.ends_with("}}") }) { - panic!("Invalid route: nested routes cannot contain wildcards (*)"); + return Err("Invalid route: nested routes cannot contain wildcards (*)"); } if v7_checks { - validate_v07_paths(path).unwrap(); + validate_v07_paths(path)?; } - path + Ok(path) } pub(crate) fn path_for_nested_route<'a>(prefix: &'a str, path: &'a str) -> Cow<'a, str> { diff --git a/axum/src/routing/tests/nest.rs b/axum/src/routing/tests/nest.rs index 3368346e..8724c419 100644 --- a/axum/src/routing/tests/nest.rs +++ b/axum/src/routing/tests/nest.rs @@ -105,6 +105,18 @@ fn nest_service_at_empty_path() { let _: Router = Router::new().nest_service("", get(|| async {})); } +#[test] +#[should_panic(expected = "Nesting paths must start with a `/`.")] +fn nest_no_slash() { + let _: Router = Router::new().nest("x", Router::new()); +} + +#[test] +#[should_panic(expected = "Nesting paths must start with a `/`.")] +fn nest_service_no_slash() { + let _: Router = Router::new().nest_service("x", get(|| async {})); +} + #[crate::test] async fn nested_url_extractor() { let app = Router::new().nest(