From cf21df14f2e94dc16f4ffa7d2bb4e65d936b60fd Mon Sep 17 00:00:00 2001 From: Ali MJ Al-Nasrawy Date: Sat, 5 Jun 2021 20:29:00 +0300 Subject: [PATCH] `Path`: fix unsafe malformed string (#359) --- actix-router/CHANGES.md | 2 ++ actix-router/src/url.rs | 16 +++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/actix-router/CHANGES.md b/actix-router/CHANGES.md index 0e2537c5..8ed43b88 100644 --- a/actix-router/CHANGES.md +++ b/actix-router/CHANGES.md @@ -2,8 +2,10 @@ ## Unreleased - 2021-xx-xx * When matching URL parameters, `%25` is kept in the percent-encoded form - no longer decoded to `%`. [#357] +* Fixed a bug where the `Path` extractor returns unsafe malformed string due to malformed URL. [#359] [#357]: https://github.com/actix/actix-net/pull/357 +[#359]: https://github.com/actix/actix-net/pull/359 ## 0.2.7 - 2021-02-06 diff --git a/actix-router/src/url.rs b/actix-router/src/url.rs index d568e5af..130ac76f 100644 --- a/actix-router/src/url.rs +++ b/actix-router/src/url.rs @@ -170,11 +170,7 @@ impl Quoter { idx += 1; } - cloned.map(|data| { - // SAFETY: we get data from http::Uri, which does UTF-8 checks already - // this code only decodes valid pct encoded values - unsafe { String::from_utf8_unchecked(data) } - }) + cloned.map(|data| String::from_utf8_lossy(&data).into_owned()) } } @@ -259,6 +255,16 @@ mod tests { assert_eq!(path.get("id").unwrap(), &test); } + #[test] + fn test_invalid_utf8() { + let invalid_utf8 = percent_encode((0x80..=0xff).collect::>().as_slice()); + let uri = Uri::try_from(format!("/{}", invalid_utf8)).unwrap(); + let path = Path::new(Url::new(uri)); + + // We should always get a valid utf8 string + assert!(String::from_utf8(path.path().as_bytes().to_owned()).is_ok()); + } + #[test] fn test_from_hex() { let hex = b"0123456789abcdefABCDEF";