Skip to content
Myr

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

6 files+32 added−138 removed

deleted:axum/src/docs/routing/without_v07_checks.md-43 removed
modified:axum/src/extract/matched_path.rs+2 added-2 removed
405 unmodified lines
406 }407408 #[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 lines
426 }427428 #[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 lines
modified:axum/src/routing/tests/mod.rs-16 removed
1310 unmodified lines
1311 assert_eq!(res.text().await, "thing created");1312}13131314#[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)]1318async fn colon_in_route() {1319 _ = Router::<()>::new().route("/:foo", get(|| async move {}));1320}13211322#[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)]1326async fn asterisk_in_route() {1327 _ = Router::<()>::new().route("/*foo", get(|| async move {}));1328}13291330#[crate::test]1315async fn middleware_adding_body() {1316 let app = Router::new()1317 .route("/", get(()))1318 .layer(MapResponseLayer::new(|mut res: Response| -> Response {
44 unmodified lines
modified:axum/src/routing/tests/nest.rs+22 added-10 removed
439 unmodified lines
440nested_route_test!(nest_5, nest = "/a/", route = "/a", expected = "/a/a");441nested_route_test!(nest_6, nest = "/a/", route = "/a/", expected = "/a/a/");442443#[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)]447async fn colon_in_route() {448 _ = Router::<()>::new().nest("/:foo", Router::new());444async fn colon_in_nested_route() {445 let router = Router::<()>::new().nest(446 "/:foo",447 Router::new().route("/foo", get(|| async { "foo" })),448 );449450 let client = TestClient::new(router);451452 let res = client.get("/:foo/foo").await;453 let body = res.text().await;454 assert_eq!(body, "foo");455}456457#[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)]455async fn asterisk_in_route() {456 _ = Router::<()>::new().nest("/*foo", Router::new());458async fn asterisk_in_nested_route() {459 let router = Router::<()>::new().nest(460 "/*foo",461 Router::new().route("/foo", get(|| async { "foo" })),462 );463464 let client = TestClient::new(router);465466 let res = client.get("/*foo/foo").await;467 let body = res.text().await;468 assert_eq!(body, "foo");469}470471#[crate::test]472async fn nesting_router_with_fallback() {
94 unmodified lines
modified:axum/src/routing/mod.rs-7 removed
178 unmodified lines
179 },180 }181 }182183 #[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 }189183 #[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 lines
modified:axum/src/routing/path_router.rs+8 added-60 removed
14 unmodified lines
1516pub(super) struct PathRouter<S> {17 routes: Vec<Endpoint<S>>,18 node: Arc<Node>,19 v7_checks: bool,19}2022fn validate_path(v7_checks: bool, path: &str) -> Result<(), &'static str> {21fn 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 }2729 if v7_checks {30 validate_v07_paths(path)?;31 }3228 Ok(())29}3036fn 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}5731impl<S> PathRouter<S>32where33 S: Clone + Send + Sync + 'static,34{62 pub(super) fn without_v07_checks(&mut self) {63 self.v7_checks = false;64 }6535 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)?;4142 if let Some((route_id, Endpoint::MethodRouter(prev_method_router))) = self43 .node44 .path_to_route_id
45 unmodified lines
90 &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)?;9596 self.new_route(path, endpoint)?;9798 Ok(())
13 unmodified lines
112 Ok(())113 }114115 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;117153 // 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;155118 for (id, route) in routes.into_iter().enumerate() {119 let route_id = RouteId(id);120 let path = node121 .route_id_to_path
13 unmodified lines
135 &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)?;140179 let Self {180 routes,181 node,182 // Ignore the configuration of the nested router183 v7_checks: _,184 } = router;141 let Self { routes, node } = router;142143 for (id, endpoint) in routes.into_iter().enumerate() {144 let route_id = RouteId(id);145 let inner_path = node
29 unmodified lines
175 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;181182 let path = if path.ends_with('/') {183 format!("{path}{{*{NEST_TAIL_PARAM}}}")
37 unmodified lines
221222 Self {223 routes,224 node: self.node,268 v7_checks: self.v7_checks,225 }226 }227228 #[track_caller]
20 unmodified lines
249250 Self {251 routes,252 node: self.node,297 v7_checks: self.v7_checks,253 }254 }255256 pub(super) fn has_routes(&self) -> bool {
14 unmodified lines
271272 PathRouter {273 routes,274 node: self.node,320 v7_checks: self.v7_checks,275 }276 }277278 #[allow(clippy::result_large_err)]
51 unmodified lines
330 fn default() -> Self {331 Self {332 routes: Default::default(),333 node: Default::default(),380 v7_checks: true,334 }335 }336}337
10 unmodified lines
348 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 lines
393 .finish()394 }395}396445fn validate_nest_path(v7_checks: bool, path: &str) -> Result<&str, &'static str> {397fn 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 lines
407 }) {408 return Err("Invalid route: nested routes cannot contain wildcards (*)");409 }410459 if v7_checks {460 validate_v07_paths(path)?;461 }462411 Ok(path)412}413414pub(crate) fn path_for_nested_route<'a>(prefix: &'a str, path: &'a str) -> Cow<'a, str> {
11 unmodified lines