axum: remove v07 path checks (#3889)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Mládek · committed by GitHub · parent c44f665 · Browse files · 6 files·+32 added−138 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+32 added−138 removed
- tests:+22 added−26 removed
- other:+10 added−112 removed
Provenance
- Commit
7c3c678- Tree
3dbd8af- Author
David Mládek <david.mladek.cz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
c44f665
6 files changed+32 added−138 removed
deleted:axum/src/docs/routing/without_v07_checks.md-43 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243Turn off checks for compatibility with route matching syntax from 0.7.
This allows usage of paths starting with a colon `:` or an asterisk `*` which are otherwise prohibited.
# Example
```rustuse axum::{ routing::get, Router,};
let app = Router::<()>::new() .without_v07_checks() .route("/:colon", get(|| async {})) .route("/*asterisk", get(|| async {}));
// Our app now accepts// - GET /:colon// - GET /*asterisk# let _: Router = app;```
Adding such routes without calling this method first will panic.
```rust,should_panicuse axum::{ routing::get, Router,};
// This panics...let app = Router::<()>::new() .route("/:colon", get(|| async {}));```
# Merging
When two routers are merged, v0.7 checks are disabled for route registrations on the resulting router if both of the two routers had them also disabled.
# Nesting
Each router needs to have the checks explicitly disabled. Nesting a router with the checks either enabled or disabled has no effect on the outer router.modified:axum/src/extract/matched_path.rs+2 added-2 removed
405 unmodified lines406 }407 408 #[crate::test]409 async fn matching_colon() {410- let app = Router::new().without_v07_checks().route(410+ let app = Router::new().route(411 "/:foo",412 get(|path: MatchedPath| async move { path.as_str().to_owned() }),413 );414 11 unmodified lines426 }427 428 #[crate::test]429 async fn matching_asterisk() {430- let app = Router::new().without_v07_checks().route(430+ let app = Router::new().route(431 "/*foo",432 get(|path: MatchedPath| async move { path.as_str().to_owned() }),433 );434 13 unmodified linesmodified:axum/src/routing/tests/mod.rs-16 removed
1310 unmodified lines1311 assert_eq!(res.text().await, "thing created");1312 }1313 1314 #[crate::test]1315-#[should_panic(1316- expected = "Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router."1317-)]1318-async fn colon_in_route() {1319- _ = Router::<()>::new().route("/:foo", get(|| async move {}));1320-}1321-1322-#[crate::test]1323-#[should_panic(1324- expected = "Path segments must not start with `*`. For wildcard capture, use `{*wildcard}`. If you meant to literally match a segment starting with an asterisk, call `without_v07_checks` on the router."1325-)]1326-async fn asterisk_in_route() {1327- _ = Router::<()>::new().route("/*foo", get(|| async move {}));1328-}1329-1330-#[crate::test]1315 async fn middleware_adding_body() {1316 let app = Router::new()1317 .route("/", get(()))1318 .layer(MapResponseLayer::new(|mut res: Response| -> Response {44 unmodified linesmodified:axum/src/routing/tests/nest.rs+22 added-10 removed
439 unmodified lines440 nested_route_test!(nest_5, nest = "/a/", route = "/a", expected = "/a/a");441 nested_route_test!(nest_6, nest = "/a/", route = "/a/", expected = "/a/a/");442 443 #[crate::test]444-#[should_panic(445- expected = "Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router."446-)]447-async fn colon_in_route() {448- _ = Router::<()>::new().nest("/:foo", Router::new());444+async fn colon_in_nested_route() {445+ let router = Router::<()>::new().nest(446+ "/:foo",447+ Router::new().route("/foo", get(|| async { "foo" })),448+ );449+450+ let client = TestClient::new(router);451+452+ let res = client.get("/:foo/foo").await;453+ let body = res.text().await;454+ assert_eq!(body, "foo");455 }456 457 #[crate::test]452-#[should_panic(453- expected = "Path segments must not start with `*`. For wildcard capture, use `{*wildcard}`. If you meant to literally match a segment starting with an asterisk, call `without_v07_checks` on the router."454-)]455-async fn asterisk_in_route() {456- _ = Router::<()>::new().nest("/*foo", Router::new());458+async fn asterisk_in_nested_route() {459+ let router = Router::<()>::new().nest(460+ "/*foo",461+ Router::new().route("/foo", get(|| async { "foo" })),462+ );463+464+ let client = TestClient::new(router);465+466+ let res = client.get("/*foo/foo").await;467+ let body = res.text().await;468+ assert_eq!(body, "foo");469 }470 471 #[crate::test]472 async fn nesting_router_with_fallback() {94 unmodified linesmodified:axum/src/routing/mod.rs-7 removed
178 unmodified lines179 },180 }181 }182 183- #[doc = include_str!("../docs/routing/without_v07_checks.md")]184- pub fn without_v07_checks(self) -> Self {185- tap_inner!(self, mut this => {186- this.path_router.without_v07_checks();187- })188- }189-183 #[doc = include_str!("../docs/routing/route.md")]184 #[track_caller]185 pub fn route(self, path: &str, method_router: MethodRouter<S>) -> Self {186 tap_inner!(self, mut this => {647 unmodified linesmodified:axum/src/routing/path_router.rs+8 added-60 removed
14 unmodified lines15 16 pub(super) struct PathRouter<S> {17 routes: Vec<Endpoint<S>>,18 node: Arc<Node>,19- v7_checks: bool,19 }20 22-fn validate_path(v7_checks: bool, path: &str) -> Result<(), &'static str> {21+fn validate_path(path: &str) -> Result<(), &'static str> {22 if path.is_empty() {23 return Err("Paths must start with a `/`. Use \"/\" for root routes");24 } else if !path.starts_with('/') {25 return Err("Paths must start with a `/`");26 }27 29- if v7_checks {30- validate_v07_paths(path)?;31- }32-28 Ok(())29 }30 36-fn validate_v07_paths(path: &str) -> Result<(), &'static str> {37- path.split('/')38- .find_map(|segment| {39- if segment.starts_with(':') {40- Some(Err(41- "Path segments must not start with `:`. For capture groups, use \42- `{capture}`. If you meant to literally match a segment starting with \43- a colon, call `without_v07_checks` on the router.",44- ))45- } else if segment.starts_with('*') {46- Some(Err(47- "Path segments must not start with `*`. For wildcard capture, use \48- `{*wildcard}`. If you meant to literally match a segment starting with \49- an asterisk, call `without_v07_checks` on the router.",50- ))51- } else {52- None53- }54- })55- .unwrap_or(Ok(()))56-}57-31 impl<S> PathRouter<S>32 where33 S: Clone + Send + Sync + 'static,34 {62- pub(super) fn without_v07_checks(&mut self) {63- self.v7_checks = false;64- }65-35 pub(super) fn route(36 &mut self,37 path: &str,38 method_router: MethodRouter<S>,39 ) -> Result<(), Cow<'static, str>> {71- validate_path(self.v7_checks, path)?;40+ validate_path(path)?;41 42 if let Some((route_id, Endpoint::MethodRouter(prev_method_router))) = self43 .node44 .path_to_route_id45 unmodified lines90 &mut self,91 path: &str,92 endpoint: Endpoint<S>,93 ) -> Result<(), Cow<'static, str>> {125- validate_path(self.v7_checks, path)?;94+ validate_path(path)?;95 96 self.new_route(path, endpoint)?;97 98 Ok(())13 unmodified lines112 Ok(())113 }114 115 pub(super) fn merge(&mut self, other: Self) -> Result<(), Cow<'static, str>> {147- let Self {148- routes,149- node,150- v7_checks,151- } = other;116+ let Self { routes, node } = other;117 153- // If either of the two did not allow paths starting with `:` or `*`, do not allow them for the merged router either.154- self.v7_checks |= v7_checks;155-118 for (id, route) in routes.into_iter().enumerate() {119 let route_id = RouteId(id);120 let path = node121 .route_id_to_path13 unmodified lines135 &mut self,136 path_to_nest_at: &str,137 router: Self,138 ) -> Result<(), Cow<'static, str>> {177- let prefix = validate_nest_path(self.v7_checks, path_to_nest_at)?;139+ let prefix = validate_nest_path(path_to_nest_at)?;140 179- let Self {180- routes,181- node,182- // Ignore the configuration of the nested router183- v7_checks: _,184- } = router;141+ let Self { routes, node } = router;142 143 for (id, endpoint) in routes.into_iter().enumerate() {144 let route_id = RouteId(id);145 let inner_path = node29 unmodified lines175 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,176 T::Response: IntoResponse,177 T::Future: Send + 'static,178 {222- let path = validate_nest_path(self.v7_checks, path_to_nest_at)?;179+ let path = validate_nest_path(path_to_nest_at)?;180 let prefix = path;181 182 let path = if path.ends_with('/') {183 format!("{path}{{*{NEST_TAIL_PARAM}}}")37 unmodified lines221 222 Self {223 routes,224 node: self.node,268- v7_checks: self.v7_checks,225 }226 }227 228 #[track_caller]20 unmodified lines249 250 Self {251 routes,252 node: self.node,297- v7_checks: self.v7_checks,253 }254 }255 256 pub(super) fn has_routes(&self) -> bool {14 unmodified lines271 272 PathRouter {273 routes,274 node: self.node,320- v7_checks: self.v7_checks,275 }276 }277 278 #[allow(clippy::result_large_err)]51 unmodified lines330 fn default() -> Self {331 Self {332 routes: Default::default(),333 node: Default::default(),380- v7_checks: true,334 }335 }336 }337 10 unmodified lines348 fn clone(&self) -> Self {349 Self {350 routes: self.routes.clone(),351 node: self.node.clone(),399- v7_checks: self.v7_checks,352 }353 }354 }355 37 unmodified lines393 .finish()394 }395 }396 445-fn validate_nest_path(v7_checks: bool, path: &str) -> Result<&str, &'static str> {397+fn validate_nest_path(path: &str) -> Result<&str, &'static str> {398 if !path.starts_with('/') {399 return Err("Nesting paths must start with a `/`.");400 }401 if path.len() < 2 {5 unmodified lines407 }) {408 return Err("Invalid route: nested routes cannot contain wildcards (*)");409 }410 459- if v7_checks {460- validate_v07_paths(path)?;461- }462-411 Ok(path)412 }413 414 pub(crate) fn path_for_nested_route<'a>(prefix: &'a str, path: &'a str) -> Cow<'a, str> {11 unmodified lines