axum-extra: reject trailing content in JsonDeserializer (#3916)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Shuvro Roy · committed by GitHub · parent f660aa9 · Browse files · 2 files·+60 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+60 added−2 removed
- other:+60 added−2 removed
Provenance
- Commit
90f299c- Tree
91d8dfc- Author
Shuvro Roy <shuvro.nsu.cse@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
f660aa9
2 files changed+60 added−2 removed
modified:axum-extra/src/extract/json_deserializer.rs+57 added-2 removed
108 unmodified lines109 {110 /// Deserialize the request body into the target type.111 /// See [`JsonDeserializer`] for more details.112 pub fn deserialize(&'a self) -> Result<T, JsonDeserializerRejection> {113- let deserializer = &mut serde_json::Deserializer::from_slice(&self.bytes);113+ let mut deserializer = serde_json::Deserializer::from_slice(&self.bytes);114 115- let value = match serde_path_to_error::deserialize(deserializer) {115+ let value = match serde_path_to_error::deserialize(&mut deserializer) {116 Ok(value) => value,117 Err(err) => {118 let rejection = match err.inner().classify() {119 serde_json::error::Category::Data => JsonDataError::from_err(err).into(),13 unmodified lines133 return Err(rejection);134 }135 };136 137+ deserializer.end().map_err(JsonSyntaxError::from_err)?;138+139 Ok(value)140 }141 }142 101 unmodified lines244 assert_eq!(body, "bar");245 }246 247 #[tokio::test]248+ async fn deserialize_body_with_trailing_whitespace() {249+ #[derive(Deserialize)]250+ struct Input<'a> {251+ foo: &'a str,252+ }253+254+ async fn handler(deserializer: JsonDeserializer<Input<'_>>) -> Response {255+ match deserializer.deserialize() {256+ Ok(input) => input.foo.to_owned().into_response(),257+ Err(err) => err.into_response(),258+ }259+ }260+261+ let app = Router::new().route("/", post(handler));262+ let client = TestClient::new(app);263+264+ for body in [r#"{"foo":"bar"}"#, "{\"foo\":\"bar\"} \t\r\n"] {265+ let res = client266+ .post("/")267+ .header("content-type", "application/json")268+ .body(body)269+ .await;270+271+ assert_eq!(res.status(), StatusCode::OK);272+ assert_eq!(res.text().await, "bar");273+ }274+ }275+276+ #[tokio::test]277+ async fn deserialize_body_rejects_trailing_content() {278+ async fn handler(deserializer: JsonDeserializer<Value>) -> Response {279+ match deserializer.deserialize() {280+ Err(JsonDeserializerRejection::JsonSyntaxError(err)) => err.into_response(),281+ result => panic!("expected a JSON syntax error, got {result:?}"),282+ }283+ }284+285+ let app = Router::new().route("/", post(handler));286+ let client = TestClient::new(app);287+288+ for body in [r#"{"x":1} garbage"#, r#"{"x":1} {"x":2}"#] {289+ let res = client290+ .post("/")291+ .header("content-type", "application/json")292+ .body(body)293+ .await;294+295+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);296+ assert!(res.text().await.contains("trailing characters"));297+ }298+ }299+300+ #[tokio::test]301 async fn deserialize_body_escaped_to_cow() {302 #[derive(Debug, Deserialize)]303 struct Input<'a> {304 #[serde(borrow)]173 unmodified linesmodified:axum-extra/CHANGELOG.md+3 added
5 unmodified lines6 and this project adheres to [Semantic Versioning].7 8 # Unreleased9 10+- **fixed:** `JsonDeserializer` rejects trailing non-whitespace after a JSON11+ value ([#3916])12 - **breaking:** Remove the deprecated `Host`, `Scheme` and `OptionalPath`13 extractors ([#3599])14 - Also remove `HostRejection` which only had `FailedToResolveHost`15 previously used in the `Host` extractor ([#3636])11 unmodified lines27 - **added:** Add `RouterExt::typed_query` ([#3801])28 - **fixed:** Escape multipart `Content-Disposition` parameters and reject29 newlines in field names and filenames ([#3776])30 31+[#3916]: https://github.com/tokio-rs/axum/pull/391632 [#3599]: https://github.com/tokio-rs/axum/pull/359933 [#3586]: https://github.com/tokio-rs/axum/pull/358634 [#3801]: https://github.com/tokio-rs/axum/pull/380135 [#3776]: https://github.com/tokio-rs/axum/pull/3776553 unmodified lines