From c8c5b88c774959a695ef1ca55dd052a9aaf6322e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:05:22 +0000 Subject: [PATCH 01/13] Start redact-quoted-lock-urls Refs #2287. Assisted-by: Claude Code From c8f6794cbb55466b7692e0e1611f57aeaea4476f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:25:55 +0000 Subject: [PATCH 02/13] Redact URLs where a vendor refusal is built A vendored refusal quotes lock text: the source of a Cargo.lock entry, the key of a yarn.lock block, a registry. It is the `Cannot vendor` line, a `[would-refuse]` preview line and the `error` of a `--json` event, so a token in the userinfo of such a URL went to the terminal, the CI log and the stored document. `vendor::common::refused`, which every backend builds its refusals with, now redacts the URLs in its detail, as `VendorWarning::new` already does. The three refusals the npm flavor probe built by hand and the one the Maven backend rebuilt go through it. Both constructors use one helper, `redact_message`. Refs #2287. Assisted-by: Claude Code --- crates/socket-patch-core/src/utils/redact.rs | 11 +++++ crates/socket-patch-core/src/vendor/common.rs | 48 ++++++++++++++++++- .../src/vendor/maven_repo.rs | 2 +- crates/socket-patch-core/src/vendor/mod.rs | 7 +-- .../src/vendor/npm_flavor.rs | 10 ++-- 5 files changed, 64 insertions(+), 14 deletions(-) diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 5d9c105038..0e80058875 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -299,6 +299,17 @@ pub fn redact_urls_in(text: &str) -> Cow<'_, str> { Cow::Owned(out) } +/// [`redact_urls_in`] for a message its builder owns: the constructors of +/// the message types (a vendor warning or refusal, a restore's refusal, a +/// run warning) take their text through this, so a caller that quotes a +/// lockfile or a registry URL cannot forget to. +pub fn redact_message(text: String) -> String { + match redact_urls_in(&text) { + Cow::Borrowed(_) => text, + Cow::Owned(redacted) => redacted, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 60e29f93a6..dd60b9c058 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -88,10 +88,15 @@ pub(crate) fn synthesized_result( } /// Shared helper the vendor backends delegate to: a [`VendorOutcome::Refused`]. +/// +/// Every URL quoted in `detail` is redacted, as in +/// [`VendorWarning::new`]: a refusal is the `Cannot vendor …` line and the +/// `error` of a `--json` event, and what it quotes from a lockfile (a +/// Cargo source, a yarn lock key, a registry) can carry credentials. pub(crate) fn refused(code: &'static str, detail: impl Into) -> VendorOutcome { VendorOutcome::Refused { code, - detail: detail.into(), + detail: crate::utils::redact::redact_message(detail.into()), } } @@ -906,6 +911,47 @@ mod tests { use crate::hash::git_sha256::compute_git_sha256_from_bytes; + /// #2287: a refusal quotes lock text (a Cargo source, a yarn lock key, + /// a registry URL), and lands on the terminal, in CI logs and in the + /// `--json` events. Whoever builds one gets its URLs redacted, as a + /// [`VendorWarning`] does. + #[test] + fn a_refusal_never_quotes_a_credential() { + for (quoted, shown) in [ + ( + "git+https://x-access-token:ghp_S3CRET@github.com/acme/cfg-if.git?rev=0123456#0123456789abcdef", + "git+https://@github.com/acme/cfg-if.git?rev=0123456#0123456789abcdef", + ), + ( + "registry+https://bot:S3CRET@cargo.corp.example/index", + "registry+https://@cargo.corp.example/index", + ), + ( + "sparse+https://cargo.corp.example/index/?token=S3CRET", + "sparse+https://cargo.corp.example/index/?token=", + ), + ] { + let VendorOutcome::Refused { code, detail } = refused( + "vendor_source_unsupported", + format!("cfg-if@1.0.4 resolves from {quoted}; server patches require the crates.io package"), + ) else { + panic!("refused() builds a refusal"); + }; + assert_eq!(code, "vendor_source_unsupported"); + assert_eq!( + detail, + format!("cfg-if@1.0.4 resolves from {shown}; server patches require the crates.io package") + ); + } + // Text without a credential is carried as it was written. + let VendorOutcome::Refused { detail, .. } = + refused("x", "see https://docs.socket.dev/patch for more") + else { + panic!("refused() builds a refusal"); + }; + assert_eq!(detail, "see https://docs.socket.dev/patch for more"); + } + /// A manifest re-rendered in its own layout is byte-identical to itself /// whenever it is in the canonical pretty shape (what yarn / npm write): /// indent, CRLF vs LF, BOM and the trailing-newline shape all carry. diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 57fb44dd67..90729ff68b 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -1470,7 +1470,7 @@ async fn unpin_unselected( let VendorOutcome::Refused { code, detail } = outcome else { return outcome; }; - let keep = |detail: String| VendorOutcome::Refused { code, detail }; + let keep = |detail: String| refused(code, detail); if code != super::jvm::sbt_gate::MAVEN_NOT_SELECTED { return keep(detail); } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index f7713d0df6..9cc7e8ba0f 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -178,14 +178,9 @@ impl VendorWarning { /// URLs, GOPROXY / `.npmrc` / private-index registries) carry /// credentials. pub fn new(code: &'static str, detail: impl Into) -> Self { - let detail = detail.into(); - let detail = match crate::utils::redact::redact_urls_in(&detail) { - std::borrow::Cow::Borrowed(_) => detail, - std::borrow::Cow::Owned(redacted) => redacted, - }; Self { code, - detail, + detail: crate::utils::redact::redact_message(detail.into()), re_resolved: false, } } diff --git a/crates/socket-patch-core/src/vendor/npm_flavor.rs b/crates/socket-patch-core/src/vendor/npm_flavor.rs index 5c3bca20d9..3cc8857f5e 100644 --- a/crates/socket-patch-core/src/vendor/npm_flavor.rs +++ b/crates/socket-patch-core/src/vendor/npm_flavor.rs @@ -27,6 +27,7 @@ use crate::manifest::schema::PatchRecord; use crate::patch::apply::PatchSources; use crate::utils::fs::read_regular_to_string; +use super::common::refused; use super::lock_inventory::ProjectView; use super::source::PackageSource; use super::state::VendorEntry; @@ -512,16 +513,13 @@ pub async fn vendor_npm_any<'a>( let installed_dir = installed_dir.into(); let (flavor, probe_warnings) = match detect_vendorable_npm_flavor(project_root).await { Ok(found) => found, - Err((code, detail)) => return VendorOutcome::Refused { code, detail }, + Err((code, detail)) => return refused(code, detail), }; if let Some((code, detail)) = member_stray_lock_refusal(project_root).await { - return VendorOutcome::Refused { code, detail }; + return refused(code, detail); } if let Some(detail) = flavor_change_refusal(project_root, purl, flavor).await { - return VendorOutcome::Refused { - code: "vendor_flavor_changed", - detail, - }; + return refused("vendor_flavor_changed", detail); } // Every backend takes the identical 9-argument tuple; the macro collapses // the seven-way repetition (same shape as the CLI dispatcher's `vend!`). From ff7a196018a4a0ecc59229b6b7daa3c544cec75e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:25:55 +0000 Subject: [PATCH 03/13] Redact URLs in upstream restore refusals `rollback`, `remove` and a vendored takeover put a hosted pin back on its registry entry, and refuse with the reason: the sources a nuget.config maps a package to, the registry a uv.lock or pylock.toml records, or the URL of a request that failed. Credentials in any of those were printed in the `Cannot restore` line and in the `error` of the `--json` event. `FormatResult::refuse` now redacts the URLs in its reason. The JSON lookups (the npm, PyPI and Packagist documents, which a mirror variable can point at a URL with credentials) redact their errors the way the byte downloads already do. Refs #2287. Assisted-by: Claude Code --- .../src/patch/redirect/upstream/client.rs | 55 ++++++++++++++++++- .../src/patch/redirect/upstream/mod.rs | 34 +++++++++++- .../src/patch/redirect/upstream/nuget.rs | 8 +++ 3 files changed, 95 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index d8217a64a1..aa16e3785a 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -316,11 +316,24 @@ impl UpstreamClient { /// [`Self::get_json`] sending `authorization` (a private registry's /// credentials) as the `Authorization` header. reqwest drops the header - /// on a redirect to another host. + /// on a redirect to another host. Every error quotes the URL redacted, + /// as [`crate::vendor::registry_fetch::download`]'s do: a mirror variable (`SOCKET_NPM_REGISTRY`, + /// `SOCKET_PYPI_JSON_API`, `SOCKET_PACKAGIST_URL`) or a project's + /// registry can carry credentials in it. async fn get_json_authorized( &self, url: &str, authorization: Option<&str>, + ) -> Result { + self.get_json_unredacted(url, authorization) + .await + .map_err(crate::utils::redact::redact_message) + } + + async fn get_json_unredacted( + &self, + url: &str, + authorization: Option<&str>, ) -> Result { let _permit = self.permit().await; let mut request = self.http.get(url).header("accept", "application/json"); @@ -943,6 +956,46 @@ pub(crate) mod peak_server { mod tests { use super::*; + /// #2287: a JSON lookup's error names the URL it asked without the + /// credentials a mirror variable or a project's registry put in it: + /// an HTTP error status, a body that is not JSON, and a transport + /// failure (reqwest's own text). + #[tokio::test] + async fn a_failed_json_lookup_never_quotes_a_credential() { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(matchers::path("/left-pad/1.3.0")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + Mock::given(matchers::path("/left-pad/1.3.1")) + .respond_with(ResponseTemplate::new(200).set_body_string("")) + .mount(&server) + .await; + let served = server.uri().replace("http://", "http://bot:S3CRET@"); + // A port nothing listens on: the connect fails. + let dead = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + format!("http://bot:S3CRET@{}", listener.local_addr().unwrap()) + }; + let client = UpstreamClient::new(false); + for (base, version, says) in [ + (&served, "1.3.0", "HTTP 404"), + (&served, "1.3.1", "is not JSON"), + (&dead, "1.3.0", "GET http://@127.0.0.1"), + ] { + let err = client + .npm_dist_on(base, "left-pad", version) + .await + .unwrap_err(); + assert!(!err.contains("S3CRET"), "{err}"); + assert!( + err.contains("http://@127.0.0.1") && err.contains(says), + "the error still says where the request went: {err}" + ); + } + } + /// #1220: a client built with a cap of 1 (what a tight /// `RLIMIT_NOFILE` gives) sends its lookups strictly one at a time, /// however many the caller starts at once. diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 7be7d792ad..5477e36039 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -825,10 +825,15 @@ pub(crate) struct FormatResult { } impl FormatResult { + /// Refuse the pin `uuid` for `why`, unless it is refused already. + /// Every URL quoted in `why` is redacted: it is the `Cannot restore …` + /// line and the `error` of a `--json` event, and what it quotes (a + /// `nuget.config` source, a lock's registry, the URL of a failed + /// request to a mirror) can carry credentials. pub(crate) fn refuse(&mut self, uuid: &str, why: impl Into) { self.refused .entry(uuid.to_string()) - .or_insert_with(|| why.into()); + .or_insert_with(|| crate::utils::redact::redact_message(why.into())); } fn merge(&mut self, other: FormatResult) { @@ -1258,6 +1263,33 @@ mod route_sweep_tests; mod tests { use super::checkout_remedy; + /// #2287: a restore's refusal quotes what the project's files and the + /// mirror variables name (a `nuget.config` source, a lock's registry, + /// the URL of a failed request). It is the `Cannot restore …` line + /// and the `error` of a `--json` event. + #[test] + fn a_refusal_never_quotes_a_credential() { + let mut result = super::FormatResult::default(); + result.refuse( + "u1", + "p resolves from nuget.org (https://api.nuget.org/v3/index.json), corp \ + (https://bot:S3CRET@repo.corp.example/nuget/v3/index.json) under nuget.config", + ); + result.refuse( + "u2", + "pylock.toml: the lock's registry https://repo.corp.example/simple?token=S3CRET is not PyPI", + ); + assert_eq!( + result.refused["u1"], + "p resolves from nuget.org (https://api.nuget.org/v3/index.json), corp \ + (https://@repo.corp.example/nuget/v3/index.json) under nuget.config" + ); + assert_eq!( + result.refused["u2"], + "pylock.toml: the lock's registry https://repo.corp.example/simple?token= is not PyPI" + ); + } + #[test] fn bun_lock_remedies_name_the_forced_reinstall() { for file in ["bun.lockb", "bun.lock", "packages/app/bun.lockb"] { diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs b/crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs index 15a512949d..0f91f90d99 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs @@ -688,6 +688,13 @@ mod tests { false, "corp (https://corp.example/v3/index.json)", ), + // #2287: a source's credentials stay out of the refusal. + ( + hosted_config(&routed_to_corp) + .replace("https://corp.example", "https://bot:S3CRET@corp.example"), + false, + "corp (https://@corp.example/v3/index.json)", + ), (two_patterns, false, "not to the one package"), ( USER_MAPPING.to_string(), @@ -701,6 +708,7 @@ mod tests { panic!("{needle}: restored"); }; assert!(why.contains(needle), "{needle}: {why}"); + assert!(!why.contains("S3CRET"), "{why}"); assert!(why.contains("git checkout -- nuget.config"), "{why}"); assert_eq!(after, config, "{needle}"); assert_eq!(lock_after, lock(PATCHED), "{needle}"); From 87446844e9843dddee95f9c683f335f892c9b12b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:25:55 +0000 Subject: [PATCH 04/13] Redact URLs in the warnings a run reports A hosted rewriter names the lock entry it leaves alone: a yarn.lock block installed from git, a Poetry source, a requirements direct reference. With a token in that URL the warning carried it to stderr, to `warnings[].detail` of the `--json` document, and to the result of the in-memory engine. The warning is now redacted where it enters each reported type: `RunWarning::new` for the CLI (its stderr lines are printed from the same values), and `rewrite_warnings_json` and `EngineWarning::new` for the in-memory engine. A `RewriteWarning` itself keeps the lock's text, which the engine compares against lock keys. Refs #2287. Assisted-by: Claude Code --- crates/socket-patch-cli/src/json_envelope.rs | 47 ++++++++++++++++-- .../src/hosted/memory/types.rs | 29 ++++++++++- crates/socket-patch-core/src/hosted/render.rs | 48 ++++++++++++++++++- .../src/patch/redirect/mod.rs | 23 +++++++++ .../src/patch/redirect/poetry.rs | 30 ++++++++++++ .../src/patch/redirect/requirements.rs | 20 ++++++++ 6 files changed, 189 insertions(+), 8 deletions(-) diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index cc3d928d09..1182685e61 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -762,10 +762,15 @@ pub struct RunWarning { } impl RunWarning { + /// Every URL quoted in `detail` is redacted + /// ([`socket_patch_core::utils::redact::redact_urls_in`]): a run + /// warning is printed on stderr and stored with the `--json` document, + /// and one that quotes a lock entry (a key, a `resolved`, a private + /// index) would carry the credentials that entry holds. pub fn new(code: impl Into, detail: impl Into) -> Self { Self { code: code.into(), - detail: detail.into(), + detail: socket_patch_core::utils::redact::redact_message(detail.into()), } } } @@ -789,6 +794,37 @@ mod tests { use super::*; use socket_patch_core::patch::sidecars::{SidecarFile, SidecarFileAction}; + /// #2287: a run warning quotes lock text (a yarn lock key, a Poetry + /// source, a requirements reference). Its URLs are redacted where the + /// warning is built, for stderr and the `--json` document alike. + #[test] + fn a_run_warning_never_quotes_a_credential() { + let mut env = Envelope::new(Command::Scan); + env.warn( + "redirect_poetry_lock_unsupported", + "poetry.lock: refusing to replace an existing Poetry source \ + (legacy https://bot:S3CRET@pypi.corp.example/simple) for six", + ); + env.warn( + "redirect_requirements_direct_reference", + "requirements.txt installs six@1.16.0 from the direct reference \ + https://pypi.corp.example/six-1.16.0-py2.py3-none-any.whl?token=S3CRET; \ + refusing to overwrite a user-authored source (not rewritten)", + ); + let details: Vec<&str> = env.warnings.iter().map(|w| w.detail.as_str()).collect(); + assert_eq!( + details, + [ + "poetry.lock: refusing to replace an existing Poetry source \ + (legacy https://@pypi.corp.example/simple) for six", + "requirements.txt installs six@1.16.0 from the direct reference \ + https://pypi.corp.example/six-1.16.0-py2.py3-none-any.whl?token=; \ + refusing to overwrite a user-authored source (not rewritten)", + ] + ); + assert!(!env.to_pretty_json().contains("S3CRET")); + } + const ACTIONS: [(PatchAction, &str); 10] = [ (PatchAction::Discovered, "discovered"), (PatchAction::Downloaded, "downloaded"), @@ -1183,10 +1219,11 @@ mod tests { v["vex"] ); - env.vex.as_mut().unwrap().warnings.push(RunWarning { - code: "product_not_iri".into(), - detail: "product is not an IRI".into(), - }); + env.vex + .as_mut() + .unwrap() + .warnings + .push(RunWarning::new("product_not_iri", "product is not an IRI")); let v = env.to_value(); assert_eq!(v["vex"]["warnings"][0]["code"], "product_not_iri"); assert_eq!(v["vex"]["warnings"][0]["detail"], "product is not an IRI"); diff --git a/crates/socket-patch-core/src/hosted/memory/types.rs b/crates/socket-patch-core/src/hosted/memory/types.rs index fa81876e81..327b2cbfc7 100644 --- a/crates/socket-patch-core/src/hosted/memory/types.rs +++ b/crates/socket-patch-core/src/hosted/memory/types.rs @@ -251,10 +251,14 @@ pub struct EngineWarning { } impl EngineWarning { + /// Every URL quoted in `detail` is redacted + /// ([`crate::utils::redact::redact_urls_in`]): the engine's result is + /// stored and shown by its caller, and a warning that quotes a + /// project's files can carry the credentials they hold. pub fn new(code: impl Into, detail: impl Into, root: Option<&str>) -> Self { Self { code: code.into(), - detail: detail.into(), + detail: crate::utils::redact::redact_message(detail.into()), project_root: root.map(str::to_string), } } @@ -547,3 +551,26 @@ mod base64_bytes { .map_err(serde::de::Error::custom) } } + +#[cfg(test)] +mod tests { + use super::EngineWarning; + + /// #2287: the engine's result is stored and shown by its caller. A + /// warning in it never carries a credential a project file holds. + #[test] + fn a_warning_never_quotes_a_credential() { + let w = EngineWarning::new( + "redirect_copy_unpatched", + "yarn.lock: lock entry `\"left-pad@git+https://x-access-token:ghp_S3CRET@github.com/acme/left-pad.git\"` \ + installs from git", + Some("apps/web"), + ); + assert_eq!( + w.detail, + "yarn.lock: lock entry `\"left-pad@git+https://@github.com/acme/left-pad.git\"` \ + installs from git" + ); + assert_eq!(w.project_root.as_deref(), Some("apps/web")); + } +} diff --git a/crates/socket-patch-core/src/hosted/render.rs b/crates/socket-patch-core/src/hosted/render.rs index 5131ec0e29..ac29a06fd9 100644 --- a/crates/socket-patch-core/src/hosted/render.rs +++ b/crates/socket-patch-core/src/hosted/render.rs @@ -11,11 +11,19 @@ pub fn skipped_json(skipped: &SkippedPatch) -> serde_json::Value { serde_json::to_value(skipped).expect("SkippedPatch is plain strings: serialization cannot fail") } -/// Warnings as `{code, detail}` JSON. +/// Warnings as `{code, detail}` JSON. Every URL quoted in a `detail` is +/// redacted ([`crate::utils::redact::redact_urls_in`]): a rewriter names +/// the lock entry it left alone, and a lock key, a `resolved` or a +/// private index recorded there can carry credentials. pub fn rewrite_warnings_json(warnings: &[RewriteWarning]) -> Vec { warnings .iter() - .map(|w| serde_json::json!({ "code": w.code, "detail": w.detail })) + .map(|w| { + serde_json::json!({ + "code": w.code, + "detail": crate::utils::redact::redact_urls_in(&w.detail), + }) + }) .collect() } @@ -79,3 +87,39 @@ pub fn redirect_json_block( /// The `errorCode` of an `unpinned` `redirect.patches[]` row: the patch was /// granted, but no lockfile entry pinning it could be rewritten. pub const REDIRECT_UNCONFIRMED: &str = "redirect_unconfirmed"; + +#[cfg(test)] +mod tests { + use super::*; + + /// #2287: a warning's detail is reported with its URLs redacted, and + /// is otherwise the rewriter's own text. + #[test] + fn a_reported_warning_never_quotes_a_credential() { + let warning = |detail: &str| RewriteWarning { + code: "redirect_yarn_classic_git_skipped".into(), + detail: detail.into(), + }; + let reported = rewrite_warnings_json(&[ + warning( + "Lock entry `\"left-pad@git+https://x-access-token:ghp_S3CRET@github.com/acme/left-pad.git\"` \ + installs left-pad@1.3.0 from git", + ), + warning("No package-lock.json present; see https://docs.socket.dev/patch"), + ]); + assert_eq!( + reported, + [ + serde_json::json!({ + "code": "redirect_yarn_classic_git_skipped", + "detail": "Lock entry `\"left-pad@git+https://@github.com/acme/left-pad.git\"` \ + installs left-pad@1.3.0 from git", + }), + serde_json::json!({ + "code": "redirect_yarn_classic_git_skipped", + "detail": "No package-lock.json present; see https://docs.socket.dev/patch", + }), + ] + ); + } +} diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 57c014fb0f..71f6429149 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -21021,6 +21021,29 @@ mod tests { assert_eq!(codes, ["redirect_yarn_classic_git_skipped"]); assert!(r.warnings[0].detail.contains("git"), "{:?}", r.warnings); + // #2287: the key of a private git remote carries the token CI + // cloned it with. The warning a run reports names the entry + // without it. + files.insert( + "yarn.lock".to_string(), + format!("# yarn lockfile v1\n\n\n{git_block}").replace( + "https://github.com", + "https://x-access-token:ghp_S3CRET@github.com", + ), + ); + let r = rewrite_registry_redirect(&files, std::slice::from_ref(&ovr)); + let reported = crate::hosted::render::rewrite_warnings_json(&r.warnings); + assert_eq!(reported.len(), 1, "{reported:?}"); + assert_eq!(reported[0]["code"], "redirect_yarn_classic_git_skipped"); + let detail = reported[0]["detail"].as_str().unwrap(); + assert!(!detail.contains("S3CRET"), "{detail}"); + assert!( + detail.contains( + "`\"left-pad@git+https://@github.com/stevemao/left-pad.git#v1.3.0\"`" + ), + "{detail}" + ); + // Git block beside a registry block: the registry block is wired, // the git block left alone, and the uuid flagged so in-run VEX // verifies instead of assuming. diff --git a/crates/socket-patch-core/src/patch/redirect/poetry.rs b/crates/socket-patch-core/src/patch/redirect/poetry.rs index 223a8fdf14..7c330dd6fc 100644 --- a/crates/socket-patch-core/src/patch/redirect/poetry.rs +++ b/crates/socket-patch-core/src/patch/redirect/poetry.rs @@ -495,6 +495,36 @@ mod equivalence_tests { } } + /// #2287: the lock records a private index with the credentials it was + /// locked with. The refusal names the index without them. + #[test] + fn a_refused_private_index_is_named_without_its_credentials() { + let lock = fixture("2.2.1").replacen( + "\n[metadata]", + "\n[package.source]\ntype = \"legacy\"\nurl = \"https://bot:S3CRET@pypi.corp.example/simple\"\nreference = \"corp\"\n\n[metadata]", + 1, + ); + let files = BTreeMap::from([("poetry.lock".to_string(), lock)]); + let deps = [dep("urllib3", "1.26.18", Some(SHA), 0)]; + let got = crate::patch::redirect::rewrite_registry_redirect(&files, &deps); + assert!(got.files.is_empty(), "{:?}", got.warnings); + let reported = crate::hosted::render::rewrite_warnings_json(&got.warnings); + let details: Vec<&str> = reported + .iter() + .filter(|w| w["code"] == "redirect_poetry_lock_unsupported") + .filter_map(|w| w["detail"].as_str()) + .collect(); + assert_eq!(details.len(), 1, "{reported:?}"); + assert!( + details[0].contains( + "an existing Poetry source (legacy https://@pypi.corp.example/simple)" + ), + "{}", + details[0] + ); + assert!(!format!("{reported:?}").contains("S3CRET"), "{reported:?}"); + } + /// A dozen patched packages in one lock cost one whole-lock render and /// re-parse, not one per package (#760). #[test] diff --git a/crates/socket-patch-core/src/patch/redirect/requirements.rs b/crates/socket-patch-core/src/patch/redirect/requirements.rs index 75a28558a2..2adb0c3309 100644 --- a/crates/socket-patch-core/src/patch/redirect/requirements.rs +++ b/crates/socket-patch-core/src/patch/redirect/requirements.rs @@ -878,6 +878,26 @@ mod tests { assert!(result.warnings[0].detail.contains(location)); assert!(result.confirmed_requirements_uuids.is_empty()); } + // #2287: a private mirror's reference carries its credentials. The + // warning a run reports names the file without them. + let result = rewrite_registry_redirect( + &input("requests @ https://bot:S3CRET@mirror.internal/requests-2.28.1-py3-none-any.whl?token=QS3CRET\n"), + &[patch()], + ); + let reported = crate::hosted::render::rewrite_warnings_json(&result.warnings); + assert_eq!(reported.len(), 1, "{reported:?}"); + assert_eq!( + reported[0]["code"], + "redirect_requirements_direct_reference" + ); + let detail = reported[0]["detail"].as_str().unwrap(); + assert!(!detail.contains("S3CRET"), "{detail}"); + assert!( + detail.contains( + "https://@mirror.internal/requests-2.28.1-py3-none-any.whl?token=" + ), + "{detail}" + ); // A user reference to another release is not this patch's entry. let result = rewrite_registry_redirect( &input("requests @ https://mirror.internal/requests-2.32.0-py3-none-any.whl\n"), From abe1e7ed59698de1e6113a1b10ec3c5fbc457761 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:25:55 +0000 Subject: [PATCH 05/13] Redact the Gradle wrapper URL in a scan note A wrapper whose `distributionUrl` names a distribution that is not unpacked yet is reported in the `gradle_maven_local_undetermined` note of every scan of the build. A distribution server that needs credentials takes them in that URL, so the note printed them. Refs #2287. Assisted-by: Claude Code --- .../src/crawlers/gradle_cache.rs | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/crawlers/gradle_cache.rs b/crates/socket-patch-core/src/crawlers/gradle_cache.rs index b5d1549eb8..3744ca8fef 100644 --- a/crates/socket-patch-core/src/crawlers/gradle_cache.rs +++ b/crates/socket-patch-core/src/crawlers/gradle_cache.rs @@ -894,9 +894,11 @@ pub fn init_scripts_for_build(home: &GradleHome, build_root: &Path) -> InitScrip let mut dirs = vec![home.user_home.join("init.d")]; match dist_init_dirs(&dists, wrapper.name()) { Some(found) => dirs.extend(found), + // The URL is shown redacted: a distribution server that needs + // credentials takes them in `distributionUrl`. None if !wrapper.is_stock() => out.unreadable.push(format!( "wrapper distribution {} (not unpacked under {})", - wrapper.url, + crate::utils::redact::redact_url(&wrapper.url), dists.display() )), None => {} @@ -1012,6 +1014,39 @@ pub fn locked_gavs(cwd: &Path) -> BTreeSet { mod tests { use super::*; + /// #2287: a wrapper's distribution server takes its credentials in + /// `distributionUrl`. The note that the distribution is not unpacked + /// yet is printed on every scan of the build, so it names the URL + /// without them. + #[test] + fn a_wrapper_distribution_is_named_without_its_credentials() { + let tmp = tempfile::tempdir().unwrap(); + let build = tmp.path().join("build"); + std::fs::create_dir_all(build.join("gradle/wrapper")).unwrap(); + std::fs::write( + build.join("gradle/wrapper/gradle-wrapper.properties"), + "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\n\ + distributionUrl=https\\://bot\\:S3CRET@repo.corp.example/gradle-8.14.3-bin.zip\n", + ) + .unwrap(); + let user_home = tmp.path().join("home"); + let home = GradleHome { + files21: crate::gradle::home::files21_of_user_home(&user_home), + user_home, + ro_files21: None, + gradle_home: None, + }; + let unreadable = init_scripts_for_build(&home, &build).unreadable; + assert_eq!(unreadable.len(), 1, "{unreadable:?}"); + assert!( + unreadable[0].starts_with( + "wrapper distribution https://@repo.corp.example/gradle-8.14.3-bin.zip \ + (not unpacked under " + ), + "{unreadable:?}" + ); + } + /// `Properties.load` drops one leading UTF-8 BOM (#905); the bytes of a /// second one are ISO-8859-1 content of the first key. #[test] From 37cc8d7f3822ea60261b94a2d467939c7804e77a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:25:55 +0000 Subject: [PATCH 06/13] Test that no run prints a lock's credential Three file-only projects each hold one token in a URL their package manager writes or reads: a yarn classic lock keyed by a git remote, a Cargo.lock git source and a requirements direct reference. `scan` and `get` run over them in hosted and vendored mode, plain, with `--json` and with `--dry-run`, and neither stream may carry the token. Every run must still name the entry, with the credential redacted. Refs #2287. Assisted-by: Claude Code --- crates/socket-patch-cli/tests/scan/main.rs | 1 + .../tests/scan/quoted_url_credentials.rs | 233 ++++++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 crates/socket-patch-cli/tests/scan/quoted_url_credentials.rs diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index 00a6db5cf4..b68542255b 100644 --- a/crates/socket-patch-cli/tests/scan/main.rs +++ b/crates/socket-patch-cli/tests/scan/main.rs @@ -31,6 +31,7 @@ mod hosted_symlinked_files; mod hosted_wheel_metadata_order; mod hosted_yarn_berry_manifest; mod hosted_yarn_classic_sha1; +mod quoted_url_credentials; mod scan_batch_sizing_e2e; mod scan_ecosystems_scope_e2e; mod scan_failure_paths; diff --git a/crates/socket-patch-cli/tests/scan/quoted_url_credentials.rs b/crates/socket-patch-cli/tests/scan/quoted_url_credentials.rs new file mode 100644 index 0000000000..27c9f7b815 --- /dev/null +++ b/crates/socket-patch-cli/tests/scan/quoted_url_credentials.rs @@ -0,0 +1,233 @@ +//! A URL a project's own lockfile or manifest holds can carry a +//! credential (`https://user:token@host/…`). A message that quotes the +//! entry must not copy that credential to the terminal, a CI log or the +//! `--json` document (#2287). +//! +//! Each case plants one token in a file-only project, runs the built +//! binary against a wiremock patch API, and reads both streams back. + +use std::path::Path; + +use wiremock::MockServer; + +use crate::common; +use crate::hosted_fixture::*; + +/// The planted credential. No message may carry it. +const SECRET: &str = "S3CRETTOKEN0123456789"; + +/// A project whose files quote one URL with [`SECRET`] in it, and the +/// patch the API offers for the package that URL installs. +struct Case { + purl: &'static str, + /// Writes the project under the given root. + project: fn(&Path), + /// What the quoted URL reads as once its credential is redacted. A run + /// that says nothing of the entry proves nothing, so each run must + /// print this. + shown: &'static str, +} + +/// Yarn classic, with the fixture's package locked from a private git +/// remote: the lock's key and `resolved` carry the token CI cloned with. +fn yarn_classic_git(root: &Path) { + write_yarn_classic_project(root, Some("yarn@1.22.22")); + let remote = format!("git+https://x-access-token:ghp_{SECRET}@github.com/acme/{NAME}.git"); + std::fs::write( + root.join("yarn.lock"), + format!( + "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n\ + # yarn lockfile v1\n\n\n\ + \"{NAME}@{remote}\":\n version \"{VERSION}\"\n \ + resolved \"{remote}#0123456789abcdef0123456789abcdef01234567\"\n" + ), + ) + .unwrap(); +} + +/// Cargo, with `cfg-if` locked from a private git fork. +fn cargo_git(root: &Path) { + let remote = format!("https://x-access-token:ghp_{SECRET}@github.com/acme/cfg-if.git"); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap(); + std::fs::write( + root.join("Cargo.toml"), + format!( + "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\ + [dependencies]\ncfg-if = {{ git = \"{remote}\", rev = \"0123456\" }}\n" + ), + ) + .unwrap(); + std::fs::write( + root.join("Cargo.lock"), + format!( + "# This file is automatically @generated by Cargo.\n\ + # It is not intended for manual editing.\nversion = 3\n\n\ + [[package]]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\n \"cfg-if\",\n]\n\n\ + [[package]]\nname = \"cfg-if\"\nversion = \"1.0.4\"\n\ + source = \"git+{remote}?rev=0123456#0123456789abcdef0123456789abcdef01234567\"\n" + ), + ) + .unwrap(); +} + +/// pip, with `six` installed from a private mirror by direct reference. +fn requirements_direct_reference(root: &Path) { + std::fs::write( + root.join("requirements.txt"), + format!( + "six @ https://bot:{SECRET}@pypi.corp.example/packages/six-1.16.0-py2.py3-none-any.whl\n" + ), + ) + .unwrap(); +} + +const YARN: Case = Case { + purl: PURL, + project: yarn_classic_git, + shown: "git+https://@github.com/acme/covgap-hosted.git", +}; +const CARGO: Case = Case { + purl: "pkg:cargo/cfg-if@1.0.4", + project: cargo_git, + shown: "git+https://@github.com/acme/cfg-if.git", +}; +const PIP: Case = Case { + purl: "pkg:pypi/six@1.16.0", + project: requirements_direct_reference, + shown: "https://@pypi.corp.example/packages/six-1.16.0-py2.py3-none-any.whl", +}; + +/// A patch API that offers one free patch for the case's package and +/// grants its hosted artifact. +async fn patch_api(case: &Case) -> MockServer { + let server = MockServer::start().await; + mock_discovery(&server, case.purl, UUID).await; + mock_view(&server, UUID, case.purl).await; + if case.purl == PURL { + mock_served_classic_reference(&server).await; + } else { + let url = format!( + "{}/patch/x/22222222-2222-4222-8222-222222222222/{UUID}/six-1.16.0-py2.py3-none-any.whl", + server.uri() + ); + mock_reference_results( + &server, + json!({ + UUID: { + "status": "granted", + "url": url, + "purl": case.purl, + "artifacts": [{ + "kind": "tarball", + "url": url, + "integrity": { "sha256": "c".repeat(64) } + }], + "registryOverride": null + } + }), + ) + .await; + } + server +} + +/// Run `command` (with `--mode ` and the API arguments) over a fresh +/// copy of the case's project and read both streams: `Err` with what is +/// wrong when the token is printed, or when the run does not name the +/// entry in its redacted form. +async fn run_quotes_without_the_token( + case: &Case, + mode: &str, + command: &[&str], +) -> Result<(), String> { + let server = patch_api(case).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("proj"); + std::fs::create_dir_all(&root).unwrap(); + (case.project)(&root); + let cwd = root.to_str().unwrap().to_string(); + let api = server.uri(); + let mut args: Vec<&str> = command.to_vec(); + args.extend([ + "--mode", + mode, + "--yes", + "--cwd", + &cwd, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + ]); + let (code, stdout, stderr) = common::run_with_env(&root, &args, &[]); + let run = format!("{} --mode {mode} (exit {code})", command.join(" ")); + let both = format!("{stdout}\n{stderr}"); + if both.contains(SECRET) { + let line = both.lines().find(|l| l.contains(SECRET)).unwrap_or(""); + return Err(format!("{run}: TOKEN PRINTED\n {}", line.trim())); + } + if !both.contains(case.shown) { + return Err(format!( + "{run}: the run does not name `{}`\nstdout:\n{stdout}\nstderr:\n{stderr}", + case.shown + )); + } + Ok(()) +} + +/// Every run of `runs` quotes its entry without the token. All of them +/// are run before any is reported, so one failure lists every leak. +async fn assert_no_run_prints_the_token(runs: &[(&Case, &str, &[&str])]) { + let mut wrong = Vec::new(); + for (case, mode, command) in runs { + if let Err(why) = run_quotes_without_the_token(case, mode, command).await { + wrong.push(why); + } + } + assert!( + wrong.is_empty(), + "{} of {} runs:\n{}", + wrong.len(), + runs.len(), + wrong.join("\n") + ); +} + +/// Hosted mode leaves a git lock entry and a direct reference alone and +/// warns about each, on stderr and in `warnings[].detail`. +#[tokio::test] +async fn a_hosted_warning_quotes_a_lock_entry_without_its_token() { + let mut runs: Vec<(&Case, &str, &[&str])> = Vec::new(); + for case in [&YARN, &PIP] { + runs.push((case, "hosted", &["scan"])); + runs.push((case, "hosted", &["scan", "--json"])); + runs.push((case, "hosted", &["scan", "--dry-run"])); + } + runs.push((&YARN, "hosted", &["get", YARN.purl])); + runs.push((&YARN, "hosted", &["get", YARN.purl, "--json"])); + runs.push((&PIP, "hosted", &["get", PIP.purl])); + runs.push((&PIP, "hosted", &["get", PIP.purl, "--json"])); + assert_no_run_prints_the_token(&runs).await; +} + +/// Vendored mode refuses a package the lock installs from git, as an +/// `Error:` line, an `error` of `events[]` and, for yarn, a +/// `[would-refuse]` preview line (the preview does not read a Cargo +/// entry's source). +#[tokio::test] +async fn a_vendored_refusal_quotes_a_lock_entry_without_its_token() { + let mut runs: Vec<(&Case, &str, &[&str])> = Vec::new(); + for case in [&YARN, &CARGO] { + runs.push((case, "vendored", &["scan"])); + runs.push((case, "vendored", &["scan", "--json"])); + } + runs.push((&YARN, "vendored", &["scan", "--dry-run"])); + runs.push((&YARN, "vendored", &["get", YARN.purl])); + runs.push((&YARN, "vendored", &["get", YARN.purl, "--json"])); + runs.push((&CARGO, "vendored", &["get", CARGO.purl])); + runs.push((&CARGO, "vendored", &["get", CARGO.purl, "--json"])); + assert_no_run_prints_the_token(&runs).await; +} From 6bb33bf59bf7dd3797b2bf70e2399aa7287f648f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:00:44 +0000 Subject: [PATCH 07/13] Fix the redactor's panic on non-ASCII text `redact_urls_in` looks back from a `://` for the start of the scheme and stepped one byte past the character it stopped on. With a character of more than one byte right before the scheme (a curly quote, an accented letter in a lock key or a manifest value) it then sliced inside that character and panicked. Vendor warnings and download errors already ran project text through it; the refusals and run warnings this branch redacts made the panic reachable from every scan of a Gradle build whose wrapper URL has such a character: exit 101 and no `--json` document, where main exits 0. The scan now steps over the whole character. Refs #2287. Assisted-by: Claude Code --- crates/socket-patch-core/src/utils/redact.rs | 41 +++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 0e80058875..0de5487c2e 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -237,11 +237,14 @@ fn ends_url(c: char) -> bool { } /// Start of the scheme that ends at `sep` (the byte offset of a `://`), -/// scanning back no further than `floor`. +/// scanning back no further than `floor`: right after the last character +/// before `sep` that no scheme can hold, however many bytes it takes. fn scheme_start(text: &str, floor: usize, sep: usize) -> usize { text[floor..sep] - .rfind(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))) - .map_or(floor, |j| floor + j + 1) + .char_indices() + .rev() + .find(|(_, c)| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))) + .map_or(floor, |(j, c)| floor + j + c.len_utf8()) } /// Where a URL starting with the `://` at `sep` and running to at most @@ -299,10 +302,10 @@ pub fn redact_urls_in(text: &str) -> Cow<'_, str> { Cow::Owned(out) } -/// [`redact_urls_in`] for a message its builder owns: the constructors of +/// [`redact_urls_in`] for a message its builder owns. The constructors of /// the message types (a vendor warning or refusal, a restore's refusal, a -/// run warning) take their text through this, so a caller that quotes a -/// lockfile or a registry URL cannot forget to. +/// run warning) take their text through this, so what is built with one +/// of them is redacted whatever its caller quotes. pub fn redact_message(text: String) -> String { match redact_urls_in(&text) { Cow::Borrowed(_) => text, @@ -439,6 +442,32 @@ mod tests { assert!(matches!(redact_urls_in(none), Cow::Borrowed(_))); } + /// The text around a URL is a project's own: a lock key, a manifest + /// value, a path. A character of more than one byte right before the + /// scheme (or before the `://` itself) is not part of the URL, and the + /// scan for the scheme's start steps over all of its bytes. + #[test] + fn text_that_is_not_ascii_before_a_url_is_kept() { + for (text, redacted) in [ + ("see “https://u:p@h/x”", "see “https://@h/x”"), + ( + "(legacy é://bot:TOKEN@pypi.corp.example/simple)", + "(legacy é://@pypi.corp.example/simple)", + ), + ( + "résumé→https://u:p@h/x, 日本語://u:p@h/y", + "résumé→https://@h/x, 日本語://@h/y", + ), + ( + "GOPROXY=https://a.example,é,https://u:p@b.example", + "GOPROXY=https://a.example,é,https://@b.example", + ), + ("no credential é://h/x here", "no credential é://h/x here"), + ] { + assert_eq!(redact_urls_in(text), redacted, "{text}"); + } + } + /// A comma-joined URL list (GOPROXY) is redacted element by element; /// a URL nested in a query is still part of its URL. #[test] From 57a1afe95d5a096d49511fda46d3a1c4ee1d900f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:00:44 +0000 Subject: [PATCH 08/13] Redact URLs in vex's discovery notes `vex` reports a Socket-wired lock entry it cannot attribute and quotes the entry beside it: for a yarn classic lock, the key of a block that installs the same release from git. With a token in that remote the note printed it on stderr and in `warnings[].detail`. `note_warning`, which every advisory of `vex` is recorded through, built its `RunWarning` by hand and so skipped the constructor that redacts. It now calls `RunWarning::new`; the stderr lines are printed from the same values. Refs #2287. Assisted-by: Claude Code --- crates/socket-patch-cli/src/commands/vex.rs | 8 +-- crates/socket-patch-cli/src/json_envelope.rs | 10 +-- crates/socket-patch-cli/tests/vex/main.rs | 1 + .../tests/vex/quoted_url_credentials.rs | 66 +++++++++++++++++++ 4 files changed, 76 insertions(+), 9 deletions(-) create mode 100644 crates/socket-patch-cli/tests/vex/quoted_url_credentials.rs diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index fac342b07c..6a8f0792da 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2221,12 +2221,10 @@ fn vendored_out_of_sync_detail(purl: &str, copies: &[&Path], notes: &str) -> Str /// with the others of its kind ([`flush_warnings`]): nothing prints while /// the run works, so its status line stays whole, and forty advisories of /// one kind are not forty lines. Under `--silent` only the envelope copy -/// survives (warnings are not errors). +/// survives (warnings are not errors). Built with [`RunWarning::new`], so +/// a discovery note that quotes a lock entry carries no credential of it. fn note_warning(warnings: &mut Vec, _common: &GlobalArgs, code: &str, detail: String) { - warnings.push(RunWarning { - code: code.to_string(), - detail, - }); + warnings.push(RunWarning::new(code, detail)); } /// How many advisories of one kind, and how many names, a human run diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index 1182685e61..6fdd27d29f 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -764,9 +764,11 @@ pub struct RunWarning { impl RunWarning { /// Every URL quoted in `detail` is redacted /// ([`socket_patch_core::utils::redact::redact_urls_in`]): a run - /// warning is printed on stderr and stored with the `--json` document, - /// and one that quotes a lock entry (a key, a `resolved`, a private - /// index) would carry the credentials that entry holds. + /// warning is stored with the `--json` document, and the hosted scan + /// and `vex` print their stderr lines from the same values. One that + /// quotes a lock entry (a key, a `resolved`, a private index) would + /// carry the credentials that entry holds. A warning built as a + /// struct literal, or printed before it is built, does not pass here. pub fn new(code: impl Into, detail: impl Into) -> Self { Self { code: code.into(), @@ -796,7 +798,7 @@ mod tests { /// #2287: a run warning quotes lock text (a yarn lock key, a Poetry /// source, a requirements reference). Its URLs are redacted where the - /// warning is built, for stderr and the `--json` document alike. + /// warning is built. #[test] fn a_run_warning_never_quotes_a_credential() { let mut env = Envelope::new(Command::Scan); diff --git a/crates/socket-patch-cli/tests/vex/main.rs b/crates/socket-patch-cli/tests/vex/main.rs index 2e301216ef..27188e6517 100644 --- a/crates/socket-patch-cli/tests/vex/main.rs +++ b/crates/socket-patch-cli/tests/vex/main.rs @@ -9,6 +9,7 @@ #[path = "../common/mod.rs"] mod common; +mod quoted_url_credentials; mod vex_failure_paths; mod vex_fixture; mod vex_go_patches; diff --git a/crates/socket-patch-cli/tests/vex/quoted_url_credentials.rs b/crates/socket-patch-cli/tests/vex/quoted_url_credentials.rs new file mode 100644 index 0000000000..7f15b402d7 --- /dev/null +++ b/crates/socket-patch-cli/tests/vex/quoted_url_credentials.rs @@ -0,0 +1,66 @@ +//! `vex` reads the project's lockfiles for Socket wiring and says what it +//! cannot attest. A note that quotes a lock entry must not carry the +//! credential that entry's URL holds (#2287): the note is a `Warning:` +//! line on stderr and a `warnings[].detail` of the `--json` envelope. + +use std::path::Path; + +use crate::vex_fixture::*; + +/// The planted credential. No message may carry it. +const SECRET: &str = "S3CRETTOKEN0123456789"; + +/// A yarn classic lock with two blocks of `left-pad@1.3.0`: one wired to +/// a hosted patch, and one installed from a private git remote whose key +/// and `resolved` carry the token CI cloned it with. The second copy is +/// not patched, so `vex` reports the wiring as one it cannot attribute. +fn write_project(root: &Path) { + let remote = format!("git+https://x-access-token:ghp_{SECRET}@github.com/acme/left-pad.git"); + std::fs::write( + root.join("package.json"), + r#"{"name":"app","version":"1.0.0","dependencies":{"left-pad":"^1.3.0","lp-fork":"git+https://github.com/acme/left-pad.git"}}"#, + ) + .unwrap(); + std::fs::write( + root.join("yarn.lock"), + format!( + "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n\ + # yarn lockfile v1\n\n\n\ + left-pad@^1.3.0:\n version \"1.3.0\"\n \ + resolved \"https://patch.socket.dev/patch/npm/left-pad/1.3.0/22222222-3333-4444-8555-666666666666/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/left-pad-1.3.0.tgz#abcdef0123456789abcdef0123456789abcdef01\"\n \ + integrity sha512-PATCHEDpatchedPATCHEDpatched0123456789==\n\n\ + \"left-pad@{remote}\":\n version \"1.3.0\"\n \ + resolved \"{remote}#0123456789abcdef0123456789abcdef01234567\"\n" + ), + ) + .unwrap(); +} + +#[test] +fn a_discovery_note_quotes_a_git_lock_entry_without_its_token() { + for json in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("proj"); + std::fs::create_dir_all(&root).unwrap(); + write_project(&root); + let out = tmp.path().join("out.vex.json"); + let extra: &[&str] = if json { + &["--offline", "--json", "--output", out.to_str().unwrap()] + } else { + &["--offline"] + }; + let o = vex(&root, extra); + let (stdout, stderr) = (stdout(&o), stderr(&o)); + let both = format!("{stdout}\n{stderr}"); + assert!( + !both.contains(SECRET), + "vex {extra:?}: the lock's credential was printed\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + // The note is still there, and still says which entry it means. + assert!( + both.contains("left-pad@git+https://@github.com/acme/left-pad.git"), + "vex {extra:?}: the run names the git entry, with its credential redacted\n\ + stdout:\n{stdout}\nstderr:\n{stderr}" + ); + } +} From 6961706f9d1ea08f6178772bef00ab72b540a1c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:00:44 +0000 Subject: [PATCH 09/13] Spell the fallback's registry one way MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `upstream_registry_fallback` names the project's registry without its userinfo and rewrote the cause to match. The cause of a failed lookup now arrives redacted, so the rewrite found nothing and the sentence read `http://host/…` beside `http://@host/…`. The rewrite takes both spellings, and the warning reads as it does on main. The JSON lookup's test holds its port for the transport case instead of reusing one a dropped listener released, and checks each cause. Refs #2287. Assisted-by: Claude Code --- .../src/patch/redirect/upstream/client.rs | 21 ++++++++++--------- .../src/patch/redirect/upstream/npm.rs | 8 ++++++- .../src/patch/redirect/upstream/vlt.rs | 8 +++++++ 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index aa16e3785a..12c990a4f1 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -973,25 +973,26 @@ mod tests { .mount(&server) .await; let served = server.uri().replace("http://", "http://bot:S3CRET@"); - // A port nothing listens on: the connect fails. - let dead = { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - format!("http://bot:S3CRET@{}", listener.local_addr().unwrap()) - }; + // A server that holds its port for the whole test and hangs up on + // every connection: the request fails in transport. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let hangs_up = format!("http://bot:S3CRET@{}", listener.local_addr().unwrap()); + tokio::spawn(async move { while listener.accept().await.is_ok() {} }); let client = UpstreamClient::new(false); for (base, version, says) in [ - (&served, "1.3.0", "HTTP 404"), - (&served, "1.3.1", "is not JSON"), - (&dead, "1.3.0", "GET http://@127.0.0.1"), + (&served, "1.3.0", ": HTTP 404"), + (&served, "1.3.1", " is not JSON: "), + (&hangs_up, "1.3.0", ": error sending request"), ] { let err = client .npm_dist_on(base, "left-pad", version) .await .unwrap_err(); assert!(!err.contains("S3CRET"), "{err}"); + let asked = base.replace("bot:S3CRET", ""); assert!( - err.contains("http://@127.0.0.1") && err.contains(says), - "the error still says where the request went: {err}" + err.contains(&format!("{asked}/left-pad/{version}{says}")), + "the error still says where the request went, and why it failed: {err}" ); } } diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs index 20315ccdf5..bdc2466417 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs @@ -156,8 +156,14 @@ pub(super) async fn fetch_dists_on>( if let Some((base, why)) = fell_back { // The detail is printed and persisted in `--json` // output (CI logs): never the URL's credentials. + // The cause names the registry as it is configured or, + // where the transport built it, redacted: both read as + // the registry does in this sentence. let clean = crate::utils::redact::strip_url_userinfo(&base); - let why = why.replace(base.trim_end_matches('/'), &clean); + let configured = base.trim_end_matches('/'); + let why = why + .replace(configured, &clean) + .replace(&*crate::utils::redact::redact_url(configured), &clean); let base = clean; result.warnings.push(( "upstream_registry_fallback", diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs index 4bf2a7a4ff..a0a9c8e169 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs @@ -829,6 +829,14 @@ mod tests { for secret in ["s3cret-token", "ci-user"] { assert!(!fallback[0].contains(secret), "{}", fallback[0]); } + // The cause spells the registry the way the sentence around it does. + assert!( + fallback[0].contains(&format!( + "could not be read (GET http://{host}/private/left-pad/1.3.0: HTTP 404" + )), + "{}", + fallback[0] + ); } #[tokio::test] From d27601e5c6a8c394187b62edcc3e2d8941a2540d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:17:07 +0000 Subject: [PATCH 10/13] Skip a redaction span inside another one `redact_url` collects the userinfo, the grant token and each secret query value of a URL and cuts them out in order. A value that is shown as one URL is whatever a project file holds, and when a `?` with a secret-named parameter comes before its `://` (`x?auth=https://u:p@h`) the userinfo lies inside the query value: the second cut started before the first one ended, and the slice panicked. `redact_urls_in` never hands it such text, so main reaches this only from callers that pass a setting whole. This branch added two: the Gradle wrapper's `distributionUrl` and the registry of the fallback warning. A span that starts inside an earlier one is now skipped, as the earlier one covers it. The fallback warning also names its registry with any query secret or grant token redacted, not only without its userinfo, so the cause cannot put one back. Refs #2287. Assisted-by: Claude Code --- .../src/patch/redirect/upstream/npm.rs | 13 ++-- .../src/patch/redirect/upstream/vlt.rs | 67 ++++++++++++------- crates/socket-patch-core/src/utils/redact.rs | 27 +++++++- 3 files changed, 77 insertions(+), 30 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs index bdc2466417..5d4ee6737b 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs @@ -156,14 +156,17 @@ pub(super) async fn fetch_dists_on>( if let Some((base, why)) = fell_back { // The detail is printed and persisted in `--json` // output (CI logs): never the URL's credentials. - // The cause names the registry as it is configured or, - // where the transport built it, redacted: both read as - // the registry does in this sentence. - let clean = crate::utils::redact::strip_url_userinfo(&base); + // The registry is named without its userinfo, and with + // any other secret of its URL redacted. The cause + // names it as it is configured or, where the transport + // built it, redacted: both read as the registry does + // in this sentence. + use crate::utils::redact::{redact_url, strip_url_userinfo}; + let clean = redact_url(&strip_url_userinfo(&base)).into_owned(); let configured = base.trim_end_matches('/'); let why = why .replace(configured, &clean) - .replace(&*crate::utils::redact::redact_url(configured), &clean); + .replace(&*redact_url(configured), &clean); let base = clean; result.warnings.push(( "upstream_registry_fallback", diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs index a0a9c8e169..06ac1b1809 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs @@ -806,36 +806,55 @@ mod tests { let server = registry(&[("left-pad", "1.3.0", Some(LP_UPSTREAM))]).await; std::env::set_var("SOCKET_NPM_REGISTRY", server.uri()); let host = server.uri().replace("http://", ""); - let mirror = format!("http://ci-user:s3cret-token@{host}/private/"); - let text = format!( - "{{\n \"lockfileVersion\": 1,\n \"options\": {{\"registries\":{{\"npm\":\"{mirror}\"}}}},\n \"nodes\": {{\n \"~npm~left-pad@1.3.0\": [0,\"left-pad\",\"sha512-AA==\",\"{}\"]\n }},\n \"edges\": {{}}\n}}\n", - hosted(LP_UUID, "left-pad-1.3.0.tgz") - ); - let (outcome, _) = run(&text, &[pin("pkg:npm/left-pad@1.3.0", LP_UUID)], false).await; + let fallback_of = |mirror: String| { + let text = format!( + "{{\n \"lockfileVersion\": 1,\n \"options\": {{\"registries\":{{\"npm\":\"{mirror}\"}}}},\n \"nodes\": {{\n \"~npm~left-pad@1.3.0\": [0,\"left-pad\",\"sha512-AA==\",\"{}\"]\n }},\n \"edges\": {{}}\n}}\n", + hosted(LP_UUID, "left-pad-1.3.0.tgz") + ); + async move { + let (outcome, _) = + run(&text, &[pin("pkg:npm/left-pad@1.3.0", LP_UUID)], false).await; + assert!(refused(&outcome).is_empty(), "{:?}", refused(&outcome)); + let fallback: Vec = outcome + .warnings + .iter() + .filter(|(code, _)| *code == "upstream_registry_fallback") + .map(|(_, detail)| detail.clone()) + .collect(); + assert_eq!(fallback.len(), 1, "{:?}", outcome.warnings); + fallback.into_iter().next().unwrap() + } + }; + let userinfo = fallback_of(format!("http://ci-user:s3cret-token@{host}/private/")).await; + // A secret the URL carries in its query is no more printed than + // its userinfo, in the registry's name or in the cause. + let query = fallback_of(format!( + "http://ci-user:s3cret-token@{host}/private?token=q-s3cret" + )) + .await; std::env::remove_var("SOCKET_NPM_REGISTRY"); - assert!(refused(&outcome).is_empty(), "{:?}", refused(&outcome)); - let fallback: Vec<&String> = outcome - .warnings - .iter() - .filter(|(code, _)| *code == "upstream_registry_fallback") - .map(|(_, detail)| detail) - .collect(); - assert_eq!(fallback.len(), 1, "{:?}", outcome.warnings); - assert!( - fallback[0].contains(&format!("http://{host}/private")), - "{}", - fallback[0] - ); - for secret in ["s3cret-token", "ci-user"] { - assert!(!fallback[0].contains(secret), "{}", fallback[0]); + for fallback in [&userinfo, &query] { + assert!( + fallback.contains(&format!("http://{host}/private")), + "{fallback}" + ); + for secret in ["s3cret-token", "ci-user", "q-s3cret"] { + assert!(!fallback.contains(secret), "{fallback}"); + } } // The cause spells the registry the way the sentence around it does. assert!( - fallback[0].contains(&format!( + userinfo.contains(&format!( "could not be read (GET http://{host}/private/left-pad/1.3.0: HTTP 404" )), - "{}", - fallback[0] + "{userinfo}" + ); + assert!( + query.contains(&format!( + "the project's registry http://{host}/private?token= could not be \ + read (GET http://{host}/private?token=: HTTP 404" + )), + "{query}" ); } diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 0de5487c2e..1b036bd61e 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -169,7 +169,10 @@ fn secret_query_spans(url: &str) -> Vec> { spans } -/// `url` with each span replaced by `with` (spans must not overlap). +/// `url` with each span replaced by `with`. A span that starts inside an +/// earlier one is covered by it already and is skipped: in text that is +/// not a well-formed URL (`x?auth=https://u:p@h`, where the `?` precedes +/// the `://`) the userinfo lies inside a secret query value. fn replace_spans<'a>(url: &'a str, mut spans: Vec>, with: &str) -> Cow<'a, str> { if spans.is_empty() { return Cow::Borrowed(url); @@ -178,6 +181,9 @@ fn replace_spans<'a>(url: &'a str, mut spans: Vec>, with: &str) -> let mut out = String::with_capacity(url.len()); let mut at = 0; for span in spans { + if span.start < at { + continue; + } out.push_str(&url[at..span.start]); out.push_str(with); at = span.end; @@ -468,6 +474,25 @@ mod tests { } } + /// A value that is shown as one URL is whatever a project file holds + /// (a registry setting, a wrapper's `distributionUrl`), not always a + /// URL. With a `?` before the `://`, the userinfo lies inside a secret + /// query value: the value is redacted once, whole. + #[test] + fn a_credential_inside_a_secret_query_value_is_redacted_once() { + for (url, redacted) in [ + ("x?auth=https://u:p@h", "x?auth="), + ( + "host/login?password=https://u@h/x&page=2", + "host/login?password=&page=2", + ), + ("?token=://x@y", "?token="), + ("?,key=://T@", "?,key="), + ] { + assert_eq!(redact_url(url), redacted, "{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] From 2041fa643a14886d45a1bb6e1e8c628abacb11f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:29:52 +0000 Subject: [PATCH 11/13] Cut overlapping redaction spans as one The spans of a text that is not a well-formed URL can overlap only in part: a userinfo or a grant token that runs past the end of a secret query value, or a query value that starts inside one. Skipping the later span left its tail in the output (`x?auth=https://user:PASS&WORD@h` kept `&WORD`). Overlapping spans are now cut together. Each of these inputs panicked before this branch. A JSON lookup redacts the URL it asked as the one URL it is, instead of scanning its own message for URLs, so a password that holds `)` or `'` is redacted there too. Its test uses such a password. The fallback warning's test asserts only after it has removed the variable it set. Refs #2287. Assisted-by: Claude Code --- .../src/patch/redirect/upstream/client.rs | 38 +++++++++---------- .../src/patch/redirect/upstream/vlt.rs | 28 ++++++++------ crates/socket-patch-core/src/utils/redact.rs | 28 ++++++++++---- 3 files changed, 56 insertions(+), 38 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index 12c990a4f1..4165473372 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -316,8 +316,9 @@ impl UpstreamClient { /// [`Self::get_json`] sending `authorization` (a private registry's /// credentials) as the `Authorization` header. reqwest drops the header - /// on a redirect to another host. Every error quotes the URL redacted, - /// as [`crate::vendor::registry_fetch::download`]'s do: a mirror variable (`SOCKET_NPM_REGISTRY`, + /// on a redirect to another host. Every error quotes the URL redacted + /// ([`crate::utils::redact::redact_url`], as one URL: it is known whole + /// here): a mirror variable (`SOCKET_NPM_REGISTRY`, /// `SOCKET_PYPI_JSON_API`, `SOCKET_PACKAGIST_URL`) or a project's /// registry can carry credentials in it. async fn get_json_authorized( @@ -325,22 +326,13 @@ impl UpstreamClient { url: &str, authorization: Option<&str>, ) -> Result { - self.get_json_unredacted(url, authorization) - .await - .map_err(crate::utils::redact::redact_message) - } - - async fn get_json_unredacted( - &self, - url: &str, - authorization: Option<&str>, - ) -> Result { + let shown = crate::utils::redact::redact_url(url); let _permit = self.permit().await; let mut request = self.http.get(url).header("accept", "application/json"); if let Some(authorization) = authorization { let mut value = reqwest::header::HeaderValue::from_str(authorization).map_err(|_| { - format!("GET {url}: the configured credentials are not a valid header") + format!("GET {shown}: the configured credentials are not a valid header") })?; value.set_sensitive(true); request = request.header(reqwest::header::AUTHORIZATION, value); @@ -348,16 +340,16 @@ impl UpstreamClient { let resp = request .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}")); } let text = resp .text() .await - .map_err(|e| format!("reading {url}: {}", network_error_detail(&e)))?; - serde_json::from_str(&text).map_err(|e| format!("{url} is not JSON: {e}")) + .map_err(|e| format!("reading {shown}: {}", network_error_detail(&e)))?; + serde_json::from_str(&text).map_err(|e| format!("{shown} is not JSON: {e}")) } async fn get_text(&self, url: &str) -> Result { @@ -972,7 +964,9 @@ mod tests { .respond_with(ResponseTemplate::new(200).set_body_string("")) .mount(&server) .await; - let served = server.uri().replace("http://", "http://bot:S3CRET@"); + // The password holds characters that end a URL quoted in text: the + // URL is redacted as the one URL it is, so they change nothing. + let served = server.uri().replace("http://", "http://bot:S3)CR'ET@"); // A server that holds its port for the whole test and hangs up on // every connection: the request fails in transport. let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -988,8 +982,12 @@ mod tests { .npm_dist_on(base, "left-pad", version) .await .unwrap_err(); - assert!(!err.contains("S3CRET"), "{err}"); - let asked = base.replace("bot:S3CRET", ""); + for part in ["S3", "CR", "ET@"] { + assert!(!err.contains(part), "{part} in {err}"); + } + let asked = base + .replace("bot:S3)CR'ET", "") + .replace("bot:S3CRET", ""); assert!( err.contains(&format!("{asked}/left-pad/{version}{says}")), "the error still says where the request went, and why it failed: {err}" diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs index 06ac1b1809..e5f57ac197 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs @@ -812,17 +812,9 @@ mod tests { hosted(LP_UUID, "left-pad-1.3.0.tgz") ); async move { - let (outcome, _) = - run(&text, &[pin("pkg:npm/left-pad@1.3.0", LP_UUID)], false).await; - assert!(refused(&outcome).is_empty(), "{:?}", refused(&outcome)); - let fallback: Vec = outcome - .warnings - .iter() - .filter(|(code, _)| *code == "upstream_registry_fallback") - .map(|(_, detail)| detail.clone()) - .collect(); - assert_eq!(fallback.len(), 1, "{:?}", outcome.warnings); - fallback.into_iter().next().unwrap() + run(&text, &[pin("pkg:npm/left-pad@1.3.0", LP_UUID)], false) + .await + .0 } }; let userinfo = fallback_of(format!("http://ci-user:s3cret-token@{host}/private/")).await; @@ -832,7 +824,21 @@ mod tests { "http://ci-user:s3cret-token@{host}/private?token=q-s3cret" )) .await; + // Nothing is asserted before the variable is gone: a failure would + // leave it set for the tests that run after this one. std::env::remove_var("SOCKET_NPM_REGISTRY"); + let fallback_in = |outcome: &RestoreOutcome| { + assert!(refused(outcome).is_empty(), "{:?}", refused(outcome)); + let fallback: Vec = outcome + .warnings + .iter() + .filter(|(code, _)| *code == "upstream_registry_fallback") + .map(|(_, detail)| detail.clone()) + .collect(); + assert_eq!(fallback.len(), 1, "{:?}", outcome.warnings); + fallback.into_iter().next().unwrap() + }; + let (userinfo, query) = (fallback_in(&userinfo), fallback_in(&query)); for fallback in [&userinfo, &query] { assert!( fallback.contains(&format!("http://{host}/private")), diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 1b036bd61e..569f8b4725 100644 --- a/crates/socket-patch-core/src/utils/redact.rs +++ b/crates/socket-patch-core/src/utils/redact.rs @@ -169,10 +169,10 @@ fn secret_query_spans(url: &str) -> Vec> { spans } -/// `url` with each span replaced by `with`. A span that starts inside an -/// earlier one is covered by it already and is skipped: in text that is -/// not a well-formed URL (`x?auth=https://u:p@h`, where the `?` precedes -/// the `://`) the userinfo lies inside a secret query value. +/// `url` with each span replaced by `with`. Spans that overlap are cut +/// as one: in text that is not a well-formed URL (`x?auth=https://u:p@h`, +/// where the `?` precedes the `://`) the userinfo or the grant token can +/// lie inside a secret query value, or run across the end of one. fn replace_spans<'a>(url: &'a str, mut spans: Vec>, with: &str) -> Cow<'a, str> { if spans.is_empty() { return Cow::Borrowed(url); @@ -182,6 +182,7 @@ fn replace_spans<'a>(url: &'a str, mut spans: Vec>, with: &str) -> let mut at = 0; for span in spans { if span.start < at { + at = at.max(span.end); continue; } out.push_str(&url[at..span.start]); @@ -476,10 +477,11 @@ mod tests { /// A value that is shown as one URL is whatever a project file holds /// (a registry setting, a wrapper's `distributionUrl`), not always a - /// URL. With a `?` before the `://`, the userinfo lies inside a secret - /// query value: the value is redacted once, whole. + /// URL. With a `?` before the `://`, the userinfo or the grant token + /// lies inside a secret query value, or runs across its end: what + /// overlaps is redacted once, whole. #[test] - fn a_credential_inside_a_secret_query_value_is_redacted_once() { + fn credentials_that_overlap_are_redacted_as_one() { for (url, redacted) in [ ("x?auth=https://u:p@h", "x?auth="), ( @@ -488,6 +490,18 @@ mod tests { ), ("?token=://x@y", "?token="), ("?,key=://T@", "?,key="), + // The userinfo runs past the end of the query value. + ("x?auth=https://user:PASS&WORD@h/p", "x?auth=@h/p"), + // The query value starts inside the userinfo. + ( + "x?next=https://user&token=abc@DEF/p", + "x?next=https://", + ), + // The grant token runs past the end of the query value. + ( + "x?auth=https://h/patch/npm/TOK&EN/7c8d9e0f-1a2b-4a1b-8c2d-3e4f5a6b7c8d/f.tgz", + "x?auth=/7c8d9e0f-1a2b-4a1b-8c2d-3e4f5a6b7c8d/f.tgz", + ), ] { assert_eq!(redact_url(url), redacted, "{url}"); } From d6f0fdc1fa3dd09f81b55d6e9b1cfd259e2e6ad2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:53:21 +0000 Subject: [PATCH 12/13] Expect a bun patch key without its token Three messages name the `patchedDependencies` key of a `bun patch` made while the package resolved to its hosted tarball: the skip of a superseding hosted run, the refusal of a vendored takeover, and the rollback's note that the patch stops applying. The key is `@`, and the URL holds the grant token. Their tests pinned the key as written. The messages now go through the redacting constructors, so the token reads ``; the name, the patch uuid and the file still say which entry is meant. The tests expect that form and check that the token is not printed. Refs #2287. Assisted-by: Claude Code --- .../user_patch.rs | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs b/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs index e3acd15a7c..2f98b9fcee 100644 --- a/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs +++ b/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs @@ -33,6 +33,18 @@ fn add_user_patch_keyed_by(root: &Path, url: &str) -> String { key } +/// The grant token of the hosted URLs these projects pin (the path level +/// before the patch uuid): a credential, so no message may carry it. +const GRANT_TOKEN: &str = "55555555-5555-4555-8555-555555555555"; + +/// `key` as a message names it: the package and the tarball's URL, with +/// the grant token redacted (#2287). The name, the patch uuid and the +/// file still say which `patchedDependencies` entry is meant. +fn shown(key: &str) -> String { + assert!(key.contains(GRANT_TOKEN), "{key}"); + key.replace(GRANT_TOKEN, "") +} + /// The scan's `redirect_bun_patched_dependency_skipped` warning detail. fn skipped_detail(env: &Value) -> Option { env["redirect"]["warnings"] @@ -76,7 +88,8 @@ async fn bun_patch_keyed_by_hosted_url_survives_a_superseding_rerun() { ); assert_eq!(lock, hosted_lock, "{env:#}"); let detail = skipped_detail(&env).unwrap_or_else(|| panic!("no skip warning: {env:#}")); - assert!(detail.contains(&key), "{detail}"); + assert!(detail.contains(&shown(&key)), "{detail}"); + assert!(!detail.contains(GRANT_TOKEN), "{detail}"); } #[tokio::test(flavor = "multi_thread")] @@ -98,9 +111,13 @@ async fn bun_patch_keyed_by_hosted_url_blocks_the_vendored_takeover() { let failed = find_event(&env, "failed", Some("vendor_lock_entry_unsupported")); assert_eq!(failed["purl"], PURL, "{env:#}"); assert!( - failed.to_string().contains(&key), + failed.to_string().contains(&shown(&key)), "the refusal names the key: {env:#}" ); + assert!( + !failed.to_string().contains(GRANT_TOKEN), + "the refusal carries no grant token: {env:#}" + ); assert_eq!( read(root, "bun.lock"), hosted_lock, @@ -135,9 +152,10 @@ fn bun_rollback_warns_that_a_patch_keyed_by_the_hosted_url_stops_applying() { let detail = run_warning(&env, "redirect_bun_patched_dependency_dropped") .unwrap_or_else(|| panic!("no drop warning: {env:#}")); assert!( - detail.contains(&key) && detail.contains("bun patch"), + detail.contains(&shown(&key)) && detail.contains("bun patch"), "{detail}" ); + assert!(!detail.contains(GRANT_TOKEN), "{detail}"); } #[tokio::test(flavor = "multi_thread")] From 1c2ca65790403169172e36e125e7196908beb321 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:56:52 +0000 Subject: [PATCH 13/13] Redact URLs in the hosted unwind's warnings `rollback` and `remove` print the warnings of their hosted leg on stderr from the leg's own list and build the envelope's copy afterwards. The envelope's copy is redacted by its constructor; the stderr line was not, so a human run still printed the grant token in the key of a dropped `bun patch`, where `--json` showed ``. `run_hosted_leg` now redacts its warnings once, where it finishes them, so both channels read the same. The test of that warning runs `rollback` and `remove` without `--json` as well. Refs #2287. Assisted-by: Claude Code --- .../src/commands/hosted_unwind.rs | 7 ++++++ .../user_patch.rs | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 393573524b..cc7792dad6 100644 --- a/crates/socket-patch-cli/src/commands/hosted_unwind.rs +++ b/crates/socket-patch-cli/src/commands/hosted_unwind.rs @@ -323,6 +323,13 @@ pub(crate) async fn run_hosted_leg( .collect(); out.warnings .extend(crate::commands::vlt_heal::rollback_heal(common, &unwound).await); + // `rollback` and `remove` print these on stderr and store them in + // `warnings[]`. A URL one of them quotes from the project (the key of + // a `bun patch` holds the hosted tarball's URL, grant token and all) + // is redacted here, once, for both. + for (_, detail) in &mut out.warnings { + *detail = socket_patch_core::utils::redact::redact_message(std::mem::take(detail)); + } out } diff --git a/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs b/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs index 2f98b9fcee..715aaacd71 100644 --- a/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs +++ b/crates/socket-patch-cli/tests/in_process_vendor_bun_takeover/user_patch.rs @@ -156,6 +156,31 @@ fn bun_rollback_warns_that_a_patch_keyed_by_the_hosted_url_stops_applying() { "{detail}" ); assert!(!detail.contains(GRANT_TOKEN), "{detail}"); + + // The human runs print the same warning on stderr, as redacted as the + // envelope's copy. + for command in [&["rollback", "--yes"][..], &["remove", PURL, "--yes"]] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_lockfile_only_hosted_project(root, HOSTED_URL); + seed_manifest_and_blob(root); + let key = add_user_patch_keyed_by(root, HOSTED_URL); + let mut args = command.to_vec(); + args.extend(["--cwd", root.to_str().unwrap()]); + let (code, stdout, stderr) = super::run_cli_env(root, &args, &[]); + assert_eq!(code, 0, "{command:?}: {stderr}"); + assert!( + stderr.contains(&format!( + "Warning: package.json `patchedDependencies` has `{}`", + shown(&key) + )), + "{command:?}: {stderr}" + ); + assert!( + !stdout.contains(GRANT_TOKEN) && !stderr.contains(GRANT_TOKEN), + "{command:?} prints the grant token\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + } } #[tokio::test(flavor = "multi_thread")]