From e2eb92b8ed59f88b1c638a16bdf8ef386d920f02 Mon Sep 17 00:00:00 2001 From: gnieto Date: Sat, 8 May 2021 18:12:56 +0200 Subject: [PATCH] Prevent panic on requests with invalid URIs When `try_into_http_request` was used with an invalid base URI the code was panicking. Acording to `http::request::Builder` documentation, `headers_mut` returns `None` if the builder contains errors, which was the case when an invalid URI was provided. The new version only sets the additional headers in case that there are no errors on the builder, preventing the panic. The conversion will return an error when the builder is consumed on `body`. --- .../ruma-api-macros/src/api/request/outgoing.rs | 8 +++----- crates/ruma-api/CHANGELOG.md | 4 ++++ crates/ruma-api/tests/conversions.rs | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/ruma-api-macros/src/api/request/outgoing.rs b/crates/ruma-api-macros/src/api/request/outgoing.rs index f629b68a..380906b3 100644 --- a/crates/ruma-api-macros/src/api/request/outgoing.rs +++ b/crates/ruma-api-macros/src/api/request/outgoing.rs @@ -226,11 +226,9 @@ impl Request { "application/json", ); - let mut req_headers = req_builder - .headers_mut() - .expect("`http::RequestBuilder` is in unusable state"); - - #header_kvs + if let Some(mut req_headers) = req_builder.headers_mut() { + #header_kvs + } let http_request = req_builder.body(#request_body)?; diff --git a/crates/ruma-api/CHANGELOG.md b/crates/ruma-api/CHANGELOG.md index 7d0b6286..b598b4e8 100644 --- a/crates/ruma-api/CHANGELOG.md +++ b/crates/ruma-api/CHANGELOG.md @@ -21,6 +21,10 @@ Improvements: * Add a new `MatrixError` type to the `error` module that consists of a HTTP status code and JSON `body` and is the new default error type for `ruma_api!` +Bug fixes: + +* Prevent panic when building requests with an invalid URI + # 0.16.1 Bug fixes: diff --git a/crates/ruma-api/tests/conversions.rs b/crates/ruma-api/tests/conversions.rs index fc21e0e2..2f9e03e6 100644 --- a/crates/ruma-api/tests/conversions.rs +++ b/crates/ruma-api/tests/conversions.rs @@ -62,6 +62,21 @@ fn request_serde() { assert_eq!(req.user, req2.user); } +#[test] +fn invalid_uri_should_not_panic() { + let req = Request { + hello: "hi".to_owned(), + world: "test".to_owned(), + q1: "query_param_special_chars %/&@!".to_owned(), + q2: 55, + bar: "barVal".to_owned(), + user: user_id!("@bazme:ruma.io"), + }; + + let result = req.clone().try_into_http_request::>("invalid uri", SendAccessToken::None); + assert!(result.is_err()); +} + #[test] fn request_with_user_id_serde() { let req = Request {