From 78b575658a61d17bd392b4b81b64c92c8beecbac Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 09:14:32 -0500 Subject: [PATCH] fetch: delegate HTTP URL and redirect syntax to craft-http-url (#4337) --- Cargo.lock | 6 ++ crates/fetch/Cargo.toml | 1 + crates/fetch/src/http.rs | 149 +++++---------------------------------- 3 files changed, 25 insertions(+), 131 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0807fd6a80..cd78730948 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1253,6 +1253,11 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-http-url" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c247a085be0b2db5456f1f9178024d6a12e4cc57#c247a085be0b2db5456f1f9178024d6a12e4cc57" + [[package]] name = "craft-i18n" version = "0.1.0" @@ -4081,6 +4086,7 @@ dependencies = [ name = "lightcraft-fetch" version = "0.21.1" dependencies = [ + "craft-http-url", "log", "rustls", "rustls-rustcrypto", diff --git a/crates/fetch/Cargo.toml b/crates/fetch/Cargo.toml index 2e65583fbc..77d1b0fdb4 100644 --- a/crates/fetch/Cargo.toml +++ b/crates/fetch/Cargo.toml @@ -10,6 +10,7 @@ workspace = true # downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-http-url = { git = "https://github.com/storytold/craft-libs", rev = "c247a085be0b2db5456f1f9178024d6a12e4cc57" } log = { workspace = true } rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } rustls-rustcrypto = "0.0.2-alpha" diff --git a/crates/fetch/src/http.rs b/crates/fetch/src/http.rs index f5ae5e410a..287de2d1e1 100644 --- a/crates/fetch/src/http.rs +++ b/crates/fetch/src/http.rs @@ -58,146 +58,31 @@ 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 { - let bad = |why: &str| HttpError::BadUrl(why.to_string()); - if s.len() > 16 * 1024 { - return Err(bad("URL exceeds 16 KiB")); - } - let s = s.trim(); - if s.chars().any(|c| c.is_control() || c == ' ') { - return Err(bad("contains spaces or control characters")); - } - let (tls, rest) = if let Some(r) = strip_scheme(s, "https://") { - (true, r) - } else if let Some(r) = strip_scheme(s, "http://") { - (false, r) - } else { - return Err(bad("only http:// and https:// are supported")); - }; - let rest = rest.split('#').next().unwrap_or_default(); - let (authority, path) = match rest.find(['/', '?']) { - Some(i) => (rest.get(..i).unwrap_or_default(), rest.get(i..).unwrap_or_default()), - None => (rest, ""), - }; - let path = if path.starts_with('/') { path.to_string() } else { format!("/{path}") }; - let path = remove_dot_segments(&path); - if authority.contains('@') { - return Err(bad("user names and passwords in URLs are not supported")); - } - let (host, port) = if let Some(v6) = authority.strip_prefix('[') { - let end = v6.find(']').ok_or_else(|| bad("unterminated IPv6 address"))?; - let host = v6.get(..end).unwrap_or_default(); - let after = v6.get(end + 1..).unwrap_or_default(); - if !after.is_empty() && !after.starts_with(':') { - return Err(bad("unexpected text after IPv6 address")); - } - (host.to_string(), after.strip_prefix(':')) - } else { - match authority.rsplit_once(':') { - Some((h, p)) => (h.to_string(), Some(p)), - None => (authority.to_string(), None), - } - }; - let port = match port { - Some(p) if p.bytes().all(|b| b.is_ascii_digit()) => p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| bad("bad port"))?, - Some(_) => return Err(bad("bad port")), - None if tls => 443, - None => 80, - }; - if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | ':' | '_')) { - return Err(bad("bad host name")); - } - Ok(Url { tls, host: host.to_ascii_lowercase(), port, path }) + fn shared(&self) -> craft_http_url::Url { + craft_http_url::Url { tls: self.tls, host: self.host.clone(), port: self.port, path: self.path.clone() } } - /// `Location` of a redirect, resolved against this URL. - pub fn join(&self, location: &str) -> Result { - let l = location.trim(); - if strip_scheme(l, "http://").is_some() || strip_scheme(l, "https://").is_some() { - let url = Url::parse(l)?; - if self.tls && !url.tls { - return Err(HttpError::BadUrl("redirect from https to http refused".into())); - } - return Ok(url); - } - // another scheme (`ftp:`, `file:`, `data:`…) - if let Some((scheme, _)) = l.split_once(':') - && !scheme.is_empty() - && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) - { - return Err(HttpError::BadUrl(format!("redirect to an unsupported location `{scheme}:`"))); - } - let scheme = if self.tls { "https" } else { "http" }; - let host = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() }; - let base = format!("{scheme}://{host}:{}", self.port); - if let Some(rest) = l.strip_prefix("//") { - return Url::parse(&format!("{scheme}://{rest}")); - } - if l.starts_with('/') { - return Url::parse(&format!("{base}{l}")); - } - // empty or fragment-only: the same document - if l.is_empty() || l.starts_with('#') { - return Ok(self.clone()); - } - // relative to the current directory - let dir = self.path.split('?').next().unwrap_or("/"); - // a query-only reference keeps the whole path, file name included (RFC 3986 §5.2.2) - if l.starts_with('?') { - return Url::parse(&format!("{base}{dir}{l}")); - } - let dir = dir.rsplit_once('/').map_or("", |(d, _)| d); - Url::parse(&format!("{base}{dir}/{l}")) + fn from_shared(url: craft_http_url::Url) -> Self { + Self { tls: url.tls, host: url.host, port: url.port, path: url.path } + } + + pub fn parse(s: &str) -> Result { + craft_http_url::Url::parse(s).map(Self::from_shared).map_err(|e| HttpError::BadUrl(e.0)) + } + + /// Resolve a redirect without weakening HTTPS or changing app-owned credential policy. + pub fn join(&self, location: &str) -> Result { + self.shared().join(location).map(Self::from_shared).map_err(|e| HttpError::BadUrl(e.0)) } fn host_header(&self) -> String { - let host = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() }; - let default = if self.tls { 443 } else { 80 }; - if self.port == default { host } else { format!("{host}:{}", self.port) } + self.shared().host_header() } - /// The URL without its query (for messages: a query may hold a signed token). + /// The URL without its query (which may contain a signed token). pub fn display(&self) -> String { - let scheme = if self.tls { "https" } else { "http" }; - format!("{scheme}://{}{}", self.host_header(), self.path.split('?').next().unwrap_or("/")) + self.shared().display() } } @@ -697,6 +582,8 @@ mod tests { #[test] fn rejects_oversized_and_control_character_urls() { + let base = Url::parse("https://example.com/path").unwrap(); + assert!(base.join(&format!("#{}", "x".repeat(16 * 1024))).is_err()); assert!(Url::parse(&format!("https://example.com/{}", "x".repeat(16 * 1024))).is_err()); assert!(Url::parse("https://example.com/x?secret=abc\r\nInjected: 1").is_err()); }