feat: add InnerPath extractor (#3856)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dan Bondarenko · committed by GitHub · parent 7c3c678 · Browse files · 9 files·+832 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: David Mládek <david.mladek.cz@gmail.com>
Diff stats
9 files+832 added−35 removed
- tests:+2 added−2 removed
- other:+830 added−33 removed
Provenance
- Commit
bc8d491- Tree
18b3b57- Author
Dan Bondarenko <danxfer@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
7c3c678
9 files changed+832 added−35 removed
modified:axum/src/docs/routing/nest.md+5 added-1 removed
34 unmodified lines3536373839394041424315 unmodified lines59606162636465666768123 unmodified linesExpand all19219319419519619719834 unmodified linesURI.
# Captures from outer routes
Take care when using `nest` together with dynamic routes as nesting alsoTake care when using `nest` together with dynamic routes as the [`Path`] extractor alsocaptures from the outer routes:
```rustuse axum::{15 unmodified lineslet app = Router::new().nest("/{version}/api", users_api);# let _: Router = app;```
Use the [`InnerPath`] extractor if you only need the captured parameters from the inner router.
# Differences from wildcard routes
Nested routes are similar to wildcard routes. The difference is thatwildcard routes still see the whole URI whereas nested routes will have123 unmodified linesExpand all- If the route contains a wildcard (`*`).- If `path` is empty.
[`OriginalUri`]: crate::extract::OriginalUri[`InnerPath`]: crate::extract::InnerPath[`Path`]: crate::extract::Path[fallbacks]: Router::fallbackadded:axum/src/extract/path/inner_path.rs+722 added
1+use crate::extract::path::{2+ serialize_path_params, ErrorKind, FailedToDeserializePathParams, PathDeserializationError,3+};4+use crate::extract::rejection::{InnerPathRejection, MissingPathParams};5+use crate::extract::FromRequestParts;6+use crate::routing::url_params::UrlParams;7+use crate::util::PercentDecodedStr;8+use axum_core::extract::OptionalFromRequestParts;9+use axum_core::RequestPartsExt;10+use http::request::Parts;11+use serde_core::de::DeserializeOwned;12+use std::sync::Arc;13+14+/// Extractor that will get captures from the path of the innermost router15+/// and parse them using [`serde`].16+///17+/// Any percent encoded parameters will be automatically decoded. The decoded18+/// parameters must be valid UTF-8, otherwise `InnerPath` will fail and return a `40019+/// Bad Request` response.20+///21+/// # `InnerPath` vs [`Path`]22+/// [`Path`] gives you every capture in the request path, including those matched by enclosing23+/// [`nest`] calls. `InnerPath` gives you only the ones from the route the innermost router24+/// matched. If the router isn't nested, or is nested only at static paths, `InnerPath` and [`Path`] see25+/// exactly the same captures.26+///27+/// # `Option<InnerPath<T>>` behavior28+///29+/// You can use `Option<InnerPath<T>>` as an extractor to allow the same handler to30+/// be used in a route with parameters that deserialize to `T`, and another31+/// route with no parameters at all.32+///33+/// # Example34+///35+/// These examples assume the `serde` feature of the [`uuid`] crate is enabled.36+///37+/// One `InnerPath` can extract multiple captures. It is not necessary (and does38+/// not work) to give a handler more than one `InnerPath` argument.39+///40+/// [`uuid`]: https://crates.io/crates/uuid41+///42+/// ```rust,no_run43+/// use axum::{44+/// extract::InnerPath,45+/// routing::get,46+/// Router,47+/// };48+/// use uuid::Uuid;49+///50+/// async fn user_info(InnerPath(user_id): InnerPath<Uuid>) {51+/// // `user_id` is from the `{user_id}` capture,52+/// // while `{tenant_id}` from the outer router isn't included,53+/// // so this handler works no matter what it's nested under.54+/// }55+///56+/// let api = Router::new().route("/users/{user_id}", get(user_info));57+/// let app = Router::new().nest("/tenants/{tenant_id}", api);58+/// # let _: Router = app;59+/// ```60+///61+/// Captured parameters also can be deserialized into any type that implements62+/// [`serde::Deserialize`]. This includes tuples and structs:63+///64+/// ```rust,no_run65+/// use axum::{66+/// extract::InnerPath,67+/// routing::get,68+/// Router,69+/// };70+/// use serde::Deserialize;71+/// use uuid::Uuid;72+///73+/// #[derive(Deserialize)]74+/// struct Params {75+/// user_id: Uuid,76+/// team_id: Uuid,77+/// }78+///79+/// async fn users_teams_show(80+/// InnerPath(Params { user_id, team_id }): InnerPath<Params>,81+/// ) {82+/// // Capture parameters will be matched by struct field names83+/// }84+///85+/// async fn users_teams_create(86+/// InnerPath((user_id, team_id)): InnerPath<(String, String)>,87+/// ) {88+/// // When using tuples captures will be matched by their position in the route89+/// }90+///91+/// let api = Router::new().route(92+/// "/users/{user_id}/team/{team_id}",93+/// get(users_teams_show).post(users_teams_create)94+/// );95+/// let app = Router::new().nest("/tenants/{tenant_id}", api);96+/// # let _: Router = app;97+/// ```98+///99+/// If you wish to capture all inner path parameters you can use `HashMap` or `Vec`:100+///101+/// ```rust,no_run102+/// use axum::{103+/// extract::InnerPath,104+/// routing::get,105+/// Router,106+/// };107+/// use std::collections::HashMap;108+///109+/// async fn params_map(110+/// InnerPath(params): InnerPath<HashMap<String, String>>,111+/// ) {112+/// // `params` contains keys "user_id" and "team_id"113+/// }114+///115+/// async fn params_vec(116+/// InnerPath(params): InnerPath<Vec<(String, String)>>,117+/// ) {118+/// // `params` contains one tuple for `user_id` and one for `team_id`119+/// }120+///121+/// let api = Router::new()122+/// .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec));123+/// let app = Router::new().nest("/tenants/{tenant_id}", api);124+/// # let _: Router = app;125+/// ```126+///127+/// # Providing detailed rejection output128+///129+/// If the URI cannot be deserialized into the target type the request will be rejected and an130+/// error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error.131+///132+/// [`serde`]: https://crates.io/crates/serde133+/// [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html134+/// [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs135+/// [`Path`]: crate::extract::Path136+/// [`nest`]: crate::routing::Router::nest137+#[derive(Debug)]138+pub struct InnerPath<T>(pub T);139+140+axum_core::__impl_deref!(InnerPath);141+142+impl<T, S> FromRequestParts<S> for InnerPath<T>143+where144+ T: DeserializeOwned + Send,145+ S: Send + Sync,146+{147+ type Rejection = InnerPathRejection;148+149+ async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {150+ get_inner_params(parts)151+ .and_then(serialize_path_params)152+ .map(Self)153+ }154+}155+156+impl<T, S> OptionalFromRequestParts<S> for InnerPath<T>157+where158+ T: DeserializeOwned + Send + 'static,159+ S: Send + Sync,160+{161+ type Rejection = InnerPathRejection;162+163+ async fn from_request_parts(164+ parts: &mut Parts,165+ _state: &S,166+ ) -> Result<Option<Self>, Self::Rejection> {167+ match parts.extract::<Self>().await {168+ Ok(Self(params)) => Ok(Some(Self(params))),169+ Err(InnerPathRejection::FailedToDeserializePathParams(e))170+ if e.kind().is_zero_params() =>171+ {172+ Ok(None)173+ }174+ Err(e) => Err(e),175+ }176+ }177+}178+179+fn get_inner_params(parts: &Parts) -> Result<&[(Arc<str>, PercentDecodedStr)], InnerPathRejection> {180+ let url_params = parts181+ .extensions182+ .get::<UrlParams>()183+ .ok_or(MissingPathParams)?;184+185+ match url_params {186+ UrlParams::Params {187+ params,188+ inner_start,189+ } => {190+ let inner_params = params191+ .get(*inner_start..)192+ .expect("Mismatch between url params and count of captures. This is bug in axum. Please file an issue.");193+194+ Ok(inner_params)195+ }196+ UrlParams::InvalidUtf8InPathParam { key } => {197+ let error = PathDeserializationError {198+ kind: ErrorKind::InvalidUtf8InPathParam {199+ key: key.to_string(),200+ },201+ };202+ Err(InnerPathRejection::from(FailedToDeserializePathParams(203+ error,204+ )))205+ }206+ }207+}208+209+#[cfg(test)]210+mod tests {211+ use super::*;212+ use crate::{213+ extract::{Path, Request},214+ middleware::{from_fn, Next},215+ routing::get,216+ test_helpers::*,217+ Router,218+ };219+ use axum_core::response::Response;220+ use http::StatusCode;221+ use std::collections::HashMap;222+223+ type Params = Vec<(String, String)>;224+225+ fn params(pairs: &[(&str, &str)]) -> Params {226+ pairs227+ .iter()228+ .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))229+ .collect()230+ }231+232+ #[crate::test]233+ async fn without_nesting_matches_path() {234+ let app = Router::new().route(235+ "/users/{user_id}/team/{team_id}",236+ get(237+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {238+ let expected = params(&[("user_id", "42"), ("team_id", "1337")]);239+ assert_eq!(all, expected);240+ assert_eq!(inner, expected);241+ assert_eq!(inner, all);242+ "teams#show"243+ },244+ ),245+ );246+ let res = TestClient::new(app).get("/users/42/team/1337").await;247+248+ assert_eq!(res.status(), StatusCode::OK);249+ assert_eq!(res.text().await, "teams#show");250+ }251+252+ #[crate::test]253+ async fn static_nest_prefix_contributes_nothing() {254+ let app = Router::new().nest(255+ "/api",256+ Router::new().route(257+ "/users/{user_id}",258+ get(259+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {260+ let expected = params(&[("user_id", "42")]);261+ assert_eq!(all, expected);262+ assert_eq!(inner, expected);263+ assert_eq!(inner, all);264+ "users#show"265+ },266+ ),267+ ),268+ );269+ let res = TestClient::new(app).get("/api/users/42").await;270+271+ assert_eq!(res.status(), StatusCode::OK);272+ assert_eq!(res.text().await, "users#show");273+ }274+275+ #[crate::test]276+ async fn dynamic_nest_prefix_is_excluded() {277+ let app = Router::new().nest(278+ "/org/{org}",279+ Router::new().route(280+ "/team/{team_id}",281+ get(282+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {283+ assert_eq!(all, params(&[("org", "acme"), ("team_id", "1337")]));284+ assert_eq!(inner, params(&[("team_id", "1337")]));285+ "teams#show"286+ },287+ ),288+ ),289+ );290+ let res = TestClient::new(app).get("/org/acme/team/1337").await;291+292+ assert_eq!(res.status(), StatusCode::OK);293+ assert_eq!(res.text().await, "teams#show");294+ }295+296+ #[crate::test]297+ async fn nesting_mixing_static_and_dynamic_levels() {298+ let app = Router::new().nest(299+ "/api",300+ Router::new().nest(301+ "/{version}",302+ Router::new().nest(303+ "/admin",304+ Router::new().route(305+ "/{id}",306+ get(307+ |Path(all): Path<Params>,308+ InnerPath(inner): InnerPath<Params>| async move {309+ assert_eq!(all, params(&[("version", "v2"), ("id", "42")]));310+ assert_eq!(inner, params(&[("id", "42")]));311+ "admin#show"312+ },313+ ),314+ ),315+ ),316+ ),317+ );318+ let res = TestClient::new(app).get("/api/v2/admin/42").await;319+320+ assert_eq!(res.status(), StatusCode::OK);321+ assert_eq!(res.text().await, "admin#show");322+ }323+324+ #[crate::test]325+ async fn offset_sums_captures_across_levels() {326+ let app = Router::new().nest(327+ "/{prefix_one}",328+ Router::new().nest(329+ "/{prefix_two}/{prefix_three}",330+ Router::new().nest(331+ "/x/{prefix_four}",332+ Router::new().route(333+ "/{leaf_one}/{leaf_two}",334+ get(335+ |Path(all): Path<Params>,336+ InnerPath(inner): InnerPath<Params>| async move {337+ assert_eq!(338+ all,339+ params(&[340+ ("prefix_one", "1"),341+ ("prefix_two", "2"),342+ ("prefix_three", "3"),343+ ("prefix_four", "4"),344+ ("leaf_one", "5"),345+ ("leaf_two", "6"),346+ ])347+ );348+ assert_eq!(349+ inner,350+ params(&[("leaf_one", "5"), ("leaf_two", "6")])351+ );352+ "leaf"353+ },354+ ),355+ ),356+ ),357+ ),358+ );359+ let res = TestClient::new(app).get("/1/2/3/x/4/5/6").await;360+361+ assert_eq!(res.status(), StatusCode::OK);362+ assert_eq!(res.text().await, "leaf");363+ }364+365+ // `#[crate::test]` generates extra tests where `nest` calls are converted to `nest_service`.366+ // This test mixes `nest` and `nest_service` at different levels.367+ #[crate::test]368+ async fn outer_nest_with_inner_nest_service() {369+ let app = Router::new().nest(370+ "/api",371+ Router::new().nest_service(372+ "/{version}",373+ Router::new().route(374+ "/{id}",375+ get(376+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {377+ assert_eq!(all, params(&[("version", "v2"), ("id", "42")]));378+ assert_eq!(inner, params(&[("id", "42")]));379+ "items#show"380+ },381+ ),382+ ),383+ ),384+ );385+ let res = TestClient::new(app).get("/api/v2/42").await;386+387+ assert_eq!(res.status(), StatusCode::OK);388+ assert_eq!(res.text().await, "items#show");389+ }390+391+ #[crate::test]392+ async fn wildcard() {393+ let app = Router::new().nest(394+ "/org/{org}",395+ Router::new().route(396+ "/files/{*rest}",397+ get(398+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {399+ assert_eq!(all, params(&[("org", "acme"), ("rest", "a/b/c")]));400+ assert_eq!(inner, params(&[("rest", "a/b/c")]));401+ "files#show"402+ },403+ ),404+ ),405+ );406+ let res = TestClient::new(app).get("/org/acme/files/a/b/c").await;407+408+ assert_eq!(res.status(), StatusCode::OK);409+ assert_eq!(res.text().await, "files#show");410+ }411+412+ #[crate::test]413+ async fn inner_route_without_captures() {414+ let app = Router::new().nest(415+ "/org/{org}",416+ Router::new().route(417+ "/static",418+ get(419+ |Path(all): Path<Params>,420+ InnerPath(inner): InnerPath<Params>,421+ opt: Option<InnerPath<String>>| async move {422+ assert_eq!(all, params(&[("org", "acme")]));423+ assert_eq!(inner, params(&[]));424+ assert_eq!(opt.as_deref(), None);425+ "static"426+ },427+ ),428+ ),429+ );430+ let res = TestClient::new(app).get("/org/acme/static").await;431+432+ assert_eq!(res.status(), StatusCode::OK);433+ assert_eq!(res.text().await, "static");434+ }435+436+ #[crate::test]437+ async fn hash_map_only_contains_inner_captures() {438+ let app = Router::new().nest(439+ "/org/{org}",440+ Router::new().route(441+ "/team/{team_id}",442+ get(443+ |Path(all): Path<HashMap<String, String>>,444+ InnerPath(inner): InnerPath<HashMap<String, String>>| async move {445+ assert_eq!(446+ all,447+ HashMap::from_iter(params(&[("org", "acme"), ("team_id", "1337")]))448+ );449+ assert_eq!(inner, HashMap::from_iter(params(&[("team_id", "1337")])));450+ "teams#show"451+ },452+ ),453+ ),454+ );455+ let res = TestClient::new(app).get("/org/acme/team/1337").await;456+457+ assert_eq!(res.status(), StatusCode::OK);458+ assert_eq!(res.text().await, "teams#show");459+ }460+461+ #[crate::test]462+ async fn same_router_nested_at_prefixes_of_different_arity() {463+ fn resources() -> Router {464+ Router::new().route(465+ "/{id}/{version}",466+ get(|InnerPath(inner): InnerPath<Params>| async move {467+ assert_eq!(inner, params(&[("id", "thing"), ("version", "3")]));468+ "resources#show"469+ }),470+ )471+ }472+473+ let app = Router::new()474+ .nest("/global/{env}", resources())475+ .nest("/customer/{customer_id}/{env}", resources());476+ let client = TestClient::new(app);477+478+ let res = client.get("/global/prod/thing/3").await;479+ assert_eq!(res.status(), StatusCode::OK);480+ assert_eq!(res.text().await, "resources#show");481+482+ let res = client.get("/customer/acme/prod/thing/3").await;483+ assert_eq!(res.status(), StatusCode::OK);484+ assert_eq!(res.text().await, "resources#show");485+ }486+487+ #[crate::test]488+ async fn in_nested_fallback() {489+ let app = Router::new().nest(490+ "/org/{org}",491+ Router::new().fallback(get(492+ |Path(all): Path<Params>,493+ InnerPath(inner): InnerPath<Params>,494+ opt: Option<InnerPath<String>>| async move {495+ assert_eq!(all, params(&[("org", "acme")]));496+ assert_eq!(inner, params(&[]));497+ assert_eq!(opt.as_deref(), None);498+ "fallback"499+ },500+ )),501+ );502+ let res = TestClient::new(app).get("/org/acme/does-not-exist").await;503+504+ assert_eq!(res.status(), StatusCode::OK);505+ assert_eq!(res.text().await, "fallback");506+ }507+508+ #[crate::test]509+ async fn in_nested_middleware() {510+ async fn middleware(511+ Path(all): Path<Params>,512+ InnerPath(inner): InnerPath<Params>,513+ req: Request,514+ next: Next,515+ ) -> Response {516+ assert_eq!(all, params(&[("org", "acme"), ("team_id", "1337")]));517+ assert_eq!(inner, params(&[("team_id", "1337")]));518+ next.run(req).await519+ }520+521+ let app = Router::new().nest(522+ "/org/{org}",523+ Router::new()524+ .route("/team/{team_id}", get(|| async { "teams#show" }))525+ .layer(from_fn(middleware)),526+ );527+ let res = TestClient::new(app).get("/org/acme/team/1337").await;528+529+ assert_eq!(res.status(), StatusCode::OK);530+ assert_eq!(res.text().await, "teams#show");531+ }532+533+ #[crate::test]534+ async fn merge_preserves_per_route_offsets() {535+ let unnested = Router::new().route(536+ "/plain/{id}",537+ get(538+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {539+ let expected = params(&[("id", "0")]);540+ assert_eq!(all, expected);541+ assert_eq!(inner, expected);542+ "unnested"543+ },544+ ),545+ );546+547+ let nested_under_one_capture = Router::new().nest(548+ "/org/{org}",549+ Router::new().route(550+ "/{id}",551+ get(552+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {553+ assert_eq!(all, params(&[("org", "acme"), ("id", "1")]));554+ assert_eq!(inner, params(&[("id", "1")]));555+ "nested_under_one_capture"556+ },557+ ),558+ ),559+ );560+561+ let nested_under_two_captures = Router::new().nest(562+ "/team/{team}/{env}",563+ Router::new().route(564+ "/{id}",565+ get(566+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {567+ assert_eq!(568+ all,569+ params(&[("team", "blue"), ("env", "prod"), ("id", "2")])570+ );571+ assert_eq!(inner, params(&[("id", "2")]));572+ "nested_under_two_captures"573+ },574+ ),575+ ),576+ );577+578+ let client = TestClient::new(579+ unnested580+ .merge(nested_under_one_capture)581+ .merge(nested_under_two_captures),582+ );583+584+ let res = client.get("/plain/0").await;585+ assert_eq!(res.status(), StatusCode::OK);586+ assert_eq!(res.text().await, "unnested");587+588+ let res = client.get("/org/acme/1").await;589+ assert_eq!(res.status(), StatusCode::OK);590+ assert_eq!(res.text().await, "nested_under_one_capture");591+592+ let res = client.get("/team/blue/prod/2").await;593+ assert_eq!(res.status(), StatusCode::OK);594+ assert_eq!(res.text().await, "nested_under_two_captures");595+ }596+597+ #[crate::test]598+ async fn nesting_a_merged_router_composes_offsets() {599+ let already_nested = Router::new().nest(600+ "/org/{org}",601+ Router::new().route(602+ "/{id}",603+ get(604+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {605+ assert_eq!(all, params(&[("v", "2"), ("org", "acme"), ("id", "1")]));606+ assert_eq!(inner, params(&[("id", "1")]));607+ "already_nested"608+ },609+ ),610+ ),611+ );612+613+ let not_yet_nested = Router::new().route(614+ "/plain/{id}",615+ get(616+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {617+ assert_eq!(all, params(&[("v", "2"), ("id", "0")]));618+ assert_eq!(inner, params(&[("id", "0")]));619+ "not_yet_nested"620+ },621+ ),622+ );623+624+ let app = Router::new().nest("/api/{v}", already_nested.merge(not_yet_nested));625+ let client = TestClient::new(app);626+627+ let res = client.get("/api/2/org/acme/1").await;628+ assert_eq!(res.status(), StatusCode::OK);629+ assert_eq!(res.text().await, "already_nested");630+631+ let res = client.get("/api/2/plain/0").await;632+ assert_eq!(res.status(), StatusCode::OK);633+ assert_eq!(res.text().await, "not_yet_nested");634+ }635+636+ #[crate::test]637+ async fn percent_decoding_still_applies() {638+ let app = Router::new().nest(639+ "/org/{org}",640+ Router::new().route(641+ "/{name}",642+ get(643+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {644+ assert_eq!(all, params(&[("org", "acme"), ("name", "one two")]));645+ assert_eq!(inner, params(&[("name", "one two")]));646+ "names#show"647+ },648+ ),649+ ),650+ );651+ let res = TestClient::new(app).get("/org/acme/one%20two").await;652+653+ assert_eq!(res.status(), StatusCode::OK);654+ assert_eq!(res.text().await, "names#show");655+ }656+657+ #[crate::test]658+ async fn wrong_number_of_parameters_is_rejected() {659+ let app = Router::new().nest(660+ "/org/{org}",661+ Router::new().route("/{id}", get(|_: InnerPath<(u32, u32)>| async move {})),662+ );663+ let res = TestClient::new(app).get("/org/acme/42").await;664+665+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);666+ assert_eq!(667+ res.text().await,668+ "Wrong number of path arguments for `Path`. Expected 2 but got 1"669+ );670+ }671+672+ #[crate::test]673+ async fn duplicate_capture_names_across_levels() {674+ let app = Router::new().nest(675+ "/org/{id}",676+ Router::new().route(677+ "/{id}",678+ get(679+ |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {680+ assert_eq!(all, params(&[("id", "outer"), ("id", "inner")]));681+ assert_eq!(inner, params(&[("id", "inner")]));682+ "items#show"683+ },684+ ),685+ ),686+ );687+ let res = TestClient::new(app).get("/org/outer/inner").await;688+689+ assert_eq!(res.status(), StatusCode::OK);690+ assert_eq!(res.text().await, "items#show");691+ }692+693+ #[crate::test]694+ async fn invalid_utf8_in_nest_prefix_capture() {695+ let app = Router::new().nest(696+ "/org/{org}",697+ Router::new().route(698+ "/team/{team_id}",699+ get(|_: InnerPath<Params>| async move { "teams#show" }),700+ ),701+ );702+ let res = TestClient::new(app).get("/org/%FF/team/1337").await;703+704+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);705+ assert_eq!(res.text().await, "Invalid URL: Invalid UTF-8 in `org`");706+ }707+708+ #[crate::test]709+ async fn invalid_utf8_in_inner_capture() {710+ let app = Router::new().nest(711+ "/org/{org}",712+ Router::new().route(713+ "/team/{team_id}",714+ get(|_: InnerPath<Params>| async move { "teams#show" }),715+ ),716+ );717+ let res = TestClient::new(app).get("/org/acme/team/%FF").await;718+719+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);720+ assert_eq!(res.text().await, "Invalid URL: Invalid UTF-8 in `team_id`");721+ }722+}modified:axum/src/extract/path/mod.rs+49 added-28 removed
1 unmodified line2 //! [`serde`].3 4 mod de;5 6+pub(crate) mod inner_path;7+8 use crate::{9 extract::{rejection::*, FromRequestParts},10 routing::url_params::UrlParams,11 util::PercentDecodedStr,130 unmodified lines142 /// .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec));143 /// # let _: Router = app;144 /// ```145 ///146+/// # [`InnerPath`] vs `Path`147+/// `Path` gives you every capture in the request path, including those matched by enclosing148+/// [`nest`] calls. [`InnerPath`] gives you only the ones from the route the innermost router149+/// matched. If the router isn't nested, or is nested only at static paths, [`InnerPath`] and `Path` see150+/// exactly the same captures.151+///152 /// # Providing detailed rejection output153 ///154 /// If the URI cannot be deserialized into the target type the request will be rejected and an155 /// error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error.156 ///157 /// [`serde`]: https://crates.io/crates/serde158 /// [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html159 /// [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs160+/// [`InnerPath`]: crate::extract::InnerPath161+/// [`nest`]: crate::routing::Router::nest162 #[derive(Debug)]163 pub struct Path<T>(pub T);164 165 axum_core::__impl_deref!(Path);5 unmodified lines171 {172 type Rejection = PathRejection;173 174 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {165- // Extracted into separate fn so it's only compiled once for all T.166- fn get_params(parts: &Parts) -> Result<&[(Arc<str>, PercentDecodedStr)], PathRejection> {167- match parts.extensions.get::<UrlParams>() {168- Some(UrlParams::Params(params)) => Ok(params),169- Some(UrlParams::InvalidUtf8InPathParam { key }) => {170- let err = PathDeserializationError {171- kind: ErrorKind::InvalidUtf8InPathParam {172- key: key.to_string(),173- },174- };175- Err(FailedToDeserializePathParams(err).into())176- }177- None => Err(MissingPathParams.into()),178- }179- }180-181- fn failed_to_deserialize_path_params(err: PathDeserializationError) -> PathRejection {182- PathRejection::FailedToDeserializePathParams(FailedToDeserializePathParams(err))183- }184-185- match T::deserialize(de::PathDeserializer::new(get_params(parts)?)) {186- Ok(val) => Ok(Self(val)),187- Err(e) => Err(failed_to_deserialize_path_params(e)),188- }175+ get_params(parts).and_then(serialize_path_params).map(Self)176 }177 }178 179 impl<T, S> OptionalFromRequestParts<S> for Path<T>8 unmodified lines188 _state: &S,189 ) -> Result<Option<Self>, Self::Rejection> {190 match parts.extract::<Self>().await {191 Ok(Self(params)) => Ok(Some(Self(params))),205- Err(PathRejection::FailedToDeserializePathParams(e))206- if matches!(e.kind(), ErrorKind::WrongNumberOfParameters { got: 0, .. }) =>207- {192+ Err(PathRejection::FailedToDeserializePathParams(e)) if e.kind().is_zero_params() => {193 Ok(None)194 }195 Err(e) => Err(e),196 }141 unmodified lines338 /// Catch-all variant for errors that don't fit any other variant.339 Message(String),340 }341 342+impl ErrorKind {343+ fn is_zero_params(&self) -> bool {344+ matches!(&self, Self::WrongNumberOfParameters { got: 0, .. })345+ }346+}347+348 impl fmt::Display for ErrorKind {349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {350 match self {351 Self::Message(error) => error.fmt(f),159 unmodified lines511 pub fn from_request_extensions(512 extensions: &Extensions,513 ) -> Result<Self, RawPathParamsRejection> {514 match extensions.get::<UrlParams>() {524- Some(UrlParams::Params(params)) => Ok(Self(params.clone())),515+ Some(UrlParams::Params { params, .. }) => Ok(Self(params.clone())),516 Some(UrlParams::InvalidUtf8InPathParam { key }) => Err(InvalidUtf8InPathParam {517 key: Arc::clone(key),518 }519 .into()),72 unmodified lines592 (self.status(), body).into_response()593 }594 }595 596+fn get_params(parts: &Parts) -> Result<&[(Arc<str>, PercentDecodedStr)], PathRejection> {597+ let url_params = parts598+ .extensions599+ .get::<UrlParams>()600+ .ok_or(MissingPathParams)?;601+602+ match url_params {603+ UrlParams::Params { params, .. } => Ok(params),604+ UrlParams::InvalidUtf8InPathParam { key } => {605+ let error = PathDeserializationError {606+ kind: ErrorKind::InvalidUtf8InPathParam {607+ key: key.to_string(),608+ },609+ };610+ Err(PathRejection::from(FailedToDeserializePathParams(error)))611+ }612+ }613+}614+615+fn serialize_path_params<T, E>(params: &[(Arc<str>, PercentDecodedStr)]) -> Result<T, E>616+where617+ T: DeserializeOwned + Send,618+ E: From<FailedToDeserializePathParams>,619+{620+ let deserializer = de::PathDeserializer::new(params);621+ T::deserialize(deserializer)622+ .map_err(FailedToDeserializePathParams)623+ .map_err(E::from)624+}625+626 #[cfg(test)]627 mod tests {628 use super::*;629 use crate::{routing::get, test_helpers::*, Router};457 unmodified linesmodified:axum/src/extract/mod.rs+3 added
48 unmodified lines49 #[cfg(feature = "form")]50 #[doc(no_inline)]51 pub use crate::form::Form;52 53+#[doc(inline)]54+pub use self::path::inner_path::InnerPath;55+56 #[cfg(feature = "matched-path")]57 pub(crate) mod matched_path;58 59 #[cfg(feature = "matched-path")]53 unmodified linesmodified:axum/src/extract/rejection.rs+11 added
158 unmodified lines159 }160 }161 162 composite_rejection! {163+ /// Rejection used for [`InnerPath`](super::InnerPath).164+ ///165+ /// Contains one variant for each way the [`InnerPath`](super::InnerPath) extractor166+ /// can fail.167+ pub enum InnerPathRejection {168+ FailedToDeserializePathParams,169+ MissingPathParams,170+ }171+}172+173+composite_rejection! {174 /// Rejection used for [`RawPathParams`](super::RawPathParams).175 ///176 /// Contains one variant for each way the [`RawPathParams`](super::RawPathParams) extractor177 /// can fail.34 unmodified linesmodified:axum/src/routing/strip_prefix.rs+17 added
1+use crate::routing::url_params;2 use http::{Request, Uri};3 use std::{4 sync::Arc,5 task::{Context, Poll},5 unmodified lines11 #[derive(Clone)]12 pub(super) struct StripPrefix<S> {13 inner: S,14 prefix: Arc<str>,15+ captures_count: usize,16 }17 18 impl<S> StripPrefix<S> {19 pub(super) fn layer(prefix: &str) -> impl Layer<S, Service = Self> + Clone {20+ let captures_count = count_captures(prefix);21 let prefix = Arc::from(prefix);22 layer_fn(move |inner| Self {23 inner,24 prefix: Arc::clone(&prefix),25+ captures_count,26 })27 }28 }29 13 unmodified lines43 fn call(&mut self, mut req: Request<B>) -> Self::Future {44 if let Some(new_uri) = strip_prefix(req.uri(), &self.prefix) {45 *req.uri_mut() = new_uri;46 }47+ url_params::advance_inner_start(req.extensions_mut(), self.captures_count);48 self.inner.call(req)49 }50 }51 52+fn count_captures(path: &str) -> usize {53+ segments(path).filter_map(capture_prefix_suffix).count()54+}55+56 fn strip_prefix(uri: &Uri, prefix: &str) -> Option<Uri> {57 let path_and_query = uri.path_and_query()?;58 59 // Check whether the prefix matches the path and if so how long the matching prefix is.390 unmodified lines450 strip_prefix(&uri, &prefix);451 true452 }453 454+ #[test]455+ fn count_captures_counts_correctly() {456+ assert_eq!(count_captures("/index.html"), 0);457+ assert_eq!(count_captures("/api/v{version}"), 1);458+ assert_eq!(count_captures("/api/{version}/users/{id}"), 2);459+ assert_eq!(count_captures("/{{brackets}}/{version}/users/{id}"), 2);460+ }461+462 #[derive(Clone, Debug)]463 struct UriAndPrefix {464 uri: Uri,465 prefix: String,82 unmodified linesmodified:axum/src/routing/url_params.rs+23 added-4 removed
3 unmodified lines4 use std::sync::Arc;5 6 #[derive(Clone)]7 pub(crate) enum UrlParams {8- Params(Vec<(Arc<str>, PercentDecodedStr)>),9- InvalidUtf8InPathParam { key: Arc<str> },8+ Params {9+ params: Vec<(Arc<str>, PercentDecodedStr)>,10+ inner_start: usize,11+ },12+ InvalidUtf8InPathParam {13+ key: Arc<str>,14+ },15 }16 17 pub(super) fn insert_url_params(extensions: &mut Extensions, params: &Params<'_, '_>) {18 let current_params = extensions.get_mut();22 unmodified lines41 }42 (_, Err(invalid_key)) => {43 extensions.insert(UrlParams::InvalidUtf8InPathParam { key: invalid_key });44 }40- (Some(UrlParams::Params(current)), Ok(params)) => {45+ (46+ Some(UrlParams::Params {47+ params: current, ..48+ }),49+ Ok(params),50+ ) => {51 current.extend(params);52 }53 (None, Ok(params)) => {44- extensions.insert(UrlParams::Params(params));54+ extensions.insert(UrlParams::Params {55+ params,56+ inner_start: 0,57+ });58 }59 }60 }61+62+pub(super) fn advance_inner_start(extensions: &mut Extensions, count: usize) {63+ if let Some(UrlParams::Params { inner_start, .. }) = extensions.get_mut() {64+ *inner_start += count;65+ }66+}modified:axum-macros/tests/debug_handler/fail/argument_not_extractor.stderr+1 added-1 removed
8 unmodified lines9 = help: the following other types implement trait `FromRequestParts<S>`:10 `ConnectInfo<T>` implements `FromRequestParts<S>`11 `Extension<T>` implements `FromRequestParts<S>`12 `HeaderMap` implements `FromRequestParts<S>`13+ `InnerPath<T>` implements `FromRequestParts<S>`14 `MatchedPath` implements `FromRequestParts<S>`15 `Method` implements `FromRequestParts<S>`16 `OriginalUri` implements `FromRequestParts<S>`17 `Query<T>` implements `FromRequestParts<S>`17- `RawPathParams` implements `FromRequestParts<S>`18 and $N others19 = note: required for `bool` to implement `FromRequest<(), axum_core::extract::private::ViaParts>`20 note: required by a bound in `__axum_macros_check_handler_0_from_request_check`21 --> tests/debug_handler/fail/argument_not_extractor.rs:4:243 unmodified linesmodified:axum-macros/tests/from_request/fail/parts_extracting_body.stderr+1 added-1 removed
9 unmodified lines10 `ConnectInfo<T>` implements `FromRequestParts<S>`11 `Extension<T>` implements `FromRequestParts<S>`12 `Extractor` implements `FromRequestParts<S>`13 `HeaderMap` implements `FromRequestParts<S>`14+ `InnerPath<T>` implements `FromRequestParts<S>`15 `MatchedPath` implements `FromRequestParts<S>`16 `Method` implements `FromRequestParts<S>`17 `OriginalUri` implements `FromRequestParts<S>`17- `Query<T>` implements `FromRequestParts<S>`18 and $N others