From 9977623c0e9b68e3fd3323204a3c7c0a2a2a1fb7 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 15 Oct 2023 22:35:34 -0300 Subject: [PATCH] fix: content type required flag --- actix-web/CHANGES.md | 4 ++++ actix-web/src/types/json.rs | 38 +++++++++++++++++++++++++++++-------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/actix-web/CHANGES.md b/actix-web/CHANGES.md index 6ed97b671..109554436 100644 --- a/actix-web/CHANGES.md +++ b/actix-web/CHANGES.md @@ -2,6 +2,10 @@ ## Unreleased +### Fixed + +- Fix content type required validation when set to false. [#3162] + ## 4.4.0 ### Added diff --git a/actix-web/src/types/json.rs b/actix-web/src/types/json.rs index 59c95da4c..8813fa050 100644 --- a/actix-web/src/types/json.rs +++ b/actix-web/src/types/json.rs @@ -328,14 +328,17 @@ impl JsonBody { ctype_required: bool, ) -> Self { // check content-type - let can_parse_json = if let Ok(Some(mime)) = req.mime_type() { - mime.subtype() == mime::JSON - || mime.suffix() == Some(mime::JSON) - || ctype_fn.map_or(false, |predicate| predicate(mime)) - } else { - // if `ctype_required` is false, assume payload is - // json even when content-type header is missing - !ctype_required + let can_parse_json = match (ctype_required, req.mime_type()) { + (true, Ok(Some(mime))) => { + mime.subtype() == mime::JSON + || mime.suffix() == Some(mime::JSON) + || ctype_fn.map_or(false, |predicate| predicate(mime)) + } + (_, _) => { + // if `ctype_required` is false, assume payload is + // json even when content-type header is missing + !ctype_required + } }; if !can_parse_json { @@ -725,6 +728,25 @@ mod tests { assert!(s.is_ok()) } + #[actix_rt::test] + async fn test_json_ignoring_content_type() { + let (req, mut pl) = TestRequest::default() + .insert_header(( + header::CONTENT_LENGTH, + header::HeaderValue::from_static("16"), + )) + .insert_header(( + header::CONTENT_TYPE, + header::HeaderValue::from_static("invalid/value"), + )) + .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) + .app_data(JsonConfig::default().content_type_required(false)) + .to_http_parts(); + + let s = Json::::from_request(&req, &mut pl).await; + assert!(s.is_ok()) + } + #[actix_rt::test] async fn test_with_config_in_data_wrapper() { let (req, mut pl) = TestRequest::default()