diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 393573524..cc7792dad 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/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index fac342b07..6a8f0792d 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 cc3d928d0..6fdd27d29 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -762,10 +762,17 @@ pub struct RunWarning { } impl RunWarning { + /// Every URL quoted in `detail` is redacted + /// ([`socket_patch_core::utils::redact::redact_urls_in`]): a run + /// 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(), - detail: detail.into(), + detail: socket_patch_core::utils::redact::redact_message(detail.into()), } } } @@ -789,6 +796,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. + #[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 +1221,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-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 e3acd15a7..715aaacd7 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,35 @@ 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}"); + + // 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")] diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index 00a6db5cf..b68542255 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 000000000..27c9f7b81 --- /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; +} diff --git a/crates/socket-patch-cli/tests/vex/main.rs b/crates/socket-patch-cli/tests/vex/main.rs index 2e301216e..27188e651 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 000000000..7f15b402d --- /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}" + ); + } +} diff --git a/crates/socket-patch-core/src/crawlers/gradle_cache.rs b/crates/socket-patch-core/src/crawlers/gradle_cache.rs index b5d1549eb..3744ca8fe 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] diff --git a/crates/socket-patch-core/src/hosted/memory/types.rs b/crates/socket-patch-core/src/hosted/memory/types.rs index fa81876e8..327b2cbfc 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 5131ec0e2..ac29a06fd 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 57c014fb0..71f642914 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 223a8fdf1..7c330dd6f 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 75a28558a..2adb0c330 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"), 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 d8217a64a..416547337 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -316,18 +316,23 @@ 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 + /// ([`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( &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); @@ -335,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 { @@ -943,6 +948,53 @@ 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; + // 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(); + 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: "), + (&hangs_up, "1.3.0", ": error sending request"), + ] { + let err = client + .npm_dist_on(base, "left-pad", version) + .await + .unwrap_err(); + 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}" + ); + } + } + /// #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 7be7d792a..5477e3603 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/npm.rs b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs index 20315ccdf..5d4ee6737 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,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. - let clean = crate::utils::redact::strip_url_userinfo(&base); - let why = why.replace(base.trim_end_matches('/'), &clean); + // 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(&*redact_url(configured), &clean); let base = clean; result.warnings.push(( "upstream_registry_fallback", 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 15a512949..0f91f90d9 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}"); 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 4bf2a7a4f..e5f57ac19 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs @@ -806,29 +806,62 @@ 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 { + 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; + // 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; + // 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"); - 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); + 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")), + "{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!("http://{host}/private")), - "{}", - fallback[0] + userinfo.contains(&format!( + "could not be read (GET http://{host}/private/left-pad/1.3.0: HTTP 404" + )), + "{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}" ); - for secret in ["s3cret-token", "ci-user"] { - assert!(!fallback[0].contains(secret), "{}", fallback[0]); - } } #[tokio::test] diff --git a/crates/socket-patch-core/src/utils/redact.rs b/crates/socket-patch-core/src/utils/redact.rs index 5d9c10503..569f8b472 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`. 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); @@ -178,6 +181,10 @@ 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 { + at = at.max(span.end); + continue; + } out.push_str(&url[at..span.start]); out.push_str(with); at = span.end; @@ -237,11 +244,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,6 +309,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 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, + Cow::Owned(redacted) => redacted, + } +} + #[cfg(test)] mod tests { use super::*; @@ -428,6 +449,64 @@ 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 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 or the grant token + /// lies inside a secret query value, or runs across its end: what + /// overlaps is redacted once, whole. + #[test] + fn credentials_that_overlap_are_redacted_as_one() { + 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="), + // 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}"); + } + } + /// A comma-joined URL list (GOPROXY) is redacted element by element; /// a URL nested in a query is still part of its URL. #[test] diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 60e29f93a..dd60b9c05 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 57fb44dd6..90729ff68 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 f7713d0df..9cc7e8ba0 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 5c3bca20d..3cc8857f5 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!`).