Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Merge PR #2410: Match URL schemes case-insensitively in Url::parse and Url::join

aionggf0951e819c6c
diff --cc crates/fetch/src/http.rs
index 974222c2a,bad39163c..5ff6cd74b
--- a/crates/fetch/src/http.rs
+++ b/crates/fetch/src/http.rs
@@@ -58,37 -58,12 +58,43 @@@ pub struct Url
pub path: String,
}
+/// Remove `.` and `..` segments from the path part of `path` (RFC 3986 section 5.2.4); the query is kept as is.
+fn remove_dot_segments(path: &str) -> String {
+ let (p, query) = match path.find('?') {
+ Some(i) => (path.get(..i).unwrap_or_default(), path.get(i..).unwrap_or_default()),
+ None => (path, ""),
+ };
+ let mut out: Vec<&str> = Vec::new();
+ let mut segments = p.split('/').skip(1).peekable();
+ let mut trailing_slash = false;
+ while let Some(seg) = segments.next() {
+ let last = segments.peek().is_none();
+ match seg {
+ "." => trailing_slash = last,
+ ".." => {
+ out.pop();
+ trailing_slash = last;
+ }
+ _ => {
+ out.push(seg);
+ trailing_slash = false;
+ }
+ }
+ }
+ let mut result = format!("/{}", out.join("/"));
+ if trailing_slash && !result.ends_with('/') {
+ result.push('/');
+ }
+ result.push_str(query);
+ result
+}
+
+ /// `s` without the leading `prefix`, matched ASCII case-insensitively (RFC 3986 §3.1).
+ fn strip_scheme<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
+ let head = s.get(..prefix.len())?;
+ head.eq_ignore_ascii_case(prefix).then(|| s.get(prefix.len()..).unwrap_or_default())
+ }
+
impl Url {
pub fn parse(s: &str) -> Result<Url, HttpError> {
let bad = |why: &str| HttpError::BadUrl(why.to_string());
@@@ -654,22 -624,15 +660,31 @@@ mod tests
assert!(Url::parse("https://example.com/x?secret=abc\r\nInjected: 1").is_err());
}
+ #[test]
+ fn join_query_only_keeps_file_name() {
+ let u = Url::parse("https://a.example/x/y/file?q=1").unwrap();
+ assert_eq!(u.join("?page=2").unwrap().path, "/x/y/file?page=2");
+ }
+
+ #[test]
+ fn join_removes_dot_segments() {
+ let base = Url::parse("https://a.example/x/y/file").unwrap();
+ for (loc, want) in
+ [("../z", "/x/z"), ("./z", "/x/y/z"), ("../../../z", "/z"), ("/a/./b/../c", "/a/c"), ("../z?q=1", "/x/z?q=1"), ("..", "/x/")]
+ {
+ assert_eq!(base.join(loc).unwrap().path, want, "{loc}");
+ }
+ }
+
+ #[test]
+ fn url_scheme_is_matched_case_insensitively() {
+ let u = Url::parse("HTTPS://A.example/z").unwrap();
+ assert_eq!((u.tls, u.host.as_str(), u.port, u.path.as_str()), (true, "a.example", 443, "/z"));
+ assert!(Url::parse("Http://a.example/").is_ok());
+ let j = Url::parse("https://a.example/start").unwrap().join("HTTPS://cdn.example/file").unwrap();
+ assert_eq!((j.tls, j.host.as_str(), j.path.as_str()), (true, "cdn.example", "/file"));
+ }
+
#[test]
fn parses_urls() {
let u = Url::parse("https://cdn.example.com/models/sam3/model.safetensors?sig=1#x").unwrap();