diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c88bd12c..d040201cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -162,6 +162,15 @@ limits, and required install commands. - Transient apply locks are removed on normal command exit; no-op scans and full reversal avoid leaving unused `.socket/` state. Terminal output, telemetry timeouts, and update-check handling are more consistent. +- npm locks keep their own layout when edited. `scan --mode hosted`, + `scan --mode vendored`, `rollback` and `vendor --revert` + re-serialized `package-lock.json` / `npm-shrinkwrap.json` with LF line + endings (and, in hosted mode, a fixed 2-space indent), so a CRLF or + tab-indented lock got a whole-file diff and the undo did not restore its + bytes. A lock with a UTF-8 BOM, which npm installs from, was skipped as + unparseable (hosted) or refused as `vendor_lockfile_version_unsupported` + (vendored). The lock now keeps its BOM, indent and line endings, and the + undo is byte-exact (#324). ### Maintenance diff --git a/crates/socket-patch-cli/tests/e2e_vendor_npm_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_npm_build.rs index 39b4c4a04..14a7b9c73 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_npm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_npm_build.rs @@ -495,6 +495,115 @@ fn npm_vendor_fresh_checkout_npm_ci_and_revert() { ); } +/// #324 with the real npm: a CRLF lock with a UTF-8 BOM (npm installs from +/// both) is vendored in its own layout, a fresh `npm ci` installs the +/// patched bytes from it, and `vendor --revert` restores its exact bytes. +#[test] +fn npm_vendor_keeps_a_crlf_bom_lock_and_reverts_it_byte_for_byte() { + let Some(major) = npm_major_or_skip("e2e_vendor_npm_build") else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("package.json"), + r#"{"name":"vendor-crlf-bom","version":"0.0.0","private":true}"#, + ) + .unwrap(); + let cache = tmp.path().join("npm-cache"); + if !npm_e2e_common::install_fixture( + "e2e_vendor_npm_build", + &proj, + &cache, + &format!("{DEP}@{DEP_VERSION}"), + ) { + return; + } + let orig = std::fs::read(proj.join("node_modules").join(DEP).join("index.js")).unwrap(); + let patched: Vec = [MARKER.as_bytes(), orig.as_slice()].concat(); + let purl = format!("pkg:npm/{DEP}@{DEP_VERSION}"); + stage_patch_with_vuln(&proj, &purl, "package/index.js", &orig, &patched, TAIL_GHSA); + if v1_lock_is_refused(&proj, major) { + return; + } + + let lock_path = proj.join("package-lock.json"); + let lf = std::fs::read_to_string(&lock_path).unwrap(); + let pristine = format!("\u{feff}{}", lf.replace('\n', "\r\n")); + std::fs::write(&lock_path, &pristine).unwrap(); + + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "vendor", + "--json", + "--offline", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!( + code, 0, + "vendor failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_envelope(&stdout); + assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); + let wired = std::fs::read_to_string(&lock_path).unwrap(); + assert!(wired.starts_with('\u{feff}'), "the BOM is kept"); + assert!( + !wired.replace("\r\n", "").contains('\n'), + "every line stays CRLF:\n{wired:?}" + ); + + let fresh = tmp.path().join("fresh"); + std::fs::create_dir_all(&fresh).unwrap(); + std::fs::copy(proj.join("package.json"), fresh.join("package.json")).unwrap(); + std::fs::copy(&lock_path, fresh.join("package-lock.json")).unwrap(); + copy_dir_recursive(&proj.join(".socket"), &fresh.join(".socket")); + let fresh_cache = tmp.path().join("fresh-npm-cache"); + let ci = npm( + &fresh, + &[ + "ci", + "--cache", + fresh_cache.to_str().unwrap(), + "--no-audit", + "--no-fund", + ], + ); + assert!( + ci.status.success(), + "`npm ci` must install from the CRLF/BOM lock.\nstderr:\n{}", + String::from_utf8_lossy(&ci.stderr), + ); + assert_eq!( + std::fs::read(fresh.join("node_modules").join(DEP).join("index.js")).unwrap(), + patched, + "npm ci installs the PATCHED bytes" + ); + + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "vendor", + "--revert", + "--json", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!( + code, 0, + "revert failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read_to_string(&lock_path).unwrap(), + pristine, + "revert restores the CRLF/BOM lock byte for byte" + ); +} + /// Real-toolchain VEX capstone for npm: after a REAL install + `vendor`, the /// vendored `.tgz` is the on-disk evidence. `socket-patch vex` must attest the /// patch against that vendored tarball with the `(vendored)` marker — proving diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index ceed30f70..706252ea9 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -25,6 +25,7 @@ use serde_json::{json, Value}; use crate::utils::digest::is_hex64_lower; use crate::utils::line_endings::{to_lf, LineEndings}; +use crate::vendor::common::{parse_json_text, JsonLayout}; use crate::vendor::npm_origin::{legacy_packages_key, npm_non_registry_entries}; use crate::vendor::yarn_berry_lock::yarnrc_compression_level; @@ -280,6 +281,17 @@ fn serialize_json(value: &Value) -> String { ) } +/// `value` pretty-printed in the layout of `original`, the text it replaces +/// (BOM, indent, line ending and trailer; see [`JsonLayout`]), so a rewrite +/// and its revert change nothing but the edited values. npm keeps a lock's +/// CRLF and tab indent on its own rewrites, and so must we. +fn serialize_json_like(value: &Value, original: &str) -> String { + let bytes = JsonLayout::of(original) + .render(value) + .expect("serde_json::Value serializes infallibly"); + String::from_utf8(bytes).expect("rendered JSON is UTF-8") +} + /// The dep's registry override when it is of `kind`. `None` for an absent /// AND for a foreign-kind override alike — neither can drive this /// ecosystem's rewrite, so every rewriter warns its missing-override code @@ -821,7 +833,8 @@ fn rewrite_one_npm_lock( npm: &[&DepOverride], result: &mut RewriteResult, ) { - let Ok(mut lock) = serde_json::from_str::(content) else { + // npm reads past a leading UTF-8 BOM; so do we. + let Ok(mut lock) = parse_json_text(content) else { // A corrupt lockfile is strictly worse than a missing one (which // warns in the caller) — never skip the whole npm redirect silently. result.warnings.push(RewriteWarning { @@ -988,7 +1001,9 @@ fn rewrite_one_npm_lock( ), }); } - result.files.insert(lockfile.into(), serialize_json(&lock)); + result + .files + .insert(lockfile.into(), serialize_json_like(&lock, content)); } } @@ -12103,6 +12118,43 @@ mod tests { ); } + /// #324: the hosted npm rewrite changes only the rewired values and keeps + /// the lock's layout: CRLF stays CRLF, a tab indent stays tabs, and a + /// UTF-8 BOM lock (npm strips the BOM and installs from it) is rewritten + /// with its BOM rather than skipped as unparseable. + #[test] + fn npm_lock_rewrite_keeps_crlf_tabs_and_bom() { + let ovr = npm_override( + "left-pad", + "1.3.0", + "http://patch.test/left-pad-1.3.0.tgz", + "sha512-PATCHED==", + ); + let lf = "{\n \"name\": \"app\",\n \"lockfileVersion\": 3,\n \"packages\": {\n \"\": {\n \"name\": \"app\"\n },\n \"node_modules/left-pad\": {\n \"version\": \"1.3.0\",\n \"resolved\": \"https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz\",\n \"integrity\": \"sha512-UPSTREAM==\"\n }\n }\n}\n"; + let shapes = [ + ("crlf", lf.replace('\n', "\r\n")), + ("tabs", lf.replace(" ", "\t")), + ("bom", format!("\u{feff}{lf}")), + ("bom+crlf+tabs", format!("\u{feff}{}", lf.replace(" ", "\t").replace('\n', "\r\n"))), + ]; + for (shape, pristine) in shapes { + let mut files = BTreeMap::new(); + files.insert("package-lock.json".to_string(), pristine.clone()); + let r = rewrite_registry_redirect(&files, std::slice::from_ref(&ovr)); + let out = r + .files + .get("package-lock.json") + .unwrap_or_else(|| panic!("{shape}: lock must be rewritten: {:?}", r.warnings)); + let expected = pristine + .replace( + "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", + "http://patch.test/left-pad-1.3.0.tgz", + ) + .replace("sha512-UPSTREAM==", "sha512-PATCHED=="); + assert_eq!(out, &expected, "{shape}: only the rewired values may change"); + } + } + /// An unparseable package-lock.json must surface a warning, not silently /// skip the npm redirect entirely (missing-lockfile already warns; a /// corrupt lockfile is strictly worse). 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 379726b25..efff38b0a 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs @@ -149,7 +149,8 @@ pub(crate) async fn restore_npm_locks( let Some(text) = read_or_refuse(view, rel, &pins, &mut result).await else { continue; }; - let Ok(mut lock) = serde_json::from_str::(&text) else { + // npm reads past a leading UTF-8 BOM; so do we. + let Ok(mut lock) = crate::vendor::common::parse_json_text(&text) else { refuse_all_in(&pins, rel, &mut result, format!("{rel} is not valid JSON")); continue; }; @@ -192,7 +193,8 @@ pub(crate) async fn restore_npm_locks( changed = true; } if changed { - view.write(rel, super::super::serialize_json(&lock)); + // The lock's own BOM, indent and line endings (#324). + view.write(rel, super::super::serialize_json_like(&lock, &text)); } } result diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index db630ed5d..64030bd51 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -182,6 +182,11 @@ pub(crate) fn parse_json_manifest(bytes: &[u8]) -> serde_json::Result { serde_json::from_slice(bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes)) } +/// [`parse_json_manifest`] for text already decoded as UTF-8. +pub(crate) fn parse_json_text(text: &str) -> serde_json::Result { + serde_json::from_str(text.strip_prefix('\u{feff}').unwrap_or(text)) +} + /// The byte layout a re-serialized JSON manifest keeps from the text it /// replaces, so a vendor edit and its revert change nothing but the edited /// keys: the leading UTF-8 BOM, the indent unit ([`detect_indent`]), the diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/npm.rs b/crates/socket-patch-core/src/vendor/lock_inventory/npm.rs index 932ad56dc..114bf4182 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/npm.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/npm.rs @@ -164,7 +164,7 @@ pub(super) async fn inventory_package_lock_in( break; } } - let doc: Value = serde_json::from_slice(&bytes?).ok()?; + let doc: Value = crate::vendor::common::parse_json_manifest(&bytes?).ok()?; // v1 legacy locks have no `packages` map — no inventory (documented). doc.get("packages")?.as_object()?; diff --git a/crates/socket-patch-core/src/vendor/npm_lock.rs b/crates/socket-patch-core/src/vendor/npm_lock.rs index 0a8237cb8..c96322bf6 100644 --- a/crates/socket-patch-core/src/vendor/npm_lock.rs +++ b/crates/socket-patch-core/src/vendor/npm_lock.rs @@ -25,7 +25,7 @@ use crate::patch::apply::PatchSources; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_bytes}; use crate::utils::socket_dir::remove_tree_and_prune; -use super::common::{already_patched_result, detect_indent, done, refused, serialize_json}; +use super::common::{already_patched_result, done, parse_json_manifest, refused, JsonLayout}; use super::npm_common::{ done_failure_unstage, guard_coordinates, guard_revert_uuid_dir, stage_patch_pack, }; @@ -133,7 +133,7 @@ pub async fn vendor_npm<'a>( ); } }; - let lock = match LOCK_MEMO.parse(&lock_bytes, || serde_json::from_slice::(&lock_bytes)) { + let lock = match LOCK_MEMO.parse(&lock_bytes, || parse_json_manifest(&lock_bytes)) { Ok(v) => v, Err(e) => { return refused( @@ -267,8 +267,8 @@ pub async fn vendor_npm<'a>( } if sib_changed { changed = true; - let indent = detect_indent(&String::from_utf8_lossy(&sib.bytes)); - match serialize_json(&sib.lock, &indent) { + let layout = JsonLayout::of(&String::from_utf8_lossy(&sib.bytes)); + match layout.render(&sib.lock) { Ok(out) => sibling_writes.push((sib.name.clone(), sib.bytes.clone(), out)), Err(e) => { return done_failure_unstage( @@ -308,8 +308,8 @@ pub async fn vendor_npm<'a>( ); } - let indent = detect_indent(&String::from_utf8_lossy(&lock_bytes)); - let out = match serialize_json(&lock, &indent) { + let layout = JsonLayout::of(&String::from_utf8_lossy(&lock_bytes)); + let out = match layout.render(&lock) { Ok(out) => out, Err(e) => { return done_failure_unstage( @@ -512,7 +512,7 @@ pub(super) async fn read_project(project_root: &Path) -> Result return Err("vendor_lockfile_missing"), }; let lock = LOCK_MEMO - .parse(&lock_bytes, || serde_json::from_slice::(&lock_bytes)) + .parse(&lock_bytes, || parse_json_manifest(&lock_bytes)) .map_err(|_| "vendor_lockfile_version_unsupported")?; lock_version_gate(&lock, &lock_name).map_err(|o| super::npm_common::refusal_code(&o))?; Ok(NpmLockProject { lock_name, lock }) @@ -703,17 +703,16 @@ pub async fn revert_npm_opts( } Err(e) => return RevertOutcome::failed(format!("cannot read {lock_name}: {e}")), }; - let mut lock = - match LOCK_MEMO.parse(&lock_bytes, || serde_json::from_slice::(&lock_bytes)) { - Ok(v) => (*v).clone(), - // Fail-closed: editing a lock we cannot parse risks destroying - // it; the user must repair it before revert can restore. - Err(e) => { - return RevertOutcome::failed(format!( - "{lock_name} is not parseable JSON ({e}); fix it and re-run revert" - )) - } - }; + let mut lock = match LOCK_MEMO.parse(&lock_bytes, || parse_json_manifest(&lock_bytes)) { + Ok(v) => (*v).clone(), + // Fail-closed: editing a lock we cannot parse risks destroying + // it; the user must repair it before revert can restore. + Err(e) => { + return RevertOutcome::failed(format!( + "{lock_name} is not parseable JSON ({e}); fix it and re-run revert" + )) + } + }; let mut changed = false; // Reverse application order, like every backend's revert. @@ -728,8 +727,8 @@ pub async fn revert_npm_opts( } if changed { - let indent = detect_indent(&String::from_utf8_lossy(&lock_bytes)); - let out = match serialize_json(&lock, &indent) { + let layout = JsonLayout::of(&String::from_utf8_lossy(&lock_bytes)); + let out = match layout.render(&lock) { Ok(out) => out, Err(e) => { return RevertOutcome::failed(format!("cannot serialize {lock_name}: {e}")) @@ -1210,7 +1209,7 @@ fn sibling_lock_target( ) -> Result { let bytes = sib_bytes.map_err(|e| format!("it cannot be read: {e}"))?; let lock = (*LOCK_MEMO - .parse(&bytes, || serde_json::from_slice::(&bytes)) + .parse(&bytes, || parse_json_manifest(&bytes)) .map_err(|e| format!("it is not parseable JSON: {e}"))?) .clone(); let lock_version = lock.get("lockfileVersion").and_then(Value::as_u64); @@ -1333,6 +1332,7 @@ mod tests { use crate::hash::git_sha256::compute_git_sha256_from_bytes; use crate::manifest::schema::PatchFileInfo; use crate::patch::apply::{ApplyResult, VerifyStatus}; + use crate::vendor::common::{detect_indent, serialize_json}; use base64::Engine as _; use serde_json::json; use sha2::{Digest, Sha512}; @@ -2913,6 +2913,54 @@ mod tests { assert_eq!(e["license"], json!("WTFPL"), "non-dep fields untouched"); } + /// #324: vendoring keeps a CRLF, tab-indented or BOM-prefixed lock's + /// layout (a BOM lock is read the way npm reads it, not refused), and + /// `vendor --revert` restores its original bytes. + #[tokio::test] + async fn vendor_and_revert_keep_crlf_tab_and_bom_lock_layout() { + let lf = String::from_utf8(serialize_json(&default_lock(), " ").unwrap()).unwrap(); + let shapes = [ + ("crlf", lf.replace('\n', "\r\n")), + ("tabs", lf.replace(" ", "\t")), + ("bom", format!("\u{feff}{lf}")), + ("bom+crlf", format!("\u{feff}{}", lf.replace('\n', "\r\n"))), + ]; + for (shape, pristine) in shapes { + let fx = fixture().await; + tokio::fs::write(fx.lock_path(), &pristine).await.unwrap(); + + let (result, entry, _w) = expect_done(fx.vendor(false).await); + assert!(result.success, "{shape}: {:?}", result.error); + let wired = tokio::fs::read_to_string(fx.lock_path()).await.unwrap(); + assert_ne!(wired, pristine, "{shape}: the lock must be rewired"); + assert_eq!( + wired.starts_with('\u{feff}'), + pristine.starts_with('\u{feff}'), + "{shape}: BOM kept" + ); + if pristine.contains("\r\n") { + assert!( + !wired.replace("\r\n", "").contains('\n'), + "{shape}: every line stays CRLF:\n{wired:?}" + ); + } + if pristine.contains('\t') { + assert!( + wired.contains("\n\t\"packages\"") && !wired.contains("\n "), + "{shape}: tab indent kept:\n{wired}" + ); + } + + let outcome = revert_npm(&entry.unwrap(), fx.root(), false).await; + assert!(outcome.success, "{shape}: {:?}", outcome.error); + assert_eq!( + tokio::fs::read_to_string(fx.lock_path()).await.unwrap(), + pristine, + "{shape}: lock restored byte-for-byte" + ); + } + } + #[tokio::test] async fn revert_round_trips_the_lock_and_removes_the_artifact() { let fx = fixture().await; diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 11a585f0b..d571a3b6e 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -1382,7 +1382,10 @@ pub(crate) fn npm_vendored_tarball_names(vref: &VendorRef, purl: &str) -> bool { /// diagnostic detail `" is not valid JSON: "`. No BOM handling: /// the callers that tolerate one strip it first. pub(crate) fn parse_json(file: &str, bytes: &[u8]) -> Result { - serde_json::from_slice(bytes).map_err(|e| format!("{file} is not valid JSON: {e}")) + // npm and Composer both read past a leading UTF-8 BOM, and the + // rewriters keep one, so a wired BOM lock must stay discoverable. + crate::vendor::common::parse_json_manifest(bytes) + .map_err(|e| format!("{file} is not valid JSON: {e}")) } /// How [`toml_or_diag`] spells the parse error in its diagnostic (the goldens diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 0cb2b7431..7d151db2e 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -640,6 +640,25 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// #324: a BOM-prefixed lock (npm reads past the BOM, and the rewriters + /// now keep it) is discovered like any other, not reported unparseable. + #[tokio::test] + async fn bom_prefixed_wired_lock_is_discovered() { + let hosted = hosted_url("npm", "left-pad", "1.3.0", UUID_A, "left-pad-1.3.0.tgz"); + let p = Project::new(); + let lock = lock_with_packages(serde_json::json!({ + "": { "name": "app", "version": "1.0.0" }, + "node_modules/left-pad": { "version": "1.3.0", "resolved": hosted, "integrity": SRI }, + })); + p.write("package-lock.json", format!("\u{feff}{lock}")); + let out = run(&p).await; + assert_refs( + &out, + &[("pkg:npm/left-pad@1.3.0", UUID_A, WiringMode::Hosted)], + ); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + } + #[tokio::test] async fn hosted_and_vendored_entries_in_one_lock() { let hosted = hosted_url("npm", "left-pad", "1.3.0", UUID_A, "left-pad-1.3.0.tgz"); diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index 373e0bc04..e1ec1a6ac 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -239,6 +239,39 @@ async fn package_lock_goldens_round_trip() { npm_flavor("npm/package-lock-v3", &[]).await; } +/// #324: the hosted unwind of a CRLF, tab-indented or BOM-prefixed +/// package-lock.json gives back the lock's original bytes (npm keeps those +/// layouts on its own rewrites and installs from a BOM lock). +#[tokio::test] +#[serial] +async fn package_lock_layouts_round_trip() { + let basic = load("npm/package-lock-v3") + .into_iter() + .find(|c| c.dir.ends_with("basic")) + .expect("npm/package-lock-v3/basic golden"); + let lf = basic.input["package-lock.json"].clone(); + let shapes = [ + ("crlf", lf.replace('\n', "\r\n")), + ("tabs", lf.replace(" ", "\t")), + ("bom", format!("\u{feff}{lf}")), + ( + "bom+crlf+tabs", + format!("\u{feff}{}", lf.replace(" ", "\t").replace('\n', "\r\n")), + ), + ]; + for (shape, pristine) in shapes { + let case = synthetic( + &format!("npm-lock-{shape}"), + &[("package-lock.json", &pristine)], + serde_json::Value::Array(basic.overrides.clone()), + ); + let server = npm_mock(&case).await; + let _env = EnvGuard::set(&[("SOCKET_NPM_REGISTRY", server.uri())]); + let (after, statuses) = run_case(&case).await; + assert_round_trip(&case, &after, &statuses); + } +} + #[tokio::test] #[serial] async fn yarn_classic_goldens_round_trip() {