From d43d79cd5577d43dbd42c7aae5155a1b04aafa34 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:02:30 +0000 Subject: [PATCH 1/6] Start redactor-url-ends Refs #2448. Assisted-by: Claude Code From 34614226a8633165c2c5c4d3040d226fc77dbb90 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:27:33 +0000 Subject: [PATCH 2/6] Read every URL in a run of text for credentials The redactor decided where a quoted URL ends before it looked for the credential, and looked at the first authority only. So it printed: - a userinfo that holds `'` or `)`. Both are legal there, and the messages wrap a quoted URL in exactly those; - the userinfo of a URL nested in the query or the path of another, or joined to another by `;`; - the secret query values and the grant token of a URL nested in a query; - the grant token and the query secrets of a URL whose host is an IPv6 literal, which ended at its `]`; - the grant token of a registry URL whose package is named like a uuid, and of every URL but the last in a `;`-joined list. Every `://` now starts a URL of its own: its userinfo is redacted, the path behind it is read for a grant token, and a `?` inside a query pair starts a nested query. What follows a `#` is read for secret names like a query. In text, a URL's end is looked for behind the userinfo and the brackets of an IPv6 host, and a `;` before a scheme separates list elements as a `,` does. A registry URL's token is also taken by its place, right below the ecosystem. Finding the end is one forward scan now. It was a scan to the end of the text for every list element, which took 1.6 s on a 192 KB comma-joined list and takes 3 ms. Refs #2448. Assisted-by: Claude Code --- crates/socket-patch-core/src/utils/redact.rs | 462 ++++++++++++++++--- 1 file changed, 399 insertions(+), 63 deletions(-) diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 569f8b472..3fc83cef6 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -28,6 +28,15 @@ //! URL). Per RFC 3986 a raw `@` in the authority can only end the userinfo //! (it is percent-encoded everywhere else), so the authority's tail after //! its LAST `@` is exactly `host[:port]`. +//! +//! A message can quote a URL inside another, or several joined into a +//! list, so every `://` is read as the start of a URL of its own: its +//! userinfo, the path behind it (for a grant token) and the query behind +//! that (`…/fetch?url=https://user:token@host/x?sig=…`). In free text the +//! userinfo and an IPv6 host are found before the URL's end is, because +//! both can hold a character that ends a quoted URL anywhere else: `'` +//! and `)` are legal in a userinfo, and the messages wrap a URL in +//! exactly those. use std::borrow::Cow; use std::ops::Range; @@ -38,16 +47,21 @@ pub const REDACTED: &str = ""; /// Path levels under which Socket serves grant-tokenized URLs. const SERVE_ROOTS: &[&str] = &["patch", "patch-registry"]; -/// Byte range of `url`'s authority: after `scheme://` (or from the start -/// when there is no scheme) up to the first `/`, `?` or `#`. -fn authority_span(url: &str) -> Range { - let start = url.find("://").map_or(0, |i| i + 3); +/// Byte range of the authority of `url` that starts at `start`: up to +/// the first `/`, `?` or `#`. +fn authority_at(url: &str, start: usize) -> Range { let len = url[start..] .find(['/', '?', '#']) .unwrap_or(url.len() - start); start..start + len } +/// Byte range of `url`'s authority: after `scheme://` (or from the start +/// when there is no scheme) up to the first `/`, `?` or `#`. +fn authority_span(url: &str) -> Range { + authority_at(url, url.find("://").map_or(0, |i| i + 3)) +} + /// Byte range of `url`'s userinfo (without the `@`), when it has one. fn userinfo_span(url: &str) -> Option> { let authority = authority_span(url); @@ -121,47 +135,110 @@ fn is_secret_param(name: &str) -> bool { words.iter().any(|w| WORDS.contains(&w.as_str())) } -/// Byte range of the grant-token path level of a Socket-served URL: the -/// level right before the LAST uuid-shaped level, when a serve root -/// (`patch`, `patch-registry`) precedes it. A URL without a serve root, or -/// whose uuid level directly follows the root, has none. -fn grant_token_span(url: &str) -> Option> { - let authority = authority_span(url); - let path_start = authority.end; - let path_len = url[path_start..] - .find(['?', '#']) - .unwrap_or(url.len() - path_start); - let path = &url[path_start..path_start + path_len]; +/// The grant-token levels among the path levels of `url[path]`, added to +/// `spans`. +/// +/// The token is the level right before the LAST uuid-shaped level, when a +/// serve root (`patch`, `patch-registry`) precedes it: a grant token can +/// be uuid-shaped itself, so the first uuid is not the patch's. A path +/// without a serve root, or whose uuid level directly follows the root, +/// has none. +/// +/// A registry URL also holds its token at a fixed place, right below the +/// ecosystem (`patch-registry////…`). What follows the +/// uuid there is a package's own path, and a package can be named like a +/// uuid, which makes the patch uuid the level before the last one. +fn grant_tokens_in(url: &str, path: Range, spans: &mut Vec>) { let mut levels: Vec> = Vec::new(); - let mut offset = 0; - for level in path.split('/') { - levels.push(path_start + offset..path_start + offset + level.len()); + let mut offset = path.start; + for level in url[path].split('/') { + levels.push(offset..offset + level.len()); offset += level.len() + 1; } - let root = levels - .iter() - .position(|r| SERVE_ROOTS.contains(&&url[r.clone()]))?; - let uuid = levels + let is_uuid = |r: &Range| is_uuid_shaped(&url[r.clone()]); + let last_uuid = levels .iter() - .rposition(|r| is_uuid_shaped(&url[r.clone()]))?; - (uuid > root + 1) - .then(|| levels[uuid - 1].clone()) - .filter(|r| !r.is_empty()) + .position(|r| SERVE_ROOTS.contains(&&url[r.clone()])) + .zip(levels.iter().rposition(is_uuid)) + .filter(|(root, uuid)| *uuid > root + 1) + .map(|(_, uuid)| uuid - 1); + let registry = (0..levels.len()) + .filter(|&root| { + &url[levels[root].clone()] == "patch-registry" + && levels.get(root + 3).is_some_and(is_uuid) + }) + .map(|root| root + 2); + spans.extend( + last_uuid + .into_iter() + .chain(registry) + .map(|token| levels[token].clone()) + .filter(|r| !r.is_empty()), + ); +} + +/// Byte ranges of the grant-token path levels of a Socket-served URL +/// ([`grant_tokens_in`]): those of `url`'s own path, which runs to the +/// first `?` or `#`, and those of the path behind each `://` in it, so +/// that a URL nested in another, or joined to it, is read for its own +/// token. Such a path ends at the next `?`, `#` or `&` (a nested URL can +/// be a query value), or where the next `://` begins. +fn grant_token_spans(url: &str) -> Vec> { + let mut spans = Vec::new(); + let start = authority_span(url).end; + let len = url[start..].find(['?', '#']).unwrap_or(url.len() - start); + let own = start..start + len; + grant_tokens_in(url, own.clone(), &mut spans); + let mut seps = url.match_indices("://").map(|(sep, _)| sep).peekable(); + while let Some(sep) = seps.next() { + let limit = seps.peek().copied().unwrap_or(url.len()); + let start = authority_at(url, sep + 3).end.min(limit); + let len = url[start..limit] + .find(['?', '#', '&']) + .unwrap_or(limit - start); + let path = start..start + len; + if path != own { + grant_tokens_in(url, path, &mut spans); + } + } + spans } -/// Byte ranges of the secret query values of `url` (the query runs from -/// the first `?`, when no `#` precedes it, to the next `#`). +/// Byte ranges of the secret values among the `name=value` pairs of +/// `url`: those of its query, and those behind it. +/// +/// The pairs start at the first `?` or `#` and are separated by `&` and +/// `#`. What follows a `#` is read like a query because a URL nested in +/// this one, or joined to it, has its query there, and a fragment can +/// name a secret itself (`#access_token=…`). A `?` inside a pair starts +/// the query of a nested URL (`?url=https://h/x?token=…`): the name after +/// it is read too, and a secret value runs to the end of the pair either +/// way. fn secret_query_spans(url: &str) -> Vec> { - let Some(q) = url.find(['?', '#']).filter(|&i| url.as_bytes()[i] == b'?') else { + let Some(q) = url.find(['?', '#']) else { return Vec::new(); }; - let end = url[q..].find('#').map_or(url.len(), |i| q + i); let mut spans = Vec::new(); let mut pos = q + 1; - for pair in url[q + 1..end].split('&') { - if let Some(eq) = pair.find('=') { - if eq + 1 < pair.len() && is_secret_param(&pair[..eq]) { - spans.push(pos + eq + 1..pos + pair.len()); + for pair in url[q + 1..].split(['&', '#']) { + // Where the name that the next `=` ends starts: the pair's start, + // then right after the first `?` that follows each `=`. + let mut name = Some(0); + for (i, byte) in pair.bytes().enumerate() { + match byte { + b'?' => { + name.get_or_insert(i + 1); + } + b'=' => { + let secret = name + .take() + .is_some_and(|start| is_secret_param(&pair[start..i])); + if secret && i + 1 < pair.len() { + spans.push(pos + i + 1..pos + pair.len()); + break; + } + } + _ => {} } } pos += pair.len() + 1; @@ -193,23 +270,40 @@ fn replace_spans<'a>(url: &'a str, mut spans: Vec>, with: &str) -> Cow::Owned(out) } -/// Whether `userinfo` of `url` is a bare ssh login name (`git` in -/// `ssh://git@github.com/…`): an ssh URL authenticates with a key, so a -/// userinfo without a `:password` names the account, not a secret. -fn is_ssh_login(url: &str, userinfo: &str) -> bool { - url.split_once("://") - .is_some_and(|(scheme, _)| scheme.to_ascii_lowercase().ends_with("ssh")) +/// Whether `userinfo`, behind a scheme that ends where `before` does, is +/// a bare ssh login name (`git` in `ssh://git@github.com/…`): an ssh URL +/// authenticates with a key, so a userinfo without a `:password` names +/// the account, not a secret. +fn is_ssh_login(before: &str, userinfo: &str) -> bool { + let scheme = before.as_bytes(); + scheme.len() >= 3 + && scheme[scheme.len() - 3..].eq_ignore_ascii_case(b"ssh") && !userinfo.contains(':') } +/// Byte ranges of the userinfo that is a credential, of every authority +/// in `url`: one per `://` (a URL nested in the path or the query of +/// another carries its own), or the leading one of a `url` with no +/// scheme. An ssh login name ([`is_ssh_login`]) is not one. +fn secret_userinfo_spans(url: &str) -> Vec> { + let userinfo = |scheme_end: usize, start: usize| { + let at = url[authority_at(url, start)].rfind('@')?; + let span = start..start + at; + (!is_ssh_login(&url[..scheme_end], &url[span.clone()])).then_some(span) + }; + if !url.contains("://") { + return userinfo(0, 0).into_iter().collect(); + } + url.match_indices("://") + .filter_map(|(sep, _)| userinfo(sep, sep + 3)) + .collect() +} + /// `url` safe to show: userinfo, the Socket grant token and secret query /// values each replaced with [`REDACTED`]. pub fn redact_url(url: &str) -> Cow<'_, str> { - let mut spans: Vec> = userinfo_span(url) - .filter(|r| !is_ssh_login(url, &url[r.clone()])) - .into_iter() - .collect(); - spans.extend(grant_token_span(url)); + let mut spans = secret_userinfo_spans(url); + spans.extend(grant_token_spans(url)); spans.extend(secret_query_spans(url)); replace_spans(url, spans, REDACTED) } @@ -243,6 +337,37 @@ fn ends_url(c: char) -> bool { c.is_whitespace() || matches!(c, '"' | '\'' | '`' | '<' | '>' | ')' | ']' | '}' | '|') } +/// A character that no userinfo holds, so the text after a `://` is not +/// read for one past it: where the authority ends, and every [`ends_url`] +/// character but `'` and `)`, which RFC 3986 lets a userinfo hold as they +/// are. +fn ends_userinfo(c: char) -> bool { + matches!(c, '/' | '?' | '#') || (ends_url(c) && !matches!(c, '\'' | ')')) +} + +/// Length of the userinfo that `text` starts with, its `@` included; 0 +/// when the authority there has none. +fn userinfo_len(text: &str) -> usize { + let authority = &text[..text.find(ends_userinfo).unwrap_or(text.len())]; + authority.rfind('@').map_or(0, |at| at + 1) +} + +/// Length of the bracketed IPv6 host that `text` starts with (`[::1]`, +/// `[fe80::1%25eth0]`); 0 when it starts with none. +fn ipv6_host_len(text: &str) -> usize { + let Some(inner) = text.strip_prefix('[') else { + return 0; + }; + let len = inner + .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, ':' | '.' | '%' | '-' | '_'))) + .unwrap_or(inner.len()); + if inner[len..].starts_with(']') && inner[..len].contains(':') { + len + 2 + } else { + 0 + } +} + /// Start of the scheme that ends at `sep` (the byte offset of a `://`), /// scanning back no further than `floor`: right after the last character /// before `sep` that no scheme can hold, however many bytes it takes. @@ -254,26 +379,49 @@ fn scheme_start(text: &str, floor: usize, sep: usize) -> usize { .map_or(floor, |(j, c)| floor + j + c.len_utf8()) } -/// Where a URL starting with the `://` at `sep` and running to at most -/// `end` stops because the next element of a comma-joined list begins (a -/// GOPROXY value: `https://a,https://u:p@b,direct`): the `,` before the -/// next `scheme://`. A `scheme://` after anything else (`?next=https://…`) -/// is part of the URL, so a query secret after it stays in its query. -fn list_element_end(text: &str, sep: usize, end: usize) -> usize { - let mut from = sep + 3; - while let Some(j) = text[from..end].find("://").map(|j| from + j) { - let scheme = scheme_start(text, from, j); - if scheme > from && scheme < j && text[..scheme].ends_with(',') { +/// Where the URL whose `://` is at `sep` ends in `text`. +/// +/// A URL quoted in free text ends at the first [`ends_url`] character, +/// but two parts of it can hold one and are stepped over first: a +/// userinfo ([`ends_userinfo`]) and the brackets of an IPv6 host. A URL +/// nested in this one (`…?url=https://user:token@host/…`) has its own. +/// +/// It also ends where the next element of a `,`- or `;`-joined list +/// begins (a GOPROXY value: `https://a,https://u:p@b,direct`): at the +/// separator before the next `scheme://`. A `scheme://` after anything +/// else (`?next=https://…`) is part of the URL, so a query secret after +/// it stays in its query. +fn url_end(text: &str, mut sep: usize) -> usize { + loop { + let start = sep + 3; + let host = start + userinfo_len(&text[start..]); + let from = host + ipv6_host_len(&text[host..]); + // The URL's end or the next `://`, whichever comes first. + let mut next = None; + for (i, c) in text[from..].char_indices() { + if ends_url(c) { + return from + i; + } + if c == ':' && text[from + i..].starts_with("://") { + next = Some(from + i); + break; + } + } + let Some(next) = next else { + return text.len(); + }; + let scheme = scheme_start(text, start, next); + if scheme > start && scheme < next && text[..scheme].ends_with([',', ';']) { return scheme - 1; } - from = j + 3; + sep = next; } - end } /// `text` with every `scheme://…` URL in it passed through [`redact_url`]. /// Trailing sentence punctuation (`.`, `,`, `;`, `:`) is not taken as part -/// of a URL, and each element of a comma-joined URL list is its own URL. +/// of a URL, and each element of a `,`- or `;`-joined URL list is its own +/// URL ([`url_end`]). pub fn redact_urls_in(text: &str) -> Cow<'_, str> { if !text.contains("://") { return Cow::Borrowed(text); @@ -283,9 +431,7 @@ pub fn redact_urls_in(text: &str) -> Cow<'_, str> { let mut changed = false; while let Some(i) = text[at..].find("://").map(|i| at + i) { let start = scheme_start(text, at, i); - let tail = &text[i..]; - let end = i + tail.find(ends_url).unwrap_or(tail.len()); - let end = list_element_end(text, i, end); + let end = url_end(text, i); let end = start + text[start..end] .trim_end_matches(['.', ',', ';', ':']) @@ -507,8 +653,198 @@ mod tests { } } - /// A comma-joined URL list (GOPROXY) is redacted element by element; - /// a URL nested in a query is still part of its URL. + /// RFC 3986 lets a userinfo hold `'` and `)` as they are, and the + /// messages wrap a quoted URL in exactly those. Past the host they + /// end the URL as before, and so does a character no userinfo holds. + #[test] + fn a_credential_that_holds_a_quote_or_a_bracket_is_redacted() { + for (text, redacted) in [ + ( + "refusing a Poetry source (legacy https://bot:pa)ss@pypi.corp.example/simple) for six", + "refusing a Poetry source (legacy https://@pypi.corp.example/simple) for six", + ), + ( + "lock block `\"left-pad@git+https://x-access-token:gh'p_tok@github.com/acme/left-pad.git\"` installs from git", + "lock block `\"left-pad@git+https://@github.com/acme/left-pad.git\"` installs from git", + ), + ( + "'https://u:(p')@h.example:8443' is not reachable", + "'https://@h.example:8443' is not reachable", + ), + // The closing bracket of the text, not of a credential. + ( + "(see https://h.example) or mail bob@corp.example", + "(see https://h.example) or mail bob@corp.example", + ), + ( + "'https://a.example' and 'bob@b.example'", + "'https://a.example' and 'bob@b.example'", + ), + ( + "{\"url\":\"https://h.example\",\"email\":\"bob@corp.example\"}", + "{\"url\":\"https://h.example\",\"email\":\"bob@corp.example\"}", + ), + ( + "(https://u:p@h.example/a)b@c", + "(https://@h.example/a)b@c", + ), + ] { + assert_eq!(redact_urls_in(text), redacted, "{text}"); + } + } + + /// Every `://` has an authority of its own: a URL in the query or the + /// path of another, and each element of a list however it is joined. + #[test] + fn the_userinfo_of_every_url_in_a_run_is_redacted() { + for (text, redacted) in [ + ( + "six @ https://proxy.corp.example/fetch?url=https://bot:tok@pypi.corp.example/six.whl; refusing", + "six @ https://proxy.corp.example/fetch?url=https://@pypi.corp.example/six.whl; refusing", + ), + ( + "https://u:p@h/a/https://u2:p2@h2/x", + "https://@h/a/https://@h2/x", + ), + ( + "RestoreSources=https://a.example/x;https://u:p@b.example", + "RestoreSources=https://a.example/x;https://@b.example", + ), + ( + "a@https://h/x,b@https://u:p@h/y", + "a@https://h/x,b@https://@h/y", + ), + ( + "https://a.example,é://u:p@b", + "https://a.example,é://@b", + ), + ( + "(https://proxy/fetch?url=https://bot:to)k@h.example/x)", + "(https://proxy/fetch?url=https://@h.example/x)", + ), + // A nested ssh login name is no more a secret than a leading one. + ( + "https://h/x?next=ssh://git@github.com/o/r.git", + "https://h/x?next=ssh://git@github.com/o/r.git", + ), + ( + "https://h/x?next=ssh://git:hunter2@git.corp/r.git", + "https://h/x?next=ssh://@git.corp/r.git", + ), + ] { + assert_eq!(redact_urls_in(text), redacted, "{text}"); + assert_eq!(redact_url(text), redacted, "as one URL: {text}"); + } + } + + /// The brackets of an IPv6 host are part of the URL: what follows + /// them is still its path and query. A `]` anywhere else ends it. + #[test] + fn an_ipv6_host_does_not_end_its_url() { + for (text, redacted) in [ + ( + "GET http://[::1]:8080/x?token=abc: HTTP 404".to_string(), + "GET http://[::1]:8080/x?token=: HTTP 404".to_string(), + ), + ( + format!("GET http://[::1]:8080/patch-registry/npm/GSEC/{UUID}/left-pad: HTTP 404"), + format!("GET http://[::1]:8080/patch-registry/npm//{UUID}/left-pad: HTTP 404"), + ), + ( + format!("(https://u:p@[fe80::1%25eth0]:8443/patch/npm/a/1.0.0/GSEC/{UUID}/a.tgz)"), + format!("(https://@[fe80::1%25eth0]:8443/patch/npm/a/1.0.0//{UUID}/a.tgz)"), + ), + ( + "[https://[::1]/x?token=abc]".to_string(), + "[https://[::1]/x?token=]".to_string(), + ), + ( + "[https://h.example/x]?token=abc".to_string(), + "[https://h.example/x]?token=abc".to_string(), + ), + ( + "https://[docs]/x?token=abc".to_string(), + "https://[docs]/x?token=abc".to_string(), + ), + ] { + assert_eq!(redact_urls_in(&text), redacted, "{text}"); + } + } + + /// A URL nested in another has a query and a path of its own, and a + /// fragment is read for secret names like a query. + #[test] + fn the_query_and_the_grant_token_of_a_nested_url_are_redacted() { + for (url, redacted) in [ + ( + "https://proxy.corp.example/fetch?url=https://s3.example/b/six.whl?X-Amz-Signature=abc&v=1".to_string(), + "https://proxy.corp.example/fetch?url=https://s3.example/b/six.whl?X-Amz-Signature=&v=1".to_string(), + ), + ( + format!("https://proxy/fetch?v=1&url=https://patch.socket.dev/patch/npm/a/1.0.0/{TOKEN}/{UUID}/a.tgz&w=2"), + format!("https://proxy/fetch?v=1&url=https://patch.socket.dev/patch/npm/a/1.0.0//{UUID}/a.tgz&w=2"), + ), + ( + "https://h/app#/callback?access_token=abc&state=1".to_string(), + "https://h/app#/callback?access_token=&state=1".to_string(), + ), + ( + "https://h/a.whl#sha256=0abc;https://h/b.whl?token=abc".to_string(), + "https://h/a.whl#sha256=0abc;https://h/b.whl?token=".to_string(), + ), + // The name of a pair is everything before its first `=`. + ( + "https://h/x?token?v=1".to_string(), + "https://h/x?token?v=".to_string(), + ), + ( + "https://h/x.whl#sha256=0abc&egg=six&subdirectory=src".to_string(), + "https://h/x.whl#sha256=0abc&egg=six&subdirectory=src".to_string(), + ), + ] { + assert_eq!(redact_url(&url), redacted, "{url}"); + assert_eq!(redact_urls_in(&url), redacted, "in text: {url}"); + } + } + + /// A registry URL holds its token right below the ecosystem, whatever + /// the package's own path looks like, and each URL of a list has one. + #[test] + fn a_registry_token_is_redacted_whatever_follows_the_uuid() { + // A package named like a uuid: the patch uuid goes with the token, + // being the level before the last uuid-shaped one. + assert_eq!( + redact_urls_in(&format!( + "GET https://h/patch-registry/npm/GSEC/{UUID}/{TOKEN}/1.3.0: HTTP 404" + )), + format!( + "GET https://h/patch-registry/npm///{TOKEN}/1.3.0: HTTP 404" + ) + ); + let sources = format!( + "https://h/patch-registry/nuget/GSEC1/{UUID}/index.json;https://h/patch-registry/nuget/GSEC2/{TOKEN}/index.json" + ); + let redacted = format!( + "https://h/patch-registry/nuget//{UUID}/index.json;https://h/patch-registry/nuget//{TOKEN}/index.json" + ); + assert_eq!( + redact_urls_in(&format!("sources ({sources})")), + format!("sources ({redacted})") + ); + assert_eq!(redact_url(&sources), redacted); + let artifacts = format!( + "https://h/patch/npm/a/1.0.0/GSEC1/{UUID}/a.tgz;https://h/patch/npm/b/1.0.0/GSEC2/{TOKEN}/b.tgz" + ); + let redacted = format!( + "https://h/patch/npm/a/1.0.0//{UUID}/a.tgz;https://h/patch/npm/b/1.0.0//{TOKEN}/b.tgz" + ); + assert_eq!(redact_urls_in(&artifacts), redacted); + assert_eq!(redact_url(&artifacts), redacted); + } + + /// A `,`- or `;`-joined URL list (GOPROXY, NuGet's sources) is redacted + /// element by element; a URL nested in a query is still part of its + /// URL. #[test] fn every_element_of_a_url_list_is_redacted() { assert_eq!( From ad6ee30d85d1fffbe717eaa2c6205f6a9fd6dde6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:27:33 +0000 Subject: [PATCH 3/6] Redact a failed request's URL as one URL reqwest names the request URL in brackets in its error text, and `network_error_detail` redacted it by scanning that text. A secret query value that holds a `)` ended the URL there, so the rest of the value was printed. The URL is now taken from the error and redacted whole before the text is scanned. Refs #2448. Assisted-by: Claude Code --- crates/socket-patch-core/src/api/client.rs | 42 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 571ee770d..2457a949c 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -23,7 +23,7 @@ use crate::constants::USER_AGENT as USER_AGENT_VALUE; use crate::utils::digest::is_hex; use crate::utils::env_compat::{is_offline_env, proxy_url_from_env}; use crate::utils::notice::{notice_once, Notice}; -use crate::utils::redact::{redact_url, redact_urls_in}; +use crate::utils::redact::{redact_message, redact_url}; use crate::utils::socket_cli_config; use crate::utils::target::is_uuid_shaped; @@ -59,11 +59,19 @@ static MULTI_ORG_SHOWN: AtomicBool = AtomicBool::new(false); /// spelled out by an outer message are skipped. pub(crate) fn network_error_detail(e: &reqwest::Error) -> String { // reqwest's text names the request URL: a grant URL, or one with - // userinfo from `--api-url` / a proxy, is quoted redacted. - let mut msg = redact_urls_in(&e.to_string()).into_owned(); + // userinfo from `--api-url` / a proxy, is quoted redacted. The URL is + // taken from the error and redacted as one URL first: cut out of the + // text, it would end at a `)` that a secret query value holds. + let shown = |text: String| { + redact_message(match e.url() { + Some(url) => text.replace(url.as_str(), &redact_url(url.as_str())), + None => text, + }) + }; + let mut msg = shown(e.to_string()); let mut source = std::error::Error::source(e); while let Some(cause) = source { - let part = redact_urls_in(&cause.to_string()).into_owned(); + let part = shown(cause.to_string()); if !part.is_empty() && !msg.contains(&part) { msg.push_str(": "); msg.push_str(&part); @@ -4498,6 +4506,32 @@ mod tests { } } + /// reqwest names the request URL in brackets. A secret query value + /// that holds a `)` is redacted whole: the URL is taken from the + /// error, not cut out of its text. + #[tokio::test] + async fn network_error_detail_redacts_the_request_url_as_one_url() { + let port = { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + l.local_addr().unwrap().port() + }; + let err = reqwest::Client::new() + .get(format!( + "http://127.0.0.1:{port}/private?token=ab)cdSECRET&v=1" + )) + .send() + .await + .expect_err("nothing listens there"); + let detail = network_error_detail(&err); + assert!(!detail.contains("SECRET"), "{detail}"); + assert!( + detail.contains(&format!( + "(http://127.0.0.1:{port}/private?token=&v=1)" + )), + "{detail}" + ); + } + #[tokio::test] async fn network_error_detail_keeps_the_root_cause() { // A port that was just free: connecting is refused, deterministically. From 31d0e404e6754d3c34ad6e55025ddb47b30330dd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:40:02 +0000 Subject: [PATCH 4/6] End a token's path where the next URL begins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `;` before a scheme split the text into two URLs, as a `,` does. That showed text `main` hides: after a secret query value, the `;https://…` behind it was the tail of the value. A `;`-joined list is one URL again, as on `main`, so nothing `main` redacts is shown. What the split was for is done where the token is looked for. The path behind a `://` ends before the next URL's scheme and before the `,` or `;` that joins the two, so a registry URL that ends at its uuid is read however the list is joined, and as one URL too. Refs #2448. Assisted-by: Claude Code --- crates/socket-patch-core/src/utils/redact.rs | 29 +++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 3fc83cef6..b85d151b3 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -182,7 +182,8 @@ fn grant_tokens_in(url: &str, path: Range, spans: &mut Vec>) /// first `?` or `#`, and those of the path behind each `://` in it, so /// that a URL nested in another, or joined to it, is read for its own /// token. Such a path ends at the next `?`, `#` or `&` (a nested URL can -/// be a query value), or where the next `://` begins. +/// be a query value), or where the next URL begins: before its scheme, +/// and before the `,` or `;` that joins it to this one. fn grant_token_spans(url: &str) -> Vec> { let mut spans = Vec::new(); let start = authority_span(url).end; @@ -191,7 +192,10 @@ fn grant_token_spans(url: &str) -> Vec> { grant_tokens_in(url, own.clone(), &mut spans); let mut seps = url.match_indices("://").map(|(sep, _)| sep).peekable(); while let Some(sep) = seps.next() { - let limit = seps.peek().copied().unwrap_or(url.len()); + let limit = seps.peek().map_or(url.len(), |&next| { + let scheme = scheme_start(url, sep + 3, next); + scheme - usize::from(scheme > sep + 3 && url[..scheme].ends_with([',', ';'])) + }); let start = authority_at(url, sep + 3).end.min(limit); let len = url[start..limit] .find(['?', '#', '&']) @@ -386,11 +390,11 @@ fn scheme_start(text: &str, floor: usize, sep: usize) -> usize { /// userinfo ([`ends_userinfo`]) and the brackets of an IPv6 host. A URL /// nested in this one (`…?url=https://user:token@host/…`) has its own. /// -/// It also ends where the next element of a `,`- or `;`-joined list -/// begins (a GOPROXY value: `https://a,https://u:p@b,direct`): at the -/// separator before the next `scheme://`. A `scheme://` after anything -/// else (`?next=https://…`) is part of the URL, so a query secret after -/// it stays in its query. +/// It also ends where the next element of a comma-joined list begins (a +/// GOPROXY value: `https://a,https://u:p@b,direct`): at the `,` before +/// the next `scheme://`. A `scheme://` after anything else +/// (`?next=https://…`, a `;`-joined list) is part of the URL, so a query +/// secret after it stays in its query. fn url_end(text: &str, mut sep: usize) -> usize { loop { let start = sep + 3; @@ -411,7 +415,7 @@ fn url_end(text: &str, mut sep: usize) -> usize { return text.len(); }; let scheme = scheme_start(text, start, next); - if scheme > start && scheme < next && text[..scheme].ends_with([',', ';']) { + if scheme > start && scheme < next && text[..scheme].ends_with(',') { return scheme - 1; } sep = next; @@ -420,8 +424,8 @@ fn url_end(text: &str, mut sep: usize) -> usize { /// `text` with every `scheme://…` URL in it passed through [`redact_url`]. /// Trailing sentence punctuation (`.`, `,`, `;`, `:`) is not taken as part -/// of a URL, and each element of a `,`- or `;`-joined URL list is its own -/// URL ([`url_end`]). +/// of a URL, and each element of a comma-joined URL list is its own URL +/// ([`url_end`]). pub fn redact_urls_in(text: &str) -> Cow<'_, str> { if !text.contains("://") { return Cow::Borrowed(text); @@ -842,9 +846,8 @@ mod tests { assert_eq!(redact_url(&artifacts), redacted); } - /// A `,`- or `;`-joined URL list (GOPROXY, NuGet's sources) is redacted - /// element by element; a URL nested in a query is still part of its - /// URL. + /// A comma-joined URL list (GOPROXY) is redacted element by element; + /// a URL nested in a query is still part of its URL. #[test] fn every_element_of_a_url_list_is_redacted() { assert_eq!( From a286629bb0fe8a9b4c94a569f5171a9dab3c93e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:41:08 +0000 Subject: [PATCH 5/6] Take the review's findings on the redactor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A grant token could be missed in a URL that is now nested where `main` read it on its own: its path was cut at an `&` (a package named `a&b`) or at the next `://`. The path behind each `://` is read three ways: as a URL of its own, up to where the next URL begins, and up to its first `&`. Paths read whole do not overlap, so the work stays linear. - Reading a fragment's own pairs redacted values that are no secret: the `state` of `#/auth/callback?state=…`, `#key=value`, the padding of an integrity fragment. A fragment's pairs are not read; a `?` behind the `#` starts a query, which is where the query of a URL joined to this one sits. - Six rules could be switched off with every test passing. Each has a row now, and twelve mutants, one per rule, each fail the test that names the rule. - A doc comment said the uuid always stays, and a test's name promised more than its rule. Refs #2448. Assisted-by: Claude Code --- crates/socket-patch-core/src/utils/redact.rs | 180 +++++++++++++------ 1 file changed, 126 insertions(+), 54 deletions(-) diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index b85d151b3..cadf67fa9 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -32,7 +32,8 @@ //! A message can quote a URL inside another, or several joined into a //! list, so every `://` is read as the start of a URL of its own: its //! userinfo, the path behind it (for a grant token) and the query behind -//! that (`…/fetch?url=https://user:token@host/x?sig=…`). In free text the +//! that (`…/fetch?url=https://user:token@host/x?sig=…`), also when a `#` +//! comes first. In free text the //! userinfo and an IPv6 host are found before the URL's end is, because //! both can hold a character that ends a quoted URL anywhere else: `'` //! and `)` are legal in a userinfo, and the messages wrap a URL in @@ -147,7 +148,8 @@ fn is_secret_param(name: &str) -> bool { /// A registry URL also holds its token at a fixed place, right below the /// ecosystem (`patch-registry////…`). What follows the /// uuid there is a package's own path, and a package can be named like a -/// uuid, which makes the patch uuid the level before the last one. +/// uuid. The first rule then takes the patch uuid for the token, so both +/// levels are cut. fn grant_tokens_in(url: &str, path: Range, spans: &mut Vec>) { let mut levels: Vec> = Vec::new(); let mut offset = path.start; @@ -178,74 +180,98 @@ fn grant_tokens_in(url: &str, path: Range, spans: &mut Vec>) } /// Byte ranges of the grant-token path levels of a Socket-served URL -/// ([`grant_tokens_in`]): those of `url`'s own path, which runs to the -/// first `?` or `#`, and those of the path behind each `://` in it, so -/// that a URL nested in another, or joined to it, is read for its own -/// token. Such a path ends at the next `?`, `#` or `&` (a nested URL can -/// be a query value), or where the next URL begins: before its scheme, -/// and before the `,` or `;` that joins it to this one. +/// ([`grant_tokens_in`]). The path behind every `://` is read, so that a +/// URL nested in another, or joined to it, is read for its own token: +/// +/// * as a URL of its own, to the first `?` or `#`, whatever lies between +/// (the reading of `url`'s own path; a `://` inside a path already +/// read this way adds nothing to it); +/// * as one of several, to where the next URL begins: before its scheme, +/// and before the `,` or `;` that joins it to this one; +/// * as a query value, to its first `&`. fn grant_token_spans(url: &str) -> Vec> { let mut spans = Vec::new(); - let start = authority_span(url).end; - let len = url[start..].find(['?', '#']).unwrap_or(url.len() - start); - let own = start..start + len; - grant_tokens_in(url, own.clone(), &mut spans); + let path_end = |start: usize, limit: usize| { + start + url[start..limit].find(['?', '#']).unwrap_or(limit - start) + }; let mut seps = url.match_indices("://").map(|(sep, _)| sep).peekable(); + if seps.peek().is_none() { + let start = authority_span(url).end; + grant_tokens_in(url, start..path_end(start, url.len()), &mut spans); + } + let mut read_to = 0; while let Some(sep) = seps.next() { + let start = authority_at(url, sep + 3).end; + let mut whole = None; + if start >= read_to { + read_to = path_end(start, url.len()); + grant_tokens_in(url, start..read_to, &mut spans); + whole = Some(start..read_to); + } let limit = seps.peek().map_or(url.len(), |&next| { let scheme = scheme_start(url, sep + 3, next); scheme - usize::from(scheme > sep + 3 && url[..scheme].ends_with([',', ';'])) }); - let start = authority_at(url, sep + 3).end.min(limit); - let len = url[start..limit] - .find(['?', '#', '&']) - .unwrap_or(limit - start); - let path = start..start + len; - if path != own { - grant_tokens_in(url, path, &mut spans); + let start = start.min(limit); + let path = start..path_end(start, limit); + if whole.as_ref() != Some(&path) { + grant_tokens_in(url, path.clone(), &mut spans); + } + if let Some(pair_end) = url[path.clone()].find('&') { + grant_tokens_in(url, path.start..path.start + pair_end, &mut spans); } } spans } /// Byte ranges of the secret values among the `name=value` pairs of -/// `url`: those of its query, and those behind it. +/// `url`: those of its query, which starts at the first `?` when no `#` +/// precedes it, and those of each query behind that. /// -/// The pairs start at the first `?` or `#` and are separated by `&` and -/// `#`. What follows a `#` is read like a query because a URL nested in -/// this one, or joined to it, has its query there, and a fragment can -/// name a secret itself (`#access_token=…`). A `?` inside a pair starts -/// the query of a nested URL (`?url=https://h/x?token=…`): the name after -/// it is read too, and a secret value runs to the end of the pair either -/// way. +/// A `?` inside a pair starts the query of a URL nested in this one +/// (`?url=https://h/x?token=…`): the name after it is read too, and a +/// secret value runs to the end of the pair either way. A `#` ends a +/// query. What follows it is a fragment, whose own pairs are not read +/// (`#sha256=…`, a route), until a `?` in it starts the query of a URL +/// nested in the fragment or joined to this one behind it. fn secret_query_spans(url: &str) -> Vec> { let Some(q) = url.find(['?', '#']) else { return Vec::new(); }; let mut spans = Vec::new(); + let mut in_query = url.as_bytes()[q] == b'?'; let mut pos = q + 1; - for pair in url[q + 1..].split(['&', '#']) { - // Where the name that the next `=` ends starts: the pair's start, - // then right after the first `?` that follows each `=`. - let mut name = Some(0); - for (i, byte) in pair.bytes().enumerate() { - match byte { - b'?' => { - name.get_or_insert(i + 1); - } - b'=' => { - let secret = name - .take() - .is_some_and(|start| is_secret_param(&pair[start..i])); - if secret && i + 1 < pair.len() { - spans.push(pos + i + 1..pos + pair.len()); - break; + for part in url[q + 1..].split('#') { + for pair in part.split('&') { + // Where the name that the next `=` ends starts. In a query it + // is the pair's start; after the pair's first `=`, and in a + // fragment, it is right after the first `?`. + let mut name = in_query.then_some(0); + let mut restarts = !in_query; + for (i, byte) in pair.bytes().enumerate() { + match byte { + b'?' => { + in_query = true; + if restarts { + name.get_or_insert(i + 1); + } + } + b'=' => { + restarts = true; + let secret = name + .take() + .is_some_and(|start| is_secret_param(&pair[start..i])); + if secret && i + 1 < pair.len() { + spans.push(pos + i + 1..pos + pair.len()); + break; + } } + _ => {} } - _ => {} } + pos += pair.len() + 1; } - pos += pair.len() + 1; + in_query = false; } spans } @@ -688,9 +714,10 @@ mod tests { "{\"url\":\"https://h.example\",\"email\":\"bob@corp.example\"}", "{\"url\":\"https://h.example\",\"email\":\"bob@corp.example\"}", ), + // Past the host a `)` ends the URL, whatever follows it. ( - "(https://u:p@h.example/a)b@c", - "(https://@h.example/a)b@c", + "(https://u:p@h.example/a)b@c?token=abc", + "(https://@h.example/a)b@c?token=abc", ), ] { assert_eq!(redact_urls_in(text), redacted, "{text}"); @@ -775,8 +802,8 @@ mod tests { } } - /// A URL nested in another has a query and a path of its own, and a - /// fragment is read for secret names like a query. + /// A URL nested in another has a query and a path of its own, also + /// behind a `#`. A fragment's own pairs are not read. #[test] fn the_query_and_the_grant_token_of_a_nested_url_are_redacted() { for (url, redacted) in [ @@ -793,18 +820,47 @@ mod tests { "https://h/app#/callback?access_token=&state=1".to_string(), ), ( - "https://h/a.whl#sha256=0abc;https://h/b.whl?token=abc".to_string(), - "https://h/a.whl#sha256=0abc;https://h/b.whl?token=".to_string(), + "https://h/a.whl#sha256=0abc;https://h/b.whl?v=1&token=abc".to_string(), + "https://h/a.whl#sha256=0abc;https://h/b.whl?v=1&token=".to_string(), + ), + // A registry URL that is a query value ends at the next pair. + ( + format!("https://proxy/fetch?url=https://h/patch-registry/npm/GSEC/{UUID}&w=2"), + format!("https://proxy/fetch?url=https://h/patch-registry/npm//{UUID}&w=2"), + ), + // A package can hold an `&` in its name, so the path is read past it too. + ( + format!("https://proxy/fetch?url=https://h/patch/npm/a&b/1.0.0/GSEC/{UUID}/a.tgz"), + format!("https://proxy/fetch?url=https://h/patch/npm/a&b/1.0.0//{UUID}/a.tgz"), + ), + // Read as a URL of its own, its path runs on through another. + ( + format!("https://proxy/fetch?url=https://h/patch/npm/a/https://mirror/1.0.0/GSEC/{UUID}/a.tgz"), + format!("https://proxy/fetch?url=https://h/patch/npm/a/https://mirror/1.0.0//{UUID}/a.tgz"), ), - // The name of a pair is everything before its first `=`. + // The name of a query pair is everything before its first `=`, + // and a secret value runs to the end of the pair. ( "https://h/x?token?v=1".to_string(), "https://h/x?token?v=".to_string(), ), + ( + "https://h/x?token=a?b=c&v=1".to_string(), + "https://h/x?token=&v=1".to_string(), + ), + // A fragment's own pairs and its route are not a query. ( "https://h/x.whl#sha256=0abc&egg=six&subdirectory=src".to_string(), "https://h/x.whl#sha256=0abc&egg=six&subdirectory=src".to_string(), ), + ( + "https://h/x?q=1#key=value&token=abc".to_string(), + "https://h/x?q=1#key=value&token=abc".to_string(), + ), + ( + "https://h/app#/auth/callback?state=abc".to_string(), + "https://h/app#/auth/callback?state=abc".to_string(), + ), ] { assert_eq!(redact_url(&url), redacted, "{url}"); assert_eq!(redact_urls_in(&url), redacted, "in text: {url}"); @@ -812,9 +868,9 @@ mod tests { } /// A registry URL holds its token right below the ecosystem, whatever - /// the package's own path looks like, and each URL of a list has one. + /// path levels follow the uuid, and each URL of a list has one. #[test] - fn a_registry_token_is_redacted_whatever_follows_the_uuid() { + fn a_registry_token_is_redacted_by_its_place() { // A package named like a uuid: the patch uuid goes with the token, // being the level before the last uuid-shaped one. assert_eq!( @@ -844,6 +900,16 @@ mod tests { ); assert_eq!(redact_urls_in(&artifacts), redacted); assert_eq!(redact_url(&artifacts), redacted); + // A list element that ends at its uuid: the `;` that joins the + // next one is not part of the level. + assert_eq!( + redact_url(&format!( + "https://h/patch-registry/nuget/GSEC1/{UUID};https://h/patch-registry/nuget/GSEC2/{TOKEN}" + )), + format!( + "https://h/patch-registry/nuget//{UUID};https://h/patch-registry/nuget//{TOKEN}" + ) + ); } /// A comma-joined URL list (GOPROXY) is redacted element by element; @@ -862,6 +928,12 @@ mod tests { redact_urls_in("https://h/x?next=https://n/y&token=SECRET"), "https://h/x?next=https://n/y&token=" ); + // A `,` before a scheme starts the next element; a `;` does not, + // so what follows it is still the secret value. + assert_eq!( + redact_urls_in("https://a/x?token=S,https://b/y and https://a/x?token=S;https://b/y"), + "https://a/x?token=,https://b/y and https://a/x?token=" + ); } #[test] From 39f96bf073e0927ff5df8ef1fda1938320e433a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:41:08 +0000 Subject: [PATCH 6/6] Name a download's URL as one URL in its errors The registry download, the Maven fetch and two messages of `utils/http.rs` put the raw URL into a message and scanned the message afterwards, so a secret query value that holds a `)` was printed from the `)` on. Each has the URL, and names it through `redact_url`. The Maven fetch takes reqwest's text through `network_error_detail`, as the registry download does, so its error also names the cause. `network_error_detail` replaced the request URL wherever it occurs as a substring. It replaces `()`, the form reqwest writes. Refs #2448. Assisted-by: Claude Code --- crates/socket-patch-core/src/api/client.rs | 14 +++++++++----- crates/socket-patch-core/src/utils/http.rs | 13 ++++++++++--- .../src/vendor/maven_repo.rs | 19 ++++++++++++------- .../src/vendor/registry_fetch.rs | 15 +++++++++++---- 4 files changed, 42 insertions(+), 19 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 2457a949c..f92fdee6d 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -58,13 +58,17 @@ static MULTI_ORG_SHOWN: AtomicBool = AtomicBool::new(false); /// act on ("Connection refused", a DNS or TLS failure). Causes already /// spelled out by an outer message are skipped. pub(crate) fn network_error_detail(e: &reqwest::Error) -> String { - // reqwest's text names the request URL: a grant URL, or one with - // userinfo from `--api-url` / a proxy, is quoted redacted. The URL is - // taken from the error and redacted as one URL first: cut out of the - // text, it would end at a `)` that a secret query value holds. + // reqwest's text names the request URL, as `()`: a grant URL, + // or one with userinfo from `--api-url` / a proxy, is quoted redacted. + // The URL is taken from the error and redacted as one URL first: cut + // out of the text, it would end at a `)` that a secret query value + // holds. let shown = |text: String| { redact_message(match e.url() { - Some(url) => text.replace(url.as_str(), &redact_url(url.as_str())), + Some(url) => text.replace( + &format!("({url})"), + &format!("({})", redact_url(url.as_str())), + ), None => text, }) }; diff --git a/crates/socket-patch-core/src/utils/http.rs b/crates/socket-patch-core/src/utils/http.rs index 60d994713..2acf4103e 100644 --- a/crates/socket-patch-core/src/utils/http.rs +++ b/crates/socket-patch-core/src/utils/http.rs @@ -259,7 +259,7 @@ pub(crate) fn secure_url(url: &str) -> Result { .ok_or_else(|| { format!( "`{}` is not an https URL (plain http is accepted for a loopback host only)", - crate::utils::redact::redact_urls_in(url) + crate::utils::redact::redact_url(url) ) }) } @@ -339,8 +339,8 @@ fn redirect_refusal(from: &reqwest::Url, to: &reqwest::Url) -> Option { (!followed).then(|| { format!( "refusing a redirect from {} to {}, which is not an https URL", - crate::utils::redact::redact_urls_in(from.as_str()), - crate::utils::redact::redact_urls_in(to.as_str()) + crate::utils::redact::redact_url(from.as_str()), + crate::utils::redact::redact_url(to.as_str()) ) }) } @@ -477,6 +477,13 @@ mod tests { ) .unwrap(); assert!(!why.contains("hunter2"), "{why}"); + // Each side is one URL: a secret value that holds a `)` is cut whole. + let why = redirect_refusal( + &url("https://rubygems.org/gems/a-1.gem?token=ab)FROMSECRET"), + &url("http://cdn.example.test/a-1.gem?sig=ab)TOSECRET"), + ) + .unwrap(); + assert!(!why.contains("SECRET"), "{why}"); } /// Serve one raw HTTP/1.1 response on loopback and return a response diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 90729ff68..da8173828 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -2624,13 +2624,18 @@ async fn fetch_registry_bytes_unredacted(url: &str, cap: u64) -> Result, let client = super::registry_fetch::registry_client_builder(MAVEN_USER_AGENT) .build() .map_err(|e| format!("build http client: {e}"))?; - let resp = client - .get(url) - .send() - .await - .map_err(|e| format!("GET {url}: {e}"))?; + // Named as one URL, and reqwest's text through the helper that takes + // the URL from the error: cut out of a message, a URL ends at a `)` + // that a secret query value holds. + let shown = crate::utils::redact::redact_url(url); + let resp = client.get(url).send().await.map_err(|e| { + format!( + "GET {shown}: {}", + crate::api::client::network_error_detail(&e) + ) + })?; if !resp.status().is_success() { - return Err(format!("GET {url}: HTTP {}", resp.status())); + return Err(format!("GET {shown}: HTTP {}", resp.status())); } // Enforce the cap on the declared Content-Length AND on the streamed // bytes (the shared reader every other registry download uses): a @@ -2638,7 +2643,7 @@ async fn fetch_registry_bytes_unredacted(url: &str, cap: u64) -> Result, // buffered whole before the size check. crate::utils::http::read_capped(resp, cap, "Maven artifact") .await - .map_err(|e| format!("{url}: {e}")) + .map_err(|e| format!("{shown}: {e}")) } /// Write the jar + pom + their `.sha1` sidecars into the maven2 leaf dir, diff --git a/crates/socket-patch-core/src/vendor/registry_fetch.rs b/crates/socket-patch-core/src/vendor/registry_fetch.rs index cf9bd0969..8985ee802 100644 --- a/crates/socket-patch-core/src/vendor/registry_fetch.rs +++ b/crates/socket-patch-core/src/vendor/registry_fetch.rs @@ -1005,21 +1005,24 @@ pub(crate) async fn download(client: &reqwest::Client, url: &str) -> Result Result, String> { + // Named as one URL: quoted in a message and cut out of it again, it + // would end at a `)` that a secret query value holds. + let shown = crate::utils::redact::redact_url(url); if !(url.starts_with("https://") || url.starts_with("http://")) { - return Err(format!("refusing non-http(s) artifact URL `{url}`")); + return Err(format!("refusing non-http(s) artifact URL `{shown}`")); } let resp = client .get(url) .send() .await - .map_err(|e| format!("GET {url}: {}", network_error_detail(&e)))?; + .map_err(|e| format!("GET {shown}: {}", network_error_detail(&e)))?; let status = resp.status(); if !status.is_success() { - return Err(format!("GET {url}: HTTP {status}")); + return Err(format!("GET {shown}: HTTP {status}")); } crate::utils::http::read_capped(resp, MAX_DOWNLOAD_BYTES, "registry artifact") .await - .map_err(|e| format!("{url}: {e}")) + .map_err(|e| format!("{shown}: {e}")) } /// The registry client for bytes that socket-patch itself builds or @@ -2979,6 +2982,10 @@ mod tests { format!("ftp://u:pw@h.example/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz"), format!("{served}/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz?token=QSECRET"), format!("http://u:pw@{dead}/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz"), + // A secret value that holds a `)`, which ends a URL in text. + format!("ftp://h.example/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz?token=ab)QSECRET"), + format!("{served}/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz?token=ab)QSECRET"), + format!("http://{dead}/patch/npm/a/1.0.0/GRANTTOKEN/{UUID}/a.tgz?token=ab)QSECRET"), ] { let err = download(&build_registry_client(), &url).await.unwrap_err(); for needle in ["GRANTTOKEN", "u:pw", "QSECRET"] {