From e647a94b4ad0ead19c3d1efb9b4e8df67cda5c4f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 09:06:12 -0500 Subject: [PATCH 01/13] Read tarballs, wheels and nupkgs within shared limits, and make a limit an error The tarball reader (npm tarballs, Python sdists) and the zip reader of the vendored-artifact checks (wheels, .nupkg) were sized for patch archives: 64 MiB unpacked, 10,000 entries, 16 MiB for one tarball member. They read whole packages now. A wheel with one compiled extension of 60 MiB, or an npm package of 31,858 files, could not be vendored or checked, and `vendor` said the service's archive "does not carry the patched files" (#2197). Both readers now take their limits from one place, `patch::archive_limits`: 200,000 entries, 512 MiB inflated in one read, and no more than 100 times the archive's own size once past the 64 MiB every archive may still use. The module docs give the packages the numbers were measured on. A member may be as large as what is left of its archive's budget; the tarball reader checks the declared size against that before it allocates. Both readers still hold what they inflate, so 512 MiB plus the archive is what reading one archive may take. Reaching a limit is now an error, never the end of the input (#2330). The tarball reader bounded the gzip stream with `Read::take`, which hands the tar parser an end of input at the limit. Between two entries the parser takes that for the end of the archive, so a second `package/index.js` placed exactly 64 MiB into the stream was never seen by the check for a second entry over a patched file, and the tarball verified. The stream is now read through a reader that fails on the first byte past the budget, and the walk reports that failure whatever the parser made of it. An archive past a limit says which limit, and what it holds or unpacks to where its own headers say: - `vendor --check`, `vex` and `repair` report a committed tarball, wheel, sdist or .nupkg as `vendor_artifact_too_large` (it was `vendor_artifact_unreadable`), and `vendor --check` names the limit. - `vendor` refuses a served Python distribution with `vendor_artifact_too_large`, and fails an npm package with "the patch service's tarball for @ cannot be checked: ". - `repair` reports a download past a limit the way it does for a jar. Three jar tests asserted that the wheel reader refuses a jar of 10,001 entries and 65 MiB; it reads one now, and the assertions are gone. Co-Authored-By: Claude Fable 5.2 --- .../src/patch/archive_limits.rs | 409 +++++++++++++ .../src/patch/jar_members.rs | 15 +- crates/socket-patch-core/src/patch/jvm_jar.rs | 9 +- crates/socket-patch-core/src/patch/mod.rs | 1 + crates/socket-patch-core/src/patch/package.rs | 546 ++++++++++++++---- .../src/vendor/maven_repo.rs | 5 +- .../src/vendor/npm_common.rs | 40 +- crates/socket-patch-core/src/vendor/pypi.rs | 23 +- .../src/vendor/pypi_distribution.rs | 31 +- .../src/vendor/redownload.rs | 31 +- crates/socket-patch-core/src/vendor/reuse.rs | 26 +- .../vendor/test_support/service_fixture.rs | 2 +- crates/socket-patch-core/src/vendor/verify.rs | 494 +++++++++++++--- 13 files changed, 1363 insertions(+), 269 deletions(-) create mode 100644 crates/socket-patch-core/src/patch/archive_limits.rs diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs new file mode 100644 index 0000000000..c370ba8199 --- /dev/null +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -0,0 +1,409 @@ +//! The limits the tarball and zip readers hold an archive to. +//! +//! Two readers decode a whole archive into a map of its members: the +//! tarball reader ([`crate::patch::package`]: npm tarballs, Python sdists) +//! and the zip reader of the vendored-artifact checks +//! (`vendor::verify::read_zip_to_map`: wheels, `.nupkg`). Both were sized +//! for patch archives of a few kilobytes: 64 MiB unpacked, 10,000 entries, +//! 16 MiB for one tarball member. They read whole packages now, and released +//! packages are larger than that, so a patch for one could not be vendored +//! or checked: +//! +//! | Package | Archive | Unpacked | Entries | Largest member | +//! |---|---|---|---|---| +//! | `next-15.1.0.tgz` | 24.1 MiB | 115.0 MiB | 6,873 | 10.2 MiB | +//! | `@mui/icons-material-6.2.1.tgz` | 1.6 MiB | 17.2 MiB | 31,858 | 2.2 MiB | +//! | `@next/swc-linux-x64-gnu-15.1.0.tgz` | 44.2 MiB | 135.7 MiB | 3 | 135.7 MiB | +//! | `onnxruntime-node-1.20.1.tgz` | 66.8 MiB | 180.1 MiB | 36 | 27.3 MiB | +//! | `ansible-11.1.0` (wheel) | 49.0 MiB | 185.1 MiB | 21,105 | 2.7 MiB | +//! | `py_rattler-0.23.2` (wheel) | 20.4 MiB | 55.8 MiB | 69 | 55.4 MiB | +//! | `PyQt6_Qt6-6.8.1` (wheel) | 77.1 MiB | 200.1 MiB | 2,476 | 30.6 MiB | +//! | `xgboost-2.1.3` (wheel) | 146.8 MiB | 239.3 MiB | 47 | 238.5 MiB | +//! | `paddlepaddle-2.6.2` (wheel) | 120.1 MiB | 430.0 MiB | 2,478 | 219.4 MiB | +//! +//! # The limits +//! +//! The sizes an archive declares for its members are the author's claim, so +//! the byte limit is on what is actually inflated; a declared size only +//! refuses an archive sooner. +//! +//! * `max_entries`: 200,000 entries, the jar reader's count +//! ([`crate::patch::jar_members`]). Six times the largest tarball measured +//! above and nine times the largest wheel. +//! * `max_inflated_bytes`: 512 MiB inflated in one read of one archive. +//! Both readers hold what they inflate, so this, beside the archive's own +//! bytes, is what reading one archive may take in memory, and it is half +//! of what the jar reader, which holds a digest per member, may inflate. +//! It is what a download at the patch service's 256 MiB cap unpacks to +//! at 2:1 and one at the registries' 128 MiB cap at 4:1 (compiled wheels +//! sit between 1.6:1 and 4.3:1), the size a committed artifact is read up +//! to, and what the registry extractors may unpack to disk +//! (`vendor::registry_fetch`). Every tarball measured is under half of +//! it. Two wheels measured within the download cap are past it and stay +//! refused: `mkl-2025.0.1` (176.2 MiB, 521.1 MiB unpacked) and +//! `tensorflow_cpu-2.18.0` (219.6 MiB, 945.6 MiB unpacked). +//! * `max_inflate_ratio` past `ratio_floor_bytes`: no more than 100 times +//! the archive's own size, once past the 64 MiB (the old limit) every +//! archive may use, so nothing that was read whole before is refused now. +//! Deflate reaches 1000:1 on a crafted stream. The packages above are +//! between 1.6:1 and 11:1 by their members' bytes, and the tarball of +//! 31,858 small files is 26:1 counted as the tarball reader counts it +//! (below). This keeps a small hostile archive from spending the whole +//! 512 MiB. +//! +//! There is no separate limit on one member: `libxgboost.so` is 238.5 MiB +//! and `_catboost.so` 281.9 MiB, so a member may be as large as what is left +//! of its archive's budget. The tarball reader checks a member's declared +//! size against that before it allocates for it, so a header cannot claim +//! more than the archive's own size allows. +//! +//! For a tarball the bytes counted are those of the tar stream the gzip +//! layer inflates: every member's 512-byte header and padding as well as +//! its content. For a zip they are the members' contents. +//! +//! # A limit is an error +//! +//! [`Bounded`] fails on the first byte past the budget. A reader that stops +//! at its limit (`Read::take`) hands the tar parser an end of input, which +//! the parser takes for the end of the archive when it falls between two +//! entries: every entry after it is then never seen, and no error is +//! raised. The text of a limit error says which limit, and what the archive +//! holds or unpacks to where its own headers say. + +use std::io::Read; + +const KIB: u64 = 1024; +const MIB: u64 = 1024 * KIB; + +/// The limits one read of one archive is held to (see the module docs). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ArchiveLimits { + /// Entries one archive may hold. + pub(crate) max_entries: usize, + /// Bytes one read of one archive may inflate. + pub(crate) max_inflated_bytes: u64, + /// Inflated bytes allowed per archive byte, past `ratio_floor_bytes`. + pub(crate) max_inflate_ratio: u64, + /// What any archive may inflate to, however small it is. + pub(crate) ratio_floor_bytes: u64, +} + +impl ArchiveLimits { + /// The limits of the readers that hold every member in memory. + pub(crate) const IN_MEMORY: Self = Self { + max_entries: 200_000, + max_inflated_bytes: 512 * MIB, + max_inflate_ratio: 100, + ratio_floor_bytes: 64 * MIB, + }; + + /// What one read of an archive of `archive_len` bytes may inflate. + pub(crate) fn budget(&self, archive_len: u64) -> Budget { + let by_ratio = archive_len.saturating_mul(self.max_inflate_ratio); + Budget { + bytes: self + .max_inflated_bytes + .min(self.ratio_floor_bytes.max(by_ratio)), + archive_len, + limits: *self, + } + } + + /// The error text of an archive with more entries than the limit. + /// `found` is the count the archive itself declares (a zip's + /// directory); a tar stream declares none. + pub(crate) fn too_many_entries(&self, found: Option) -> String { + match found { + Some(found) => format!( + "it holds {found} entries, over the limit of {}", + self.max_entries + ), + None => format!( + "it holds more than {} entries, the limit for one archive", + self.max_entries + ), + } + } +} + +/// What an archive says it unpacks to, for the text of a limit error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Unpacked { + /// The sum its directory declares for its members (a zip). + Declared(u64), + /// What it has unpacked plus the size its next member declares (a tar + /// stream, which declares its members one at a time). + AtLeast(u64), + /// Nothing: the limit was met while inflating. + Unknown, +} + +/// The inflated bytes one read of one archive may use. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Budget { + bytes: u64, + archive_len: u64, + limits: ArchiveLimits, +} + +impl Budget { + pub(crate) fn bytes(&self) -> u64 { + self.bytes + } + + /// The limits the budget was taken from. + pub(crate) fn limits(&self) -> &ArchiveLimits { + &self.limits + } + + /// The error text of an archive that unpacks to more than the budget. + pub(crate) fn exceeded(&self, unpacked: Unpacked) -> String { + let limits = &self.limits; + let capped = self.bytes >= limits.max_inflated_bytes; + let unpacks_to = match unpacked { + Unpacked::Declared(bytes) => format!("it unpacks to {}", size(bytes)), + Unpacked::AtLeast(bytes) => format!("it unpacks to at least {}", size(bytes)), + Unpacked::Unknown if capped => { + return format!( + "it unpacks to more than {}, the limit for one archive", + size(limits.max_inflated_bytes) + ) + } + Unpacked::Unknown => format!("it unpacks to more than {}", size(self.bytes)), + }; + if capped { + format!( + "{unpacks_to}, over the limit of {} for one archive", + size(limits.max_inflated_bytes) + ) + } else { + format!( + "{unpacks_to}, over {} times its own size ({}) and the {} every archive may use", + limits.max_inflate_ratio, + size(self.archive_len), + size(limits.ratio_floor_bytes) + ) + } + } +} + +/// `bytes` rounded up to whole KiB below 1 MiB and to whole MiB above, so a +/// size just past a limit never prints as the limit. +fn size(bytes: u64) -> String { + if bytes < MIB { + format!("{} KiB", bytes.div_ceil(KIB)) + } else { + format!("{} MiB", bytes.div_ceil(MIB)) + } +} + +/// A reader that yields at most `budget` bytes of `inner` and fails on the +/// first byte past them (see the module docs). An input of exactly `budget` +/// bytes reads to its end without an error. +pub(crate) struct Bounded { + inner: R, + budget: u64, + read: u64, + over: bool, +} + +impl Bounded { + pub(crate) fn new(inner: R, budget: &Budget) -> Self { + Bounded { + inner, + budget: budget.bytes, + read: 0, + over: false, + } + } + + /// Whether the input holds more than the budget. Once it does every + /// read fails, so a caller that asks after its own read loop cannot + /// take an input cut at the limit for a complete one, whatever the + /// parser in between made of the failed read. + pub(crate) fn over(&self) -> bool { + self.over + } +} + +impl Read for Bounded { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let past_budget = || std::io::Error::other("the input is larger than its limit"); + if self.over { + return Err(past_budget()); + } + if buf.is_empty() { + return Ok(0); + } + // One byte past the budget is asked for at most: that byte, when + // the input has one, is what tells an input cut at the limit from + // one that ends there. + let room = (self.budget - self.read).saturating_add(1); + let want = buf.len().min(usize::try_from(room).unwrap_or(usize::MAX)); + let n = self.inner.read(&mut buf[..want])?; + self.read += n as u64; + if self.read > self.budget { + self.over = true; + return Err(past_budget()); + } + Ok(n) + } +} + +/// `len` bytes that deflate cannot shrink, for the fixtures of the readers' +/// tests. A fixture of zeros alone is a few kilobytes on disk, which past +/// the floor is a bomb by the ratio rule; an honest large archive is large +/// on disk too. +#[cfg(test)] +pub(crate) fn noise(len: usize) -> Vec { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut out = Vec::with_capacity(len + 8); + while out.len() < len { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + out.extend_from_slice(&state.to_le_bytes()); + } + out.truncate(len); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const SMALL: ArchiveLimits = ArchiveLimits { + max_entries: 3, + max_inflated_bytes: 4000, + max_inflate_ratio: 10, + ratio_floor_bytes: 1000, + }; + + #[test] + fn the_budget_is_the_ratio_between_the_floor_and_the_limit() { + // The floor, however small the archive. + assert_eq!(SMALL.budget(0).bytes(), 1000); + assert_eq!(SMALL.budget(100).bytes(), 1000); + // Then ten times the archive. + assert_eq!(SMALL.budget(101).bytes(), 1010); + assert_eq!(SMALL.budget(399).bytes(), 3990); + // Never past the limit. + assert_eq!(SMALL.budget(400).bytes(), 4000); + assert_eq!(SMALL.budget(u64::MAX).bytes(), 4000); + + let limits = ArchiveLimits::IN_MEMORY; + assert_eq!(limits.budget(0).bytes(), 64 * MIB); + // Below 655 KiB the floor is the larger. + assert_eq!(limits.budget(655 * KIB).bytes(), 64 * MIB); + assert_eq!(limits.budget(MIB).bytes(), 100 * MIB); + assert_eq!(limits.budget(6 * MIB).bytes(), 512 * MIB); + } + + #[test] + fn a_limit_error_names_the_limit_and_what_the_archive_says() { + let limits = ArchiveLimits::IN_MEMORY; + assert_eq!( + limits.too_many_entries(Some(200_001)), + "it holds 200001 entries, over the limit of 200000" + ); + assert_eq!( + limits.too_many_entries(None), + "it holds more than 200000 entries, the limit for one archive" + ); + + // Large enough for the whole 512 MiB. + let capped = limits.budget(220 * MIB); + assert_eq!( + capped.exceeded(Unpacked::Declared(946 * MIB)), + "it unpacks to 946 MiB, over the limit of 512 MiB for one archive" + ); + assert_eq!( + capped.exceeded(Unpacked::AtLeast(512 * MIB + 1)), + "it unpacks to at least 513 MiB, over the limit of 512 MiB for one archive" + ); + assert_eq!( + capped.exceeded(Unpacked::Unknown), + "it unpacks to more than 512 MiB, the limit for one archive" + ); + + // A small archive is held to its own size. + let small = limits.budget(65 * KIB); + assert_eq!( + small.exceeded(Unpacked::Unknown), + "it unpacks to more than 64 MiB, over 100 times its own size (65 KiB) and the 64 MiB \ + every archive may use" + ); + let middling = limits.budget(2 * MIB); + assert_eq!( + middling.exceeded(Unpacked::Declared(300 * MIB)), + "it unpacks to 300 MiB, over 100 times its own size (2 MiB) and the 64 MiB every \ + archive may use" + ); + } + + /// A budget of exactly `bytes`, whatever the archive's size. + fn exactly(bytes: u64) -> Budget { + ArchiveLimits { + max_inflated_bytes: bytes, + ratio_floor_bytes: bytes, + ..SMALL + } + .budget(0) + } + + /// How many bytes a reader hands out before it fails or ends. + fn drain(reader: &mut impl Read, chunk: usize) -> (usize, bool) { + let mut buf = vec![0u8; chunk]; + let mut total = 0; + loop { + match reader.read(&mut buf) { + Ok(0) => return (total, false), + Ok(n) => total += n, + Err(_) => return (total, true), + } + } + } + + #[test] + fn bounded_fails_on_the_first_byte_past_the_budget() { + let budget = exactly(1000); + for chunk in [1, 7, 512, 1000, 4096] { + // An input of exactly the budget ends without an error. + let exact = vec![1u8; 1000]; + let mut reader = Bounded::new(&exact[..], &budget); + assert_eq!(drain(&mut reader, chunk), (1000, false), "chunk {chunk}"); + assert!(!reader.over()); + + // One byte more is an error, never an end of input, and stays + // one on every later read. + let longer = vec![1u8; 1001]; + let mut reader = Bounded::new(&longer[..], &budget); + let (read, failed) = drain(&mut reader, chunk); + assert!(failed, "chunk {chunk}"); + assert!(read <= 1000, "chunk {chunk}: {read} bytes handed out"); + assert!(reader.over()); + assert!(reader.read(&mut [0u8; 8]).is_err()); + } + } + + /// The reader never takes more than one byte past the budget from its + /// input, however much input there is: a bomb costs the budget, not its + /// own size. + #[test] + fn bounded_reads_one_byte_past_the_budget_at_most() { + struct Endless(u64); + impl Read for Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.0 += buf.len() as u64; + buf.fill(0); + Ok(buf.len()) + } + } + let budget = exactly(10_000); + let mut reader = Bounded::new(Endless(0), &budget); + let (read, failed) = drain(&mut reader, 4096); + assert!(failed); + assert!(read <= 10_000); + assert_eq!(reader.inner.0, 10_001); + } +} diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index 09c2090379..3127c2b7f3 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -1,12 +1,13 @@ //! Bounded, streaming reads of a JVM jar. //! //! The zip reader the vendored-artifact checks share -//! (`vendor::verify::read_zip_to_map`) was sized for Python wheels: 10,000 -//! entries, 64 MiB inflated, every member held in memory. Released jars pass -//! both (`hive-exec-3.1.3.jar`: 23,728 entries, 93 MiB; -//! `poi-ooxml-full-5.2.5.jar`: 15,181 entries), so a patch for one could -//! never be applied, and comparing two jars through it held every member of -//! both at once. +//! (`vendor::verify::read_zip_to_map`) holds every member in memory, and +//! when jars were read through it, it stopped at 10,000 entries and 64 MiB +//! inflated. Released jars pass both (`hive-exec-3.1.3.jar`: 23,728 +//! entries, 93 MiB; `poi-ooxml-full-5.2.5.jar`: 15,181 entries), so a patch +//! for one could never be applied, and comparing two jars through it held +//! every member of both at once. (Its limits are now those of +//! [`crate::patch::archive_limits`]; it still holds what it inflates.) //! //! Here each member is inflated through a hasher and dropped, so one pass //! holds a digest per member, whatever the jar's size. @@ -1026,8 +1027,6 @@ mod tests { OLD_BYTES + 1024 * 1024, &[("a/B.class", b"code")], ); - // The reader this module replaces for jars refuses it. - assert!(crate::vendor::verify::read_zip_bytes_to_map(&bytes).is_err()); let digests = Digests::of_bytes(&bytes).unwrap(); assert_eq!(digests.len(), OLD_ENTRIES + 2); let expected: [u8; 32] = Sha256::digest(b"code").into(); diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index b1107077de..1d7ed2f1fc 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -1663,10 +1663,10 @@ mod tests { } } - /// A jar over both limits of the wheel reader the swap used to compare - /// through (10,000 entries, 64 MiB inflated) is swapped and rolled back - /// like any other. It used to be refused as "the patch service's jar is - /// unreadable". + /// A jar over both limits the wheel reader had when the swap compared + /// through it (10,000 entries, 64 MiB inflated) is swapped and rolled + /// back like any other. It used to be refused as "the patch service's + /// jar is unreadable". #[tokio::test] async fn a_jar_over_the_wheel_reader_limits_swaps_and_rolls_back() { use crate::patch::jar_members::testing::big_jar; @@ -1674,7 +1674,6 @@ mod tests { const BYTES: u64 = 65 * 1024 * 1024; let original = big_jar(ENTRIES, BYTES, &[("META-INF/NOTICE.txt", b"pristine")]); let service = big_jar(ENTRIES, BYTES, &[("META-INF/NOTICE.txt", b"patched")]); - assert!(crate::vendor::verify::read_zip_bytes_to_map(&service).is_err()); let (_server, cfg) = mock_service(&service, &service).await; let d = tempfile::tempdir().unwrap(); diff --git a/crates/socket-patch-core/src/patch/mod.rs b/crates/socket-patch-core/src/patch/mod.rs index c653345e85..39354a78a0 100644 --- a/crates/socket-patch-core/src/patch/mod.rs +++ b/crates/socket-patch-core/src/patch/mod.rs @@ -1,5 +1,6 @@ pub mod apply; pub mod apply_lock; +pub(crate) mod archive_limits; pub mod conda_copy; // `fresh_copy`/`remove_tree` are shared by the Go redirect and the vendor backends. pub mod copy_tree; diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 433ef5e7bc..2f8d8574f6 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -3,7 +3,14 @@ //! The vendored and hosted backends read registry tarballs (npm `.tgz`, //! PyPI sdists) into memory through these helpers. Entry paths are //! **normalized** (the `package/` prefix is stripped), and every reader -//! enforces the size, entry-count and path-safety limits below. +//! enforces the path-safety gate below and the size and entry-count limits +//! of `patch::archive_limits`, where the numbers and the packages they +//! were measured on are. +//! +//! A tarball past a limit is [`ArchiveError::TooLarge`], and the text says +//! which limit. Reaching a limit is never read as the end of the archive: +//! an entry that lies past it is one the installers extract, so a reader +//! that stopped there would vouch for a tarball it has not seen the end of. use std::collections::HashMap; use std::io::Read; @@ -13,33 +20,21 @@ use flate2::read::GzDecoder; use tar::Archive; use crate::patch::apply::{is_safe_relative_subpath, normalize_file_path}; +use crate::patch::archive_limits::{ArchiveLimits, Bounded, Budget, Unpacked}; -/// Maximum cumulative *decompressed* bytes we accept from a single -/// archive. Real socket-patch archives are tiny (kilobytes); 64 MiB is a -/// generous ceiling. Beyond this we assume gzip/tar bomb and refuse. -const MAX_TOTAL_DECOMPRESSED_BYTES: u64 = 64 * 1024 * 1024; - -/// Maximum size of any single archive entry, in bytes. Caps the buffer -/// we'll allocate per entry, defusing header-driven `with_capacity` -/// allocation attacks. -const MAX_ENTRY_BYTES: u64 = 16 * 1024 * 1024; - -/// Maximum number of entries in an archive. Defuses -/// "tar-of-a-million-empty-files" memory-exhaustion attacks against -/// the in-memory `HashMap`. -const MAX_ENTRIES: usize = 10_000; - -/// Errors produced while reading a patch archive. +/// Errors produced while reading a tarball. #[derive(Debug, thiserror::Error)] pub enum ArchiveError { #[error("archive I/O error: {0}")] Io(#[from] std::io::Error), #[error("entry path {0:?} escapes the archive root")] UnsafePath(String), - #[error("entry {path:?} is {size} bytes (max {max})")] - EntryTooLarge { path: String, size: u64, max: u64 }, - #[error("archive contains more than {0} entries")] - TooManyEntries(usize), + /// The archive is past a limit the readers hold one to: its entry + /// count, what it may unpack to, or what it may unpack to for its own + /// size. The text names the limit, and what the archive holds or + /// unpacks to where its own headers say. + #[error("{0}")] + TooLarge(String), /// Strict decoding only: the archive is not in the canonical shape an /// installer extracts exactly as decoded (see /// [`read_archive_bytes_to_map_strict`]). @@ -47,6 +42,14 @@ pub enum ArchiveError { NonCanonical(String), } +impl ArchiveError { + /// Whether the archive was refused for its size, not for what it holds: + /// its contents were not checked. + pub fn is_too_large(&self) -> bool { + matches!(self, ArchiveError::TooLarge(_)) + } +} + /// The key two archive member names collide under on a case-insensitive /// filesystem, or `None` when the name is outside the strict shape: ASCII /// only (no Unicode case-folding / normalization aliases), no backslash, @@ -76,8 +79,9 @@ pub(crate) fn canonical_member_key(name: &str) -> Option { /// Returns an error if any entry path is absolute or contains `..` /// components. Symlinks and other non-regular entries are silently /// skipped. The reader is hard-capped against decompression-bomb / -/// memory-exhaustion attacks: cumulative decompressed bytes, -/// per-entry size, and entry count are all bounded. +/// memory-exhaustion attacks: the bytes it inflates (in all, and for the +/// archive's own size), the size a member declares, and the entry count +/// are all bounded. /// /// Note: we never call `tar::Archive::unpack`; the bytes are buffered /// and later written through `apply_file_patch_at` to an explicit @@ -103,13 +107,15 @@ pub fn read_archive_to_map(archive_path: &Path) -> Result Result Result>, ArchiveError> { - read_archive_from_reader(bytes, false, true) + read_archive_from_reader(bytes, &budget_of(bytes), false, true) +} + +/// What one read of the in-memory tarball `bytes` may inflate. +fn budget_of(bytes: &[u8]) -> Budget { + ArchiveLimits::IN_MEMORY.budget(bytes.len() as u64) +} + +/// Which limit the tarball `bytes` is past, in the words of +/// [`ArchiveError::TooLarge`]; `None` when it is within them all. For the +/// message of a caller that holds only a reader's routing tag. +pub(crate) fn limit_exceeded(bytes: &[u8]) -> Option { + match read_archive_from_reader(bytes, &budget_of(bytes), false, false) { + Err(ArchiveError::TooLarge(why)) => Some(why), + _ => None, + } } /// [`read_archive_bytes_to_map`] that additionally refuses any archive an @@ -140,7 +161,7 @@ pub fn read_archive_bytes_to_map(bytes: &[u8]) -> Result pub fn read_archive_bytes_to_map_strict( bytes: &[u8], ) -> Result>, ArchiveError> { - read_archive_from_reader(bytes, true, true) + read_archive_from_reader(bytes, &budget_of(bytes), true, true) } /// [`read_archive_bytes_to_map`] keyed the way npm-family installers @@ -154,7 +175,7 @@ pub fn read_archive_bytes_to_map_strict( pub(crate) fn read_archive_bytes_to_map_any_root( bytes: &[u8], ) -> Result>, ArchiveError> { - let raw = read_archive_from_reader(bytes, false, false)?; + let raw = read_archive_from_reader(bytes, &budget_of(bytes), false, false)?; let mut out: HashMap> = HashMap::new(); let mut ambiguous: std::collections::HashSet = std::collections::HashSet::new(); let mut roots: HashMap = HashMap::new(); @@ -201,9 +222,57 @@ pub(crate) fn read_archive_bytes_to_map_any_root( /// Unlike [`read_archive_bytes_to_map_strict`] this judges only the listed /// files: an upstream tarball with a link, a non-ASCII name or a case twin /// somewhere else still passes. +/// +/// Every entry up to the tar end-of-archive marker is judged or the call +/// fails: a tarball past a limit is [`ArchiveError::TooLarge`], never one +/// whose entries beyond the limit went unseen. pub(crate) fn shadowed_member( bytes: &[u8], files: &[String], +) -> Result, ArchiveError> { + shadowed_member_within(bytes, files, &budget_of(bytes)) +} + +/// [`shadowed_member`] within `budget`. +fn shadowed_member_within( + bytes: &[u8], + files: &[String], + budget: &Budget, +) -> Result, ArchiveError> { + let mut inflated = Bounded::new(GzDecoder::new(bytes), budget); + let shadowed = shadowed_in_tar(&mut inflated, files, budget); + within_budget(shadowed, &inflated, budget) +} + +/// The outcome of a walk over `inflated`, unless the walk met the budget: +/// that is the error, whatever the tar parser made of the failed read. +fn within_budget( + walked: Result, + inflated: &Bounded, + budget: &Budget, +) -> Result { + match walked { + Err(e) if e.is_too_large() => Err(e), + _ if inflated.over() => Err(ArchiveError::TooLarge(budget.exceeded(Unpacked::Unknown))), + walked => walked, + } +} + +/// Count one more entry of the archive against the entry limit. +fn count_entry(entry_count: &mut usize, budget: &Budget) -> Result<(), ArchiveError> { + *entry_count += 1; + let limits = budget.limits(); + if *entry_count > limits.max_entries { + return Err(ArchiveError::TooLarge(limits.too_many_entries(None))); + } + Ok(()) +} + +/// [`shadowed_member`] over the tar stream `inflated`. +fn shadowed_in_tar( + inflated: R, + files: &[String], + budget: &Budget, ) -> Result, ArchiveError> { use tar::EntryType; @@ -227,15 +296,11 @@ pub(crate) fn shadowed_member( .iter() .map(|file| (fold(normalize_file_path(file)), 0)) .collect(); - let bounded = GzDecoder::new(bytes).take(MAX_TOTAL_DECOMPRESSED_BYTES); - let mut tar = Archive::new(bounded); + let mut tar = Archive::new(inflated); let mut entry_count: usize = 0; for entry in tar.entries()? { let entry = entry?; - entry_count += 1; - if entry_count > MAX_ENTRIES { - return Err(ArchiveError::TooManyEntries(MAX_ENTRIES)); - } + count_entry(&mut entry_count, budget)?; let entry_type = entry.header().entry_type(); if matches!( entry_type, @@ -274,23 +339,37 @@ pub(crate) fn shadowed_member( pub(crate) fn read_sdist_tar_bytes_to_map_strict( bytes: &[u8], ) -> Result>, ArchiveError> { - read_archive_from_reader(bytes, true, false) + read_archive_from_reader(bytes, &budget_of(bytes), true, false) } /// The shared decoder behind [`read_archive_to_map`] and /// [`read_archive_bytes_to_map`]: gunzip → tar walk with every cap and the /// post-normalization path-safety gate (plus the canonical-shape gate when -/// `strict`). +/// `strict`). `budget` is what the gzip layer may inflate, for the archive +/// `reader` holds. fn read_archive_from_reader( reader: R, + budget: &Budget, + strict: bool, + strip_package_prefix: bool, +) -> Result>, ArchiveError> { + // Hard-cap decompressed bytes to defuse gzip / tar bombs. The first + // byte past the budget fails the read, and the walk with it: a reader + // that only stopped there would hand the tar parser an end of input, + // which between two entries reads as the end of the archive. + let mut inflated = Bounded::new(GzDecoder::new(reader), budget); + let members = members_of_tar(&mut inflated, budget, strict, strip_package_prefix); + within_budget(members, &inflated, budget) +} + +/// [`read_archive_from_reader`] over the tar stream `inflated`. +fn members_of_tar( + inflated: R, + budget: &Budget, strict: bool, strip_package_prefix: bool, ) -> Result>, ArchiveError> { - // Hard-cap decompressed bytes to defuse gzip / tar bombs. Reads - // beyond the limit yield EOF, which the tar parser surfaces as a - // truncated-archive error. - let bounded = GzDecoder::new(reader).take(MAX_TOTAL_DECOMPRESSED_BYTES); - let mut tar = Archive::new(bounded); + let mut tar = Archive::new(inflated); let mut out: HashMap> = HashMap::new(); // Strict mode: canonical keys of every file / directory seen. @@ -300,10 +379,7 @@ fn read_archive_from_reader( for entry in tar.entries()? { let mut entry = entry?; - entry_count += 1; - if entry_count > MAX_ENTRIES { - return Err(ArchiveError::TooManyEntries(MAX_ENTRIES)); - } + count_entry(&mut entry_count, budget)?; let entry_type = entry.header().entry_type(); if strict { @@ -412,20 +488,21 @@ fn read_archive_from_reader( return Err(ArchiveError::UnsafePath(path_str)); } - // The header-declared size is attacker-controlled. Reject - // oversize entries *before* allocating so a single u64::MAX - // claim can't OOM the process via `Vec::with_capacity`. + // The header-declared size is attacker-controlled. Reject a + // member that does not fit in what is left of the archive's budget + // *before* allocating, so a single u64::MAX claim can't OOM the + // process via `Vec::with_capacity`: what a header may claim is + // bounded by the budget, and so by the archive's own size. let size = entry.size(); - if size > MAX_ENTRY_BYTES { - return Err(ArchiveError::EntryTooLarge { - path: path_str, - size, - max: MAX_ENTRY_BYTES, - }); + let unpacked = entry.raw_file_position(); + if size > budget.bytes().saturating_sub(unpacked) { + return Err(ArchiveError::TooLarge( + budget.exceeded(Unpacked::AtLeast(unpacked.saturating_add(size))), + )); } - // `size` is bounded above by MAX_ENTRY_BYTES (16 MiB), so the - // cast to `usize` is safe on all targets we support. + // `size` is within the budget (512 MiB at most), so the cast to + // `usize` is safe on all targets we support. let mut bytes = Vec::with_capacity(size as usize); entry.read_to_end(&mut bytes)?; out.insert(normalized, bytes); @@ -437,6 +514,7 @@ fn read_archive_from_reader( #[cfg(test)] mod tests { use super::*; + use crate::patch::archive_limits::noise; use flate2::write::GzEncoder; use flate2::Compression; use std::io::Write; @@ -837,20 +915,202 @@ mod tests { gz.finish().unwrap(); } - /// The raw `entries` (name, ustar type flag, data) as a `.tar.gz`. - fn raw_tar_gz(entries: &[(&str, u8, &[u8])]) -> Vec { + /// The raw `entries` (name, ustar type flag, data) as a tar stream, + /// without the end-of-archive marker. + fn raw_tar(entries: &[(&str, u8, &[u8])]) -> Vec { let mut tar_bytes = Vec::new(); for (name, kind, data) in entries { tar_bytes.extend_from_slice(&ustar_block(name.as_bytes(), *kind, data.len() as u64)); tar_bytes.extend_from_slice(data); tar_bytes.extend(std::iter::repeat_n(0u8, (512 - (data.len() % 512)) % 512)); } - tar_bytes.extend([0u8; 1024]); + tar_bytes + } + + fn gzip(bytes: &[u8]) -> Vec { let mut gz = GzEncoder::new(Vec::new(), Compression::default()); - gz.write_all(&tar_bytes).unwrap(); + gz.write_all(bytes).unwrap(); gz.finish().unwrap() } + /// The raw `entries` (name, ustar type flag, data) as a `.tar.gz`. + fn raw_tar_gz(entries: &[(&str, u8, &[u8])]) -> Vec { + let mut tar_bytes = raw_tar(entries); + tar_bytes.extend([0u8; 1024]); + gzip(&tar_bytes) + } + + const FILE: u8 = b'0'; + const DIR: u8 = b'5'; + const MIB: usize = 1024 * 1024; + + /// A budget of exactly `inflated` bytes, whatever the archive's size. + fn budget(inflated: u64) -> Budget { + ArchiveLimits { + max_entries: 1000, + max_inflated_bytes: inflated, + max_inflate_ratio: 1, + ratio_floor_bytes: inflated, + } + .budget(0) + } + + fn too_large(result: Result) -> String { + match result { + Err(ArchiveError::TooLarge(why)) => why, + other => panic!("expected ArchiveError::TooLarge, got {other:?}"), + } + } + + /// The limits were 64 MiB unpacked, 16 MiB for one member and 10,000 + /// entries. A package past each of them is read, as long as it is as + /// large on disk as an honest one. + #[test] + fn a_tarball_past_the_old_limits_is_read() { + let big = vec![0u8; 40 * MIB]; + let filler = noise(MIB); + let tgz = raw_tar_gz(&[ + ("package/index.js", FILE, b"patched"), + // One member of 40 MiB, then 80 MiB in all. + ("package/a.node", FILE, &big), + ("package/b.node", FILE, &big), + ("package/filler.bin", FILE, &filler), + ]); + assert!(tgz.len() > MIB && tgz.len() < 2 * MIB, "{}", tgz.len()); + let map = read_archive_bytes_to_map(&tgz).unwrap(); + assert_eq!(map.len(), 4); + assert_eq!(map["index.js"], b"patched"); + assert_eq!(map["a.node"].len(), 40 * MIB); + assert_eq!(map["b.node"].len(), 40 * MIB); + assert_eq!(map["filler.bin"], filler); + assert_eq!(read_archive_bytes_to_map_strict(&tgz).unwrap().len(), 4); + assert_eq!( + shadowed_member(&tgz, &["package/index.js".to_string()]).unwrap(), + None + ); + + // 31,858 files in `@mui/icons-material`; the limit was 10,000. + let names: Vec = (0..12_000).map(|i| format!("package/f{i}.js")).collect(); + let entries: Vec<(&str, u8, &[u8])> = names + .iter() + .map(|name| (name.as_str(), FILE, &b"x"[..])) + .collect(); + assert_eq!( + read_archive_bytes_to_map(&raw_tar_gz(&entries)) + .unwrap() + .len(), + 12_000 + ); + } + + /// An entry an installer extracts over a patched file is found where + /// the old limit fell. The second `package/index.js` starts exactly + /// 64 MiB into the tar stream: the reader used to stop there, take the + /// end of its input for the end of the archive, and report no second + /// entry and the first one's bytes. + #[test] + fn a_second_entry_past_the_old_64_mib_mark_is_seen() { + let files = vec!["package/index.js".to_string()]; + let filler = noise(MIB); + let pad = vec![0u8; 16 * MIB - 512]; + // 8 blocks of package files, the filler's 2049, three pads of + // 16 MiB each with their headers, and a last pad up to the mark. + let last = vec![0u8; 64 * MIB - 8 * 512 - (MIB + 512) - 3 * 16 * MIB - 512]; + let entries: Vec<(&str, u8, &[u8])> = vec![ + ("package/", DIR, b""), + ("package/index.js", FILE, b"patched"), + ("package/lib/", DIR, b""), + ("package/lib/util.js", FILE, b"patched"), + ("package/README.md", FILE, b"docs"), + ("package/filler.bin", FILE, &filler), + ("package/pad1.bin", FILE, &pad), + ("package/pad2.bin", FILE, &pad), + ("package/pad3.bin", FILE, &pad), + ("package/pad4.bin", FILE, &last), + ]; + assert_eq!(raw_tar(&entries).len(), 64 * MIB, "the old limit"); + let mut shadowing = entries.clone(); + shadowing.push(("package/index.js", FILE, b"original")); + let tgz = raw_tar_gz(&shadowing); + + assert_eq!( + shadowed_member(&tgz, &files).unwrap(), + Some("index.js".to_string()) + ); + // The map holds what the installers extract: the later entry. + assert_eq!( + read_archive_bytes_to_map(&tgz).unwrap()["index.js"], + b"original" + ); + // A second entry is refused outright where the tarball is to be + // reused as it is. + assert!(matches!( + read_archive_bytes_to_map_strict(&tgz), + Err(ArchiveError::NonCanonical(_)) + )); + // Without the second entry the same tarball is clean. + let clean = raw_tar_gz(&entries); + assert_eq!(shadowed_member(&clean, &files).unwrap(), None); + assert_eq!( + read_archive_bytes_to_map(&clean).unwrap()["index.js"], + b"patched" + ); + } + + /// Wherever the limit falls in a tarball, the walk either reaches the + /// second entry or fails with the limit's error. It never ends early + /// without one: a limit between two entries used to read as the end of + /// the archive, so raising the limit alone would only have moved the + /// place a second entry hides. + #[test] + fn a_limit_is_an_error_wherever_it_falls() { + let files = vec!["package/index.js".to_string()]; + let pad = vec![7u8; 3 * 512]; + let entries: Vec<(&str, u8, &[u8])> = vec![ + ("package/index.js", FILE, b"patched"), + ("package/pad.bin", FILE, &pad), + ("package/index.js", FILE, b"original"), + ]; + let second_entry = raw_tar(&entries[..2]).len() as u64; + let mut tar_bytes = raw_tar(&entries); + // What the tar reader takes: every entry and one block of the + // end-of-archive marker. + let consumed = tar_bytes.len() as u64 + 512; + tar_bytes.extend([0u8; 1024]); + let tgz = gzip(&tar_bytes); + + for limit in 0..=consumed + 600 { + let budget = budget(limit); + let shadowed = shadowed_member_within(&tgz, &files, &budget); + let map = read_archive_from_reader(&tgz[..], &budget, false, true); + if limit >= consumed { + assert_eq!(shadowed.unwrap(), Some("index.js".to_string()), "{limit}"); + assert_eq!(map.unwrap()["index.js"], b"original", "{limit}"); + continue; + } + let why = budget.exceeded(Unpacked::Unknown); + assert_eq!(too_large(shadowed), why, "limit {limit}"); + // A member whose header says it does not fit is refused by + // that header, before it is read. + let why_map = too_large(map); + assert!( + why_map == why || why_map.starts_with("it unpacks to at least "), + "limit {limit}: {why_map}" + ); + } + // The case that was silent: the limit exactly where the second + // entry's header starts. + let at_entry = budget(second_entry); + assert_eq!( + too_large(shadowed_member_within(&tgz, &files, &at_entry)), + "it unpacks to more than 3 KiB, the limit for one archive" + ); + assert_eq!( + too_large(read_archive_from_reader(&tgz[..], &at_entry, false, true)), + "it unpacks to more than 3 KiB, the limit for one archive" + ); + } + /// npm-family installers strip the first path segment whatever it is, /// extract links as well as files, and let a later entry win. A patched /// file is shadowed when another entry lands on its path or where one @@ -859,9 +1119,7 @@ mod tests { /// this check's business. #[test] fn shadowed_member_judges_only_the_listed_files() { - const FILE: u8 = b'0'; const SYMLINK: u8 = b'2'; - const DIR: u8 = b'5'; let files = vec!["package/index.js".to_string(), "lib/util.js".to_string()]; let base: &[(&str, u8, &[u8])] = &[ ("package/", DIR, b""), @@ -906,89 +1164,121 @@ mod tests { #[test] fn test_read_archive_rejects_oversize_entry_header() { - // Forge a header that claims a 1 GiB entry — well over - // MAX_ENTRY_BYTES — backed by tiny actual data. Without the - // size check, `Vec::with_capacity` would attempt the 1 GiB - // allocation. + // Forge a header that claims a 1 GiB entry backed by tiny actual + // data. Without the size check, `Vec::with_capacity` would attempt + // the 1 GiB allocation. The claim is held to what an archive of + // these few hundred bytes may unpack to, and refused unread. let dir = tempfile::tempdir().unwrap(); let archive = dir.path().join("oversize.tar.gz"); let entry = raw_entry(b"big.bin", 1024 * 1024 * 1024, b"tiny"); write_raw_tar_gz(&archive, &[entry]); - let err = read_archive_to_map(&archive).unwrap_err(); - assert!( - matches!(err, ArchiveError::EntryTooLarge { .. }), - "expected EntryTooLarge, got {:?}", - err + assert_eq!( + too_large(read_archive_to_map(&archive)), + "it unpacks to at least 1025 MiB, over 100 times its own size (1 KiB) and the \ + 64 MiB every archive may use" + ); + // A claim past what is left of the budget is refused the same way + // further into an archive. + let padding = vec![0u8; 512]; + let tgz = raw_tar_gz(&[("package/a.bin", FILE, &padding)]); + let mut tar_bytes = raw_tar(&[("package/a.bin", FILE, &padding)]); + tar_bytes.extend(raw_entry(b"package/b.bin", 4096, b"tiny")); + tar_bytes.extend([0u8; 1024]); + let claim = gzip(&tar_bytes); + assert_eq!( + read_archive_from_reader(&tgz[..], &budget(4096), false, true) + .unwrap() + .len(), + 1 + ); + assert_eq!( + too_large(read_archive_from_reader( + &claim[..], + &budget(4096), + false, + true + )), + "it unpacks to at least 6 KiB, over the limit of 4 KiB for one archive" ); } #[test] fn test_read_archive_rejects_too_many_entries() { - // Build an archive with one more entry than MAX_ENTRIES. Each - // entry is empty so the archive itself is small. - let dir = tempfile::tempdir().unwrap(); - let archive = dir.path().join("many.tar.gz"); - let entries: Vec> = (0..(MAX_ENTRIES + 1)) - .map(|i| raw_entry(format!("f{i}").as_bytes(), 0, b"")) - .collect(); - write_raw_tar_gz(&archive, &entries); + // One more entry than the limit. Each entry is empty so the + // archive itself is small. + let limits = ArchiveLimits { + max_entries: 50, + ..ArchiveLimits::IN_MEMORY + }; + let tgz_of = |count: usize| { + let names: Vec = (0..count).map(|i| format!("package/f{i}")).collect(); + let entries: Vec<(&str, u8, &[u8])> = names + .iter() + .map(|name| (name.as_str(), FILE, &b""[..])) + .collect(); + raw_tar_gz(&entries) + }; + let files = vec!["package/f0".to_string()]; - let err = read_archive_to_map(&archive).unwrap_err(); - assert!( - matches!(err, ArchiveError::TooManyEntries(_)), - "expected TooManyEntries, got {:?}", - err + let at_limit = tgz_of(50); + let budget = limits.budget(at_limit.len() as u64); + assert_eq!( + read_archive_from_reader(&at_limit[..], &budget, false, true) + .unwrap() + .len(), + 50 + ); + assert_eq!( + shadowed_member_within(&at_limit, &files, &budget).unwrap(), + None + ); + + let over = tgz_of(51); + let budget = limits.budget(over.len() as u64); + let why = "it holds more than 50 entries, the limit for one archive"; + assert_eq!( + too_large(read_archive_from_reader(&over[..], &budget, false, true)), + why + ); + assert_eq!( + too_large(shadowed_member_within(&over, &files, &budget)), + why ); } #[test] - fn test_read_archive_decompression_bomb_truncated() { - // Build a tar containing one entry that legitimately fits - // under MAX_ENTRY_BYTES but whose total content makes the - // decompressed stream exceed MAX_TOTAL_DECOMPRESSED_BYTES. - // We do this by chaining many MAX_ENTRY_BYTES-sized entries. - // - // The `Read::take(MAX_TOTAL_DECOMPRESSED_BYTES)` wrapper - // truncates reads beyond the cap. After the cap is exhausted, - // the next `entries()` iteration returns a malformed-archive - // I/O error — which surfaces as `ArchiveError::Io`. We accept - // either `Io` or `TooManyEntries` as evidence the bomb was - // defused (whichever defense fires first). + fn test_read_archive_decompression_bomb_is_refused() { + // Five members of 16 MiB of zeros: 80 MiB of tar stream in an + // archive of some 80 KiB, which gzip shrinks a thousandfold. An + // archive that small may unpack to 64 MiB and no more, however + // high the limit for a large one is. let dir = tempfile::tempdir().unwrap(); let archive = dir.path().join("bomb.tar.gz"); + let chunk = vec![0u8; 16 * MIB - 1]; + let entries: Vec> = [&b"a.bin"[..], b"b.bin", b"c.bin", b"d.bin", b"e.bin"] + .iter() + .map(|name| raw_entry(name, chunk.len() as u64, &chunk)) + .collect(); + write_raw_tar_gz(&archive, &entries); + let on_disk = std::fs::metadata(&archive).unwrap().len(); + assert!(on_disk < 128 * 1024, "{on_disk}"); - // Five entries of (MAX_ENTRY_BYTES - 1) bytes each (~16 MiB, - // ~80 MiB declared in total), but gzip compresses zeroes ~1000x - // so the on-disk archive is small. - // We don't need to *exceed* 64 MiB — the cap is enforced - // strictly, so an entry that crosses it will be truncated. - let chunk = vec![0u8; (MAX_ENTRY_BYTES - 1) as usize]; - let entry1 = raw_entry(b"a.bin", chunk.len() as u64, &chunk); - let entry2 = raw_entry(b"b.bin", chunk.len() as u64, &chunk); - let entry3 = raw_entry(b"c.bin", chunk.len() as u64, &chunk); - let entry4 = raw_entry(b"d.bin", chunk.len() as u64, &chunk); - // Four payloads come to 4 bytes under the 64 MiB cap; a fifth - // pushes past it. - let entry5 = raw_entry(b"e.bin", chunk.len() as u64, &chunk); - write_raw_tar_gz(&archive, &[entry1, entry2, entry3, entry4, entry5]); - - let result = read_archive_to_map(&archive); - // Either we get an Io error from truncation or the read - // succeeds with the first ~4 entries — both prove the cap - // prevented unbounded growth. Failure mode we want to RULE - // OUT: reading all 5 entries (~80 MiB) without error. - match result { - Err(_) => { /* defused via Io / truncation */ } - Ok(map) => { - // If parsing didn't error, ensure we didn't ingest all 5. - assert!( - map.len() < 5, - "decompression cap failed: ingested {} entries (~{} MiB)", - map.len(), - map.len() * (MAX_ENTRY_BYTES as usize - 1) / (1024 * 1024) - ); - } - } + // The fourth member, with the headers before it, does not fit in + // what is left of the 64 MiB: its header says so, and it is + // refused before it is read. + let why = too_large(read_archive_to_map(&archive)); + assert!( + why.starts_with("it unpacks to at least 65 MiB, over 100 times its own size (") + && why.ends_with(" KiB) and the 64 MiB every archive may use"), + "{why}" + ); + // A reader that holds no member meets the limit while inflating. + let bytes = std::fs::read(&archive).unwrap(); + let why = too_large(shadowed_member(&bytes, &["a.bin".to_string()])); + assert!( + why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size ("), + "{why}" + ); } } diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index da7a93d28c..25a1a3adf3 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -4802,8 +4802,8 @@ mod tests { assert!(detail.contains("patch service request failed"), "{detail}"); } - /// A jar over the limits of the reader jars used to share with Python - /// wheels (10,000 entries, 64 MiB inflated) vendors, verifies (what + /// A jar over the limits the reader jars used to share with Python + /// wheels had then (10,000 entries, 64 MiB inflated) vendors, verifies (what /// `vex` and `vendor --check` ask), passes an online re-run's comparison /// with upstream, and is repaired. #[tokio::test] @@ -4815,7 +4815,6 @@ mod tests { let (dir, blobs, installed, record) = reactor_fixture(true).await; let root = dir.path(); let upstream = big_jar(10_001, 65 * 1024 * 1024, &[(JAR_FILE, PRISTINE)]); - assert!(crate::vendor::verify::read_zip_bytes_to_map(&upstream).is_err()); tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &upstream) .await .unwrap(); diff --git a/crates/socket-patch-core/src/vendor/npm_common.rs b/crates/socket-patch-core/src/vendor/npm_common.rs index 0b1b644ef4..55fa8509fa 100644 --- a/crates/socket-patch-core/src/vendor/npm_common.rs +++ b/crates/socket-patch-core/src/vendor/npm_common.rs @@ -451,12 +451,26 @@ async fn try_service_pack( // The SRI proves only that the transfer is intact: require the tarball to // carry every patched file at its afterHash before reporting the package // patched and wiring the lock to it. - if !tgz_bytes_match_after_hashes(&archive.bytes, record) { - return Err(policy.miss(format!( - "prebuilt tarball for {}@{} does not carry the patched files at their \ - recorded paths", - coords.name, coords.version - ))); + match tgz_bytes_match_after_hashes(&archive.bytes, record) { + Ok(true) => {} + Ok(false) => { + return Err(policy.miss(format!( + "prebuilt tarball for {}@{} does not carry the patched files at their \ + recorded paths", + coords.name, coords.version + ))); + } + // Past a limit its contents were not read: it is too large, not a + // tarball without the patch. + Err(limit) => { + return Err(policy.hard( + super::verify::ARTIFACT_TOO_LARGE, + format!( + "the patch service's tarball for {}@{} cannot be checked: {limit}", + coords.name, coords.version + ), + )); + } } if dry_run { return Ok(Box::new(( @@ -563,15 +577,19 @@ async fn staged_pack_from_service_bytes( /// True when the downloaded npm tarball (`package/`-rooted, like the /// `record.files` keys) has every patched file hashing to its `afterHash`. -fn tgz_bytes_match_after_hashes(bytes: &[u8], record: &PatchRecord) -> bool { +/// `Err` is a tarball past a limit the reader holds it to, which says +/// nothing of its files: the text names the limit. +fn tgz_bytes_match_after_hashes(bytes: &[u8], record: &PatchRecord) -> Result { use crate::hash::git_sha256::compute_git_sha256_from_bytes; - let Ok(map) = crate::patch::package::read_archive_bytes_to_map(bytes) else { - return false; + let map = match crate::patch::package::read_archive_bytes_to_map(bytes) { + Ok(map) => map, + Err(e) if e.is_too_large() => return Err(e.to_string()), + Err(_) => return Ok(false), }; - record.files.iter().all(|(file_name, info)| { + Ok(record.files.iter().all(|(file_name, info)| { map.get(normalize_file_path(file_name)) .is_some_and(|content| compute_git_sha256_from_bytes(content) == info.after_hash) - }) + })) } /// Read the patched `package.json` out of a written vendored tarball (used diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index 9beeb475ba..e156c23210 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -4121,14 +4121,25 @@ async fn try_pypi_service_wheel( // members are site-packages-relative (the `record.files` keys), // so require each patched file to carry its afterHash before // reporting the package patched and pinning the lockfile to it. - if super::pypi_distribution::read_members(&archive.bytes, &wheel_name) + match super::pypi_distribution::read_members(&archive.bytes, &wheel_name) .and_then(|members| super::pypi_distribution::verify_members(&members, &wheel_name, record)) - .is_err() { - return Err(policy.miss(format!( - "prebuilt wheel for {base} does not carry the patched files at \ - their recorded paths" - ))); + Ok(()) => {} + // Past a limit its contents were not read: it is too large, not a + // distribution without the patch. + Err(tag) if tag == super::verify::ARTIFACT_TOO_LARGE => { + let limit = super::verify::archive_limit_exceeded(&archive.bytes, &wheel_name); + return Err(policy.hard( + super::verify::ARTIFACT_TOO_LARGE, + format!("the patch service's distribution for {base} cannot be checked: {limit}"), + )); + } + Err(_) => { + return Err(policy.miss(format!( + "prebuilt wheel for {base} does not carry the patched files at \ + their recorded paths" + ))); + } } let Some((name, version)) = parse_pypi_purl(base) else { return Err(policy.hard("unsafe_coordinates", base.to_string())); diff --git a/crates/socket-patch-core/src/vendor/pypi_distribution.rs b/crates/socket-patch-core/src/vendor/pypi_distribution.rs index 2fa651feae..8e2ccf7dbf 100644 --- a/crates/socket-patch-core/src/vendor/pypi_distribution.rs +++ b/crates/socket-patch-core/src/vendor/pypi_distribution.rs @@ -35,10 +35,19 @@ pub(crate) fn matches(name: &str, package: &str, version: &str) -> bool { }) } +/// The members of the Python distribution `bytes`, named `name`. A +/// distribution past a limit its reader holds it to fails with the tag +/// `vendor_artifact_too_large`, whichever archive it is; +/// [`super::verify::archive_limit_exceeded`] says which limit. pub(crate) fn read_members(bytes: &[u8], name: &str) -> Result>, String> { let members = if name.ends_with(".tar.gz") || name.ends_with(".tgz") { - crate::patch::package::read_sdist_tar_bytes_to_map_strict(bytes) - .map_err(|e| e.to_string())? + crate::patch::package::read_sdist_tar_bytes_to_map_strict(bytes).map_err(|e| { + if e.is_too_large() { + super::verify::ARTIFACT_TOO_LARGE.to_string() + } else { + e.to_string() + } + })? } else { super::verify::read_zip_bytes_to_map_strict(bytes)? }; @@ -182,9 +191,25 @@ mod tests { assert!(read_members(&aliases, "six-1.tar.gz").is_err()); let link = tar(&[("six-1/six.py", b"", tar::EntryType::Symlink)]); assert!(read_members(&link, "six-1.tar.gz").is_err()); + // A member past the 16 MiB one member was once held to is read. let bytes = vec![0; 16 * 1024 * 1024 + 1]; + let large = tar(&[("six-1/six.py", &bytes, tar::EntryType::Regular)]); + assert_eq!( + read_members(&large, "six-1.tar.gz").unwrap()["six.py"].len(), + bytes.len() + ); + // One that takes the archive past what its own size allows is too + // large, by the tag a wheel past a limit fails with. + let bytes = vec![0; 80 * 1024 * 1024]; let oversized = tar(&[("six-1/six.py", &bytes, tar::EntryType::Regular)]); - assert!(read_members(&oversized, "six-1.tar.gz").is_err()); + assert_eq!( + read_members(&oversized, "six-1.tar.gz").unwrap_err(), + "vendor_artifact_too_large" + ); + assert!( + crate::vendor::verify::archive_limit_exceeded(&oversized, "six-1.tar.gz") + .starts_with("it unpacks to at least 81 MiB, over 100 times its own size ("), + ); } #[test] diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 71ba3784f2..f44da5de75 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -171,22 +171,39 @@ pub async fn restore( // A jar is read by name, case and all, by the JVM: the // installer-shaped strictness of the wheel reader (ASCII names, // no case-colliding pair) refuses obfuscated jars that hold - // both `a.class` and `A.class`, and its size caps refuse large - // ones. The record's members are hashed within the jar limits. + // both `a.class` and `A.class`, and that reader holds every + // member in memory, within half of what a jar may inflate to. + // The record's members are hashed within the jar limits. super::verify::verify_jar_bytes_members(&archive.bytes, &record.files).map_err( |(tag, why)| format!("{tag}: the downloaded jar cannot be verified: {why}"), )?; } else { let members = if entry.ecosystem == "pypi" { - super::pypi_distribution::read_members(&archive.bytes, &entry.artifact.path)? + super::pypi_distribution::read_members(&archive.bytes, &entry.artifact.path) } else if entry.artifact.path.ends_with(".tgz") || entry.artifact.path.ends_with(".tar.gz") { - crate::patch::package::read_archive_bytes_to_map_strict(&archive.bytes) - .map_err(|e| e.to_string())? + crate::patch::package::read_archive_bytes_to_map_strict(&archive.bytes).map_err( + |e| { + if e.is_too_large() { + super::verify::ARTIFACT_TOO_LARGE.to_string() + } else { + e.to_string() + } + }, + ) } else { - super::verify::read_zip_bytes_to_map_strict(&archive.bytes)? - }; + super::verify::read_zip_bytes_to_map_strict(&archive.bytes) + } + // A download past a limit says which one, as a jar does. + .map_err(|error| { + if error != super::verify::ARTIFACT_TOO_LARGE { + return error; + } + let limit = + super::verify::archive_limit_exceeded(&archive.bytes, &entry.artifact.path); + format!("{error}: the downloaded archive cannot be verified: {limit}") + })?; if entry.ecosystem == "pypi" { super::pypi_distribution::verify_members(&members, &entry.artifact.path, record)?; } else { diff --git a/crates/socket-patch-core/src/vendor/reuse.rs b/crates/socket-patch-core/src/vendor/reuse.rs index 776a412af2..77eeb27e23 100644 --- a/crates/socket-patch-core/src/vendor/reuse.rs +++ b/crates/socket-patch-core/src/vendor/reuse.rs @@ -231,26 +231,15 @@ pub(crate) async fn verify_committed_artifact( let python_name = (entry.ecosystem == "pypi").then(|| rel_path.clone()); let (bytes, members) = tokio::task::spawn_blocking(move || { let members = if let Some(name) = &python_name { - super::pypi_distribution::read_members(&bytes, name).map_err(|error| { - if error == "vendor_artifact_non_canonical" { - ReuseMiss::NonCanonical - } else { - ReuseMiss::Unreadable - } - }) + super::pypi_distribution::read_members(&bytes, name).map_err(zip_miss) } else if is_tarball { crate::patch::package::read_archive_bytes_to_map_strict(&bytes).map_err(|e| match e { crate::patch::package::ArchiveError::NonCanonical(_) => ReuseMiss::NonCanonical, + e if e.is_too_large() => ReuseMiss::TooLarge, _ => ReuseMiss::Unreadable, }) } else { - read_zip_bytes_to_map_strict(&bytes).map_err(|e| { - if e == "vendor_artifact_non_canonical" { - ReuseMiss::NonCanonical - } else { - ReuseMiss::Unreadable - } - }) + read_zip_bytes_to_map_strict(&bytes).map_err(zip_miss) }; (bytes, members) }) @@ -272,6 +261,15 @@ pub(crate) async fn verify_committed_artifact( }) } +/// The miss of an artifact its reader refused with the routing tag `tag`. +fn zip_miss(tag: String) -> ReuseMiss { + match tag.as_str() { + "vendor_artifact_non_canonical" => ReuseMiss::NonCanonical, + super::verify::ARTIFACT_TOO_LARGE => ReuseMiss::TooLarge, + _ => ReuseMiss::Unreadable, + } +} + /// [`prior_entry`] followed by [`verify_committed_artifact`]. pub(crate) async fn reusable_committed_artifact( project_root: &Path, diff --git a/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs b/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs index 6953f8f030..0893a9fb3a 100644 --- a/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs +++ b/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs @@ -113,7 +113,7 @@ impl Fixture { pub type Secondary = Vec<(&'static str, String, Vec)>; /// Every file member of a jar, whatever its size: a fixture jar may be past -/// the wheel-sized caps of `read_zip_bytes_to_map`. +/// the limits of `read_zip_bytes_to_map`, or a bomb by its ratio rule. fn jar_members(jar: &[u8]) -> Result>, String> { use std::io::Read as _; let mut zip = zip::ZipArchive::new(std::io::Cursor::new(jar)).map_err(|e| e.to_string())?; diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 0e9785611f..65b1b1ec10 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -6,11 +6,11 @@ //! `afterHash` inside that artifact — the same standard `vex::verify` applies //! to installed trees. Dir-shaped ecosystems are hashed in place; npm //! tarballs and zip artifacts (`.whl`/`.nupkg`) are decoded in memory -//! (bounded — the artifacts are committed and tamper-able, so a crafted -//! archive must not OOM an audit). A `.jar` has its record members hashed -//! as they are inflated, within the jar limits of -//! [`crate::patch::jar_members`]: released jars are larger than the -//! wheel-sized caps of the in-memory reader allow. +//! (bounded by [`crate::patch::archive_limits`] — the artifacts are +//! committed and tamper-able, so a crafted archive must not OOM an audit). +//! A `.jar` has its record members hashed as they are inflated, within the +//! jar limits of [`crate::patch::jar_members`]: a jar may inflate to twice +//! what a reader that holds every member may. //! //! Fail-closed order (each failure is a stable snake_case routing tag): //! `no_files` → `vendor_path_unsafe` → `vendor_uuid_mismatch` → @@ -38,17 +38,13 @@ use crate::manifest::schema::{PatchFileInfo, PatchRecord}; use crate::patch::apply::{ is_missing_path, is_safe_relative_subpath, normalize_file_path, verify_file_patch, VerifyStatus, }; +use crate::patch::archive_limits::{ArchiveLimits, Budget, Unpacked}; use crate::patch::file_hash::compute_file_git_sha256; use crate::patch::package::read_archive_to_map; use super::path::parse_vendor_path; use super::state::VendorEntry; -/// Hard cap on decompressed wheel bytes, mirroring -/// `patch::package`'s bomb posture for patch archives. -const MAX_WHEEL_DECOMPRESSED_BYTES: u64 = 64 * 1024 * 1024; -const MAX_WHEEL_ENTRIES: usize = 10_000; - /// Validate `entry.artifact.path` and resolve it under `project_root`. /// /// SECURITY: state.json is committed and tamper-able. The artifact path is @@ -107,7 +103,7 @@ pub async fn verify_vendored_patch_record( } // Archive-shaped artifacts are decoded in memory and their members hashed: - // npm tarballs via the bomb-capped patch-archive reader (it strips the + // npm tarballs via the bomb-capped tarball reader (it strips the // `package/` prefix, matching `normalize_file_path`'d keys); `.whl` / // `.nupkg` (a plain OPC zip) / `.jar` (a plain zip) via the bounded zip // reader — their member paths are package-relative, exactly the manifest @@ -130,8 +126,7 @@ pub async fn verify_vendored_patch_record( if bytes.len() as u64 > MAX_HEALTH_HASH_BYTES { return Err("vendor_artifact_unreadable".into()); } - super::pypi_distribution::read_members(&bytes, &name) - .map_err(|_| "vendor_artifact_unreadable".to_string()) + super::pypi_distribution::read_members(&bytes, &name).map_err(unread_tag) }) .await .map_err(|e| e.to_string())??; @@ -215,12 +210,12 @@ pub async fn verify_vendored_patch_record( match crate::patch::package::shadowed_member(&bytes, &patched_files) { Ok(None) => {} Ok(Some(_)) => return Err("vendor_artifact_non_canonical".to_string()), - Err(_) => return Err("vendor_artifact_unreadable".to_string()), + Err(e) => return Err(tarball_error_tag(&e)), } crate::patch::package::read_archive_bytes_to_map(&bytes) - .map_err(|_| "vendor_artifact_unreadable".to_string()) + .map_err(|e| tarball_error_tag(&e)) } else if is_tarball { - read_archive_to_map(&artifact).map_err(|_| "vendor_artifact_unreadable".to_string()) + read_archive_to_map(&artifact).map_err(|e| tarball_error_tag(&e)) } else { read_wheel_to_map(&artifact) } @@ -640,10 +635,51 @@ async fn untagged_manifest_matches(dir: &Path, uuid: &str, after_hash: &str) -> .is_some_and(|b| compute_git_sha256_from_bytes(&b).eq_ignore_ascii_case(after_hash)) } -/// A jar past the limits of [`crate::patch::jar_members`]: its own tag, so -/// the omission says the jar is too large, not that it cannot be read. +/// An artifact past the limits it is read within (a jar: +/// [`crate::patch::jar_members`]; a tarball, wheel or `.nupkg`: +/// [`crate::patch::archive_limits`]): its own tag, so the omission says the +/// artifact is too large, not that it cannot be read. pub(crate) const ARTIFACT_TOO_LARGE: &str = "vendor_artifact_too_large"; +/// The tag of a tarball the reader refused. +fn tarball_error_tag(e: &crate::patch::package::ArchiveError) -> String { + if e.is_too_large() { + ARTIFACT_TOO_LARGE.to_string() + } else { + "vendor_artifact_unreadable".to_string() + } +} + +/// The tag of an artifact that could not be read, from its reader's own: +/// too large stays too large, everything else is unreadable. +fn unread_tag(tag: String) -> String { + if tag == ARTIFACT_TOO_LARGE { + tag + } else { + "vendor_artifact_unreadable".to_string() + } +} + +/// What to say of an archive past the limits when its reader's words are +/// not at hand. +const PAST_THE_LIMITS: &str = "it holds or unpacks to more than an archive of its size may"; + +/// Which limit the archive `bytes` is past (`name` tells a tarball from a +/// zip), in the words of its reader. For the message of a caller that +/// holds [`ARTIFACT_TOO_LARGE`], the tag the readers' callers pass on. +pub(crate) fn archive_limit_exceeded(bytes: &[u8], name: &str) -> String { + let limit = if name.ends_with(".tgz") || name.ends_with(".tar.gz") { + crate::patch::package::limit_exceeded(bytes) + } else { + let budget = ArchiveLimits::IN_MEMORY.budget(bytes.len() as u64); + match read_zip_within(std::io::Cursor::new(bytes), &budget, false) { + Err(ZipError::TooLarge(why)) => Some(why), + _ => None, + } + }; + limit.unwrap_or_else(|| PAST_THE_LIMITS.to_string()) +} + fn jar_error_tag(e: crate::patch::jar_members::JarError) -> String { if e.is_too_large() { ARTIFACT_TOO_LARGE.to_string() @@ -716,9 +752,9 @@ fn read_wheel_to_map(whl: &Path) -> Result>, String> { // instead of wedging it in `open(2)` waiting for a writer that never // comes (mirrors `read_archive_to_map`). The handle is kept — the zip // reader streams from it. - let (file, _metadata) = crate::utils::fs::open_regular_file_sync(whl) + let (file, metadata) = crate::utils::fs::open_regular_file_sync(whl) .map_err(|_| "vendor_artifact_unreadable".to_string())?; - read_zip_to_map(file, false) + read_zip_to_map(file, metadata.len(), false) } /// [`read_wheel_to_map`] over in-memory zip bytes — the same entry and @@ -728,7 +764,7 @@ fn read_wheel_to_map(whl: &Path) -> Result>, String> { /// fixtures and the tests. #[cfg(any(test, feature = "test-fixtures"))] pub(crate) fn read_zip_bytes_to_map(bytes: &[u8]) -> Result>, String> { - read_zip_to_map(std::io::Cursor::new(bytes), false) + read_zip_to_map(std::io::Cursor::new(bytes), bytes.len() as u64, false) } /// [`read_zip_bytes_to_map`] that also refuses a wheel an installer could @@ -744,30 +780,64 @@ pub(crate) fn read_zip_bytes_to_map(bytes: &[u8]) -> Result Result>, String> { - read_zip_to_map(std::io::Cursor::new(bytes), true) + read_zip_to_map(std::io::Cursor::new(bytes), bytes.len() as u64, true) +} + +/// Why the zip reader refused an archive. +#[derive(Debug, Clone, PartialEq, Eq)] +enum ZipError { + Unreadable, + NonCanonical, + /// Past a limit of [`crate::patch::archive_limits`]; the text names it. + TooLarge(String), +} + +impl ZipError { + /// The stable routing tag. + fn tag(&self) -> &'static str { + match self { + ZipError::Unreadable => "vendor_artifact_unreadable", + ZipError::NonCanonical => "vendor_artifact_non_canonical", + ZipError::TooLarge(_) => ARTIFACT_TOO_LARGE, + } + } } /// The shared bounded zip decoder behind [`read_wheel_to_map`] and -/// [`read_zip_bytes_to_map`] (plus the canonical-shape gate when `strict`). +/// [`read_zip_bytes_to_map`] (plus the canonical-shape gate when `strict`), +/// for an archive of `archive_len` bytes. The error is the routing tag; +/// [`archive_limit_exceeded`] says which limit a too-large archive is past. fn read_zip_to_map( reader: R, + archive_len: u64, strict: bool, ) -> Result>, String> { - let mut zip = - zip::ZipArchive::new(reader).map_err(|_| "vendor_artifact_unreadable".to_string())?; - if zip.len() > MAX_WHEEL_ENTRIES { - return Err("vendor_artifact_unreadable".to_string()); - } + let budget = ArchiveLimits::IN_MEMORY.budget(archive_len); + read_zip_within(reader, &budget, strict).map_err(|e| e.tag().to_string()) +} + +/// [`read_zip_to_map`] within `budget`. +fn read_zip_within( + reader: R, + budget: &Budget, + strict: bool, +) -> Result>, ZipError> { + let mut zip = zip::ZipArchive::new(reader).map_err(|_| ZipError::Unreadable)?; + let limits = budget.limits(); + if zip.len() > limits.max_entries { + return Err(ZipError::TooLarge(limits.too_many_entries(Some(zip.len())))); + } + // What the directory says the archive unpacks to, for the text of a + // limit error; an archive written as a stream records no sizes there. + let declared_total = zip.decompressed_size().and_then(|n| u64::try_from(n).ok()); let mut out = HashMap::new(); let mut seen: std::collections::HashSet = std::collections::HashSet::new(); let mut declared: u64 = 0; let mut actual: u64 = 0; for i in 0..zip.len() { - let mut entry = zip - .by_index(i) - .map_err(|_| "vendor_artifact_unreadable".to_string())?; + let mut entry = zip.by_index(i).map_err(|_| ZipError::Unreadable)?; if strict { - let non_canonical = || "vendor_artifact_non_canonical".to_string(); + let non_canonical = || ZipError::NonCanonical; if entry.is_symlink() || entry.name().starts_with('/') { return Err(non_canonical()); } @@ -787,10 +857,15 @@ fn read_zip_to_map( // The declared `entry.size()` is header data the attacker controls // and the zip reader never enforces, so the binding budget is bytes // ACTUALLY decompressed; the declared check just fails honest - // oversized wheels before reading anything. + // oversized wheels before reading anything. The budget is what an + // archive of this size may unpack to (`patch::archive_limits`). declared = declared.saturating_add(entry.size()); - if declared > MAX_WHEEL_DECOMPRESSED_BYTES { - return Err("vendor_artifact_unreadable".to_string()); + if declared > budget.bytes() { + let unpacked = match declared_total { + Some(total) if total >= declared => Unpacked::Declared(total), + _ => Unpacked::AtLeast(declared), + }; + return Err(ZipError::TooLarge(budget.exceeded(unpacked))); } let name = entry.name().to_string(); let mut bytes = Vec::new(); @@ -798,12 +873,12 @@ fn read_zip_to_map( // byte past it and is rejected, rather than truncating silently. entry .by_ref() - .take(MAX_WHEEL_DECOMPRESSED_BYTES - actual + 1) + .take(budget.bytes() - actual + 1) .read_to_end(&mut bytes) - .map_err(|_| "vendor_artifact_unreadable".to_string())?; + .map_err(|_| ZipError::Unreadable)?; actual = actual.saturating_add(bytes.len() as u64); - if actual > MAX_WHEEL_DECOMPRESSED_BYTES { - return Err("vendor_artifact_unreadable".to_string()); + if actual > budget.bytes() { + return Err(ZipError::TooLarge(budget.exceeded(Unpacked::Unknown))); } out.insert(name, bytes); } @@ -815,9 +890,9 @@ fn read_zip_to_map( /// must not stall `repair`. pub(crate) const MAX_HEALTH_HASH_BYTES: u64 = 512 * 1024 * 1024; -/// Hard cap on inventoried files, mirroring the zip reader's entry cap — a -/// committed artifact dir is one package; a tampered dir must not stall an -/// audit with a million planted files. +/// Hard cap on inventoried files (what the zip reader's entry cap was when +/// this one was written) — a committed artifact dir is one package; a +/// tampered dir must not stall an audit with a million planted files. const MAX_INVENTORY_ENTRIES: usize = 10_000; /// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar/gem) @@ -1145,6 +1220,31 @@ pub async fn describe_artifact_failure( }; format!("Bun workspace copy {mirror} {cause} ({reason}){canonical}; {repair}") } + ArtifactHealth::Corrupt { reason } + if reason == ARTIFACT_TOO_LARGE && !path.ends_with(".jar") => + { + // Which limit, from the reader that met it. + let (artifact, name) = (project_root.join(path), path.clone()); + let limit = tokio::task::spawn_blocking(move || { + let (file, metadata) = crate::utils::fs::open_regular_file_sync(&artifact).ok()?; + if metadata.len() > MAX_HEALTH_HASH_BYTES { + return None; + } + let mut bytes = Vec::new(); + file.take(MAX_HEALTH_HASH_BYTES) + .read_to_end(&mut bytes) + .ok()?; + Some(archive_limit_exceeded(&bytes, &name)) + }) + .await + .ok() + .flatten() + .unwrap_or_else(|| PAST_THE_LIMITS.to_string()); + format!( + "committed artifact {path} is past the limits archives are read within: {limit} \ + ({reason}), so its contents were not checked; {repair}" + ) + } ArtifactHealth::Corrupt { reason } if reason == ARTIFACT_TOO_LARGE => { // Which limit: the archive's own (entries, central directory), // else a patched member's inflated size. @@ -2346,7 +2446,7 @@ mod tests { assert!( read_wheel_to_map(&whl).is_err(), - "an 80 MiB-actual wheel declaring 0 bytes must not be buffered past the cap" + "an 80 MiB-actual wheel declaring 0 bytes must not be buffered past its budget" ); } @@ -2642,61 +2742,289 @@ mod tests { )); } - /// SECURITY: the zip entry-count cap fails a tampered wheel closed — - /// one entry past the cap (even zero-byte entries) is rejected up - /// front, while a wheel at exactly the cap still reads (no off-by-one - /// shrink of the legitimate budget). + /// A zip of `members`, deflated. + fn zip_of(members: &[(&str, &[u8])]) -> Vec { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in members { + zip.start_file::<_, ()>(*name, Default::default()).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap().into_inner() + } + + fn zip_too_large(bytes: &[u8], limits: ArchiveLimits) -> String { + let budget = limits.budget(bytes.len() as u64); + match read_zip_within(std::io::Cursor::new(bytes), &budget, false) { + Err(ZipError::TooLarge(why)) => why, + other => panic!( + "expected ZipError::TooLarge, got {:?}", + other.map(|m| m.len()) + ), + } + } + + /// SECURITY: the zip entry-count limit fails a tampered wheel closed — + /// one entry past it (even zero-byte entries) is rejected up front, + /// while a wheel at exactly the limit still reads (no off-by-one shrink + /// of the legitimate budget). The error is the limit's own, with the + /// count the archive declares. #[test] - fn wheel_entry_count_cap_rejects_over_ten_thousand_entries() { - let tmp = tempfile::tempdir().unwrap(); - let write_n_entry_whl = |n: usize| -> PathBuf { - let whl = tmp.path().join(format!("entries-{n}.whl")); - let file = std::fs::File::create(&whl).unwrap(); - let mut zip = zip::ZipWriter::new(file); - for i in 0..n { - zip.start_file::<_, ()>(format!("e{i}"), Default::default()) - .unwrap(); - } - zip.finish().unwrap(); - whl + fn wheel_entry_count_limit_rejects_one_entry_past_it() { + let n_entry_whl = |n: usize| -> Vec { + let names: Vec = (0..n).map(|i| format!("e{i}")).collect(); + let members: Vec<(&str, &[u8])> = + names.iter().map(|name| (name.as_str(), &b""[..])).collect(); + zip_of(&members) }; - - let at_cap = write_n_entry_whl(MAX_WHEEL_ENTRIES); + let limits = ArchiveLimits { + max_entries: 50, + ..ArchiveLimits::IN_MEMORY + }; + let at_limit = n_entry_whl(50); + let budget = limits.budget(at_limit.len() as u64); assert_eq!( - read_wheel_to_map(&at_cap).unwrap().len(), - MAX_WHEEL_ENTRIES, - "a wheel at exactly the entry cap still reads" + read_zip_within(std::io::Cursor::new(&at_limit[..]), &budget, true) + .unwrap() + .len(), + 50, + "a wheel at exactly the entry limit still reads" + ); + assert_eq!( + zip_too_large(&n_entry_whl(51), limits), + "it holds 51 entries, over the limit of 50", + "one entry past the limit fails closed" ); - let over_cap = write_n_entry_whl(MAX_WHEEL_ENTRIES + 1); + // 21,105 entries in the `ansible` wheel; the limit was 10,000. + let past_the_old_limit = n_entry_whl(12_000); assert_eq!( - read_wheel_to_map(&over_cap).unwrap_err(), - "vendor_artifact_unreadable", - "one entry past the cap fails closed" + read_zip_bytes_to_map(&past_the_old_limit).unwrap().len(), + 12_000 + ); + assert_eq!( + read_zip_bytes_to_map_strict(&past_the_old_limit) + .unwrap() + .len(), + 12_000 ); } - /// SECURITY: an honest wheel DECLARING more than the 64 MiB budget is - /// rejected by the declared-size fast-fail before its data is - /// decompressed — the other half of the accounting pinned by the - /// lying-header bomb test above. + /// SECURITY: a wheel DECLARING more than its budget is rejected by the + /// declared-size fast-fail before its data is decompressed — the other + /// half of the accounting pinned by the lying-header bomb test above. + /// Zeros deflate a thousandfold, so 64 MiB and one byte of them make an + /// archive of some 64 KiB: a bomb, which is held to the 64 MiB every + /// archive may use however high the limit for a large one is. #[test] - fn honest_oversized_wheel_rejected_by_declared_size_fast_fail() { + fn wheel_declaring_more_than_its_budget_is_too_large() { let tmp = tempfile::tempdir().unwrap(); let whl = tmp.path().join("big-1.0.0-py3-none-any.whl"); - let file = std::fs::File::create(&whl).unwrap(); - let mut zip = zip::ZipWriter::new(file); - // One byte past the cap, headers recording the TRUE size (zeros - // deflate to a few KiB, so the fixture itself stays tiny). - zip.start_file::<_, ()>("pad.bin", Default::default()) - .unwrap(); - zip.write_all(&vec![0u8; (MAX_WHEEL_DECOMPRESSED_BYTES + 1) as usize]) - .unwrap(); - zip.finish().unwrap(); + let bomb = zip_of(&[("pad.bin", &vec![0u8; 64 * 1024 * 1024 + 1])]); + assert!(bomb.len() < 128 * 1024, "{}", bomb.len()); + std::fs::write(&whl, &bomb).unwrap(); assert_eq!( read_wheel_to_map(&whl).unwrap_err(), - "vendor_artifact_unreadable" + "vendor_artifact_too_large" + ); + assert_eq!( + read_zip_bytes_to_map_strict(&bomb).unwrap_err(), + "vendor_artifact_too_large" + ); + let why = archive_limit_exceeded(&bomb, "big-1.0.0-py3-none-any.whl"); + assert!( + why.starts_with("it unpacks to 65 MiB, over 100 times its own size (") + && why.ends_with(" KiB) and the 64 MiB every archive may use"), + "{why}" + ); + // The limit for one archive, when the archive is large enough for + // its own size not to be what holds it. + let small = ArchiveLimits { + max_inflated_bytes: 4096, + ratio_floor_bytes: 4096, + ..ArchiveLimits::IN_MEMORY + }; + let over = zip_of(&[("a.bin", &[1u8; 4096]), ("b.bin", &[2u8; 1024])]); + assert_eq!( + zip_too_large(&over, small), + "it unpacks to 5 KiB, over the limit of 4 KiB for one archive" + ); + let within = zip_of(&[("a.bin", &[1u8; 4096])]); + let budget = small.budget(within.len() as u64); + assert_eq!( + read_zip_within(std::io::Cursor::new(&within[..]), &budget, false) + .unwrap() + .len(), + 1 + ); + } + + /// The limits were 64 MiB unpacked and 10,000 entries: a wheel with one + /// compiled extension of that size (`rattler.abi3.so` is 55 MiB, + /// `libxgboost.so` 239 MiB) could not be checked. One past the old + /// limit is read, as long as it is as large on disk as an honest one. + #[tokio::test] + async fn a_wheel_past_the_old_limits_is_read() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let rel = format!(".socket/vendor/pypi/{UUID}/big-1.0.0-cp312-abi3-linux_x86_64.whl"); + let whl = root.join(&rel); + std::fs::create_dir_all(whl.parent().unwrap()).unwrap(); + let extension = vec![0u8; 80 * 1024 * 1024]; + let filler = crate::patch::archive_limits::noise(1024 * 1024); + let bytes = zip_of(&[ + ("big/__init__.py", PATCHED), + ("big/_native.abi3.so", &extension), + ("big/filler.bin", &filler), + ]); + assert!(bytes.len() > 1024 * 1024 && bytes.len() < 2 * 1024 * 1024); + std::fs::write(&whl, &bytes).unwrap(); + + let members = read_wheel_to_map(&whl).unwrap(); + assert_eq!(members.len(), 3); + assert_eq!(members["big/_native.abi3.so"].len(), 80 * 1024 * 1024); + let rec = record(UUID, "big/__init__.py"); + let ent = entry("pypi", UUID, &rel); + assert_eq!(verify_vendored_patch_record(root, &ent, &rec).await, Ok(())); + + // The same wheel without the megabyte that makes it honest is a + // bomb: 80 MiB out of some 80 KiB. + let bomb = zip_of(&[ + ("big/__init__.py", PATCHED), + ("big/_native.abi3.so", &extension), + ]); + std::fs::write(&whl, &bomb).unwrap(); + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_too_large".to_string()) + ); + } + + /// A committed tarball or wheel past a limit is too large, not + /// unreadable, and `vendor --check` says which limit. + #[tokio::test] + async fn a_committed_archive_past_a_limit_is_too_large_and_names_the_limit() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let zeros = vec![0u8; 80 * 1024 * 1024]; + let rec = record(UUID, "package/index.js"); + + let tgz_rel = format!(".socket/vendor/npm/{UUID}/x-1.0.0.tgz"); + let tgz = root.join(&tgz_rel); + std::fs::create_dir_all(tgz.parent().unwrap()).unwrap(); + let mut builder = tar::Builder::new(GzEncoder::new( + std::fs::File::create(&tgz).unwrap(), + flate2::Compression::new(6), + )); + for (name, bytes) in [("package/index.js", PATCHED), ("package/pad.bin", &zeros)] { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder.append_data(&mut header, name, bytes).unwrap(); + } + builder.into_inner().unwrap().finish().unwrap(); + + let whl_rel = format!(".socket/vendor/pypi/{UUID}/x-1.0.0-py3-none-any.whl"); + let whl = root.join(&whl_rel); + std::fs::create_dir_all(whl.parent().unwrap()).unwrap(); + std::fs::write( + &whl, + zip_of(&[("package/index.js", PATCHED), ("pad.bin", &zeros)]), + ) + .unwrap(); + + for (eco, rel, unpacks_to) in [ + // A tar stream declares its members one at a time, a zip's + // directory all of them. + ("npm", &tgz_rel, "it unpacks to at least 81 MiB"), + ("pypi", &whl_rel, "it unpacks to 81 MiB"), + ] { + let mut ent = entry(eco, UUID, rel); + // A recorded fingerprint: what `repair` restores from. + ent.artifact.sha256 = "ab".repeat(32); + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_too_large".to_string()), + "{eco}" + ); + let health = check_vendored_artifact(root, &ent, &rec).await; + assert_eq!( + health, + ArtifactHealth::Corrupt { + reason: "vendor_artifact_too_large".to_string() + }, + "{eco}" + ); + let why = describe_artifact_failure(root, &ent, &health) + .await + .unwrap(); + let prefix = format!( + "committed artifact {rel} is past the limits archives are read within: \ + {unpacks_to}, over 100 times its own size (" + ); + assert!(why.starts_with(&prefix), "{eco}: {why}"); + assert!( + why.ends_with( + " KiB) and the 64 MiB every archive may use (vendor_artifact_too_large), \ + so its contents were not checked; run `socket-patch repair` to restore \ + it, then commit it" + ), + "{eco}: {why}" + ); + } + } + + /// A second `package/index.js` exactly 64 MiB into the tar stream of a + /// committed npm tarball: the installers extract it over the patched + /// file. The reader used to stop at 64 MiB and take the end of its + /// input for the end of the archive, so the tarball verified. + #[tokio::test] + async fn a_second_entry_at_the_old_limit_of_a_committed_tarball_is_non_canonical() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let rel = format!(".socket/vendor/npm/{UUID}/x-1.0.0.tgz"); + let tgz = root.join(&rel); + std::fs::create_dir_all(tgz.parent().unwrap()).unwrap(); + let filler = crate::patch::archive_limits::noise(1024 * 1024); + // Two blocks for the patched file, the filler's 2049, and a pad + // with its header up to the 64 MiB mark. + let pad = vec![0u8; 64 * 1024 * 1024 - 2 * 512 - (1024 * 1024 + 512) - 512]; + let write = |with_second_entry: bool| { + let mut builder = tar::Builder::new(GzEncoder::new( + std::fs::File::create(&tgz).unwrap(), + flate2::Compression::new(6), + )); + let mut members: Vec<(&str, &[u8])> = vec![ + ("package/index.js", PATCHED), + ("package/filler.bin", &filler), + ("package/pad.bin", &pad), + ]; + if with_second_entry { + members.push(("package/index.js", b"original bytes\n")); + } + for (name, bytes) in members { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder.append_data(&mut header, name, bytes).unwrap(); + } + builder.into_inner().unwrap().finish().unwrap(); + }; + let rec = record(UUID, "package/index.js"); + let ent = entry("npm", UUID, &rel); + + write(false); + assert_eq!(verify_vendored_patch_record(root, &ent, &rec).await, Ok(())); + write(true); + let bytes = std::fs::read(&tgz).unwrap(); + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&bytes[..])); + let second_entry = tar.entries().unwrap().last().unwrap().unwrap(); + assert_eq!(second_entry.raw_header_position(), 64 * 1024 * 1024); + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_non_canonical".to_string()) ); } From 736a05f70a768439f525c42f093d25fec527a6aa Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 09:06:23 -0500 Subject: [PATCH 02/13] Check the archive limits through the CLI and word the vex omission for every archive `vex` words `vendor_artifact_too_large` for any vendored artifact now, not for a jar alone, and gives both sets of limits. Three tests in the vendor suite run the binary against the fixture patch service: - A package of 73 MiB in files of 14 MiB is vendored and checks clean. It failed with "does not carry the patched files". - A served tarball of some 80 KiB that unpacks to 80 MiB fails with a message that names the limit and what the tarball unpacks to, and nothing is committed. - A committed tarball with a second `package/index.js` exactly 64 MiB into its tar stream, its ledger fingerprint and lock integrity matching, fails `vendor --check` with `vendor_artifact_non_canonical`; it verified before (#2330). The same tarball without the second entry checks clean, and one past a limit fails with `vendor_artifact_too_large` and the limit named. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/vex.rs | 7 +- .../tests/vendor/vendor_failure_paths.rs | 186 ++++++++++++++++++ 2 files changed, 190 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..3ab192df07 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2801,9 +2801,10 @@ fn omission_phrase(reason: &str) -> &'static str { "vendor_artifact_missing" => "the vendored artifact is missing", "vendor_artifact_unreadable" => "the vendored artifact cannot be read", "vendor_artifact_too_large" => { - "the vendored jar is past the limits jars are read within (200,000 entries, or 1 GiB \ - and 100 times its own size inflated), so its contents were not checked; run \ - socket-patch repair to restore the recorded jar" + "the vendored artifact is past the limits it is read within (200,000 entries, or \ + 100 times its own size inflated and 1 GiB for a jar, 512 MiB for a tarball, wheel \ + or .nupkg), so its contents were not checked; run socket-patch repair to restore \ + the recorded artifact" } "vendor_artifact_non_canonical" => { "the vendored tarball holds a second entry the package manager would extract \ diff --git a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs index db5b10f07d..936a04ae4d 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs @@ -1515,3 +1515,189 @@ fn vendor_revert_in_a_member_with_its_own_manifest_is_not_refused() { let (code, env) = vendor_cli(&member, &["--revert"]); assert_eq!(code, 0, "{env:#}"); } + +// ───────────────────────────────────────────────────────────────────── +// archive limits +// ───────────────────────────────────────────────────────────────────── + +const MIB: usize = 1024 * 1024; + +/// `len` bytes gzip cannot shrink. A fixture of zeros alone is a few +/// kilobytes on disk, which past 64 MiB unpacked is a bomb by the ratio +/// rule; an honest large package is large on disk too. +fn noise(len: usize) -> Vec { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut out = Vec::with_capacity(len + 8); + while out.len() < len { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + out.extend_from_slice(&state.to_le_bytes()); + } + out.truncate(len); + out +} + +/// `members` as an npm tarball, one 512-byte header and the padded content +/// for each, in order. +fn npm_tarball(members: &[(&str, &[u8])]) -> Vec { + let mut builder = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::default(), + )); + for (name, bytes) in members { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_mtime(0); + header.set_cksum(); + builder.append_data(&mut header, name, *bytes).unwrap(); + } + builder.into_inner().unwrap().finish().unwrap() +} + +/// Put `tgz` where the fixture's vendored tarball is, with the ledger's +/// fingerprint and the lock's integrity following it: a tampered tarball +/// whose whole-file checks all pass, so only its contents can give it away. +fn replace_committed_tarball(fx: &NpmFixture, tgz: &[u8]) { + use sha2::{Digest as _, Sha256}; + std::fs::write(fx.tgz_path(), tgz).unwrap(); + let mut state: Value = serde_json::from_slice(&std::fs::read(fx.state_path()).unwrap()) + .expect("state.json parses"); + let artifact = &mut state["entries"][PURL]["artifact"]; + artifact["sha256"] = json!(hex::encode(Sha256::digest(tgz))); + if !artifact["size"].is_null() { + artifact["size"] = json!(tgz.len()); + } + std::fs::write(fx.state_path(), serde_json::to_vec_pretty(&state).unwrap()).unwrap(); + let mut lock: Value = serde_json::from_slice(&fx.lock_bytes()).unwrap(); + lock["packages"]["node_modules/left-pad"]["integrity"] = json!(sri_of(tgz)); + std::fs::write(fx.lock_path(), serde_json::to_vec_pretty(&lock).unwrap()).unwrap(); +} + +/// #2197: a package of 73 MiB in files of 14 MiB each. The tarball reader +/// stopped at 64 MiB unpacked and 16 MiB for one file, and `vendor` said +/// the service's tarball "does not carry the patched files". It is vendored +/// and checks clean. +#[test] +fn a_package_past_the_old_64_mib_limit_is_vendored_and_checked() { + let fx = npm_fixture(); + let dist = fx.root().join("node_modules/left-pad/dist"); + std::fs::create_dir_all(&dist).unwrap(); + for chunk in 1..=5 { + std::fs::write(dist.join(format!("chunk{chunk}.js")), vec![b' '; 14 * MIB]).unwrap(); + } + // What makes the tarball as large on disk as an honest one. + std::fs::write(dist.join("assets.bin"), noise(MIB)).unwrap(); + + let (code, env) = vendor_cli(fx.root(), &[]); + assert_eq!(code, 0, "{env:#}"); + assert_eq!(env["summary"]["applied"], 1, "{env:#}"); + let on_disk = std::fs::metadata(fx.tgz_path()).unwrap().len(); + assert!(on_disk > MIB as u64, "the tarball is committed: {on_disk}"); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 0, "{env:#}"); +} + +/// A tarball that unpacks to more than its own size allows is refused for +/// that, by a message that names the limit and what the tarball unpacks to, +/// not as one that "does not carry the patched files": 80 MiB of one byte +/// make a tarball of some 80 KiB, which may unpack to 64 MiB. +#[test] +fn a_served_tarball_past_what_its_size_allows_is_refused_as_too_large() { + let fx = npm_fixture(); + std::fs::write( + fx.root().join("node_modules/left-pad/pad.bin"), + vec![0u8; 80 * MIB], + ) + .unwrap(); + + let (code, env) = vendor_cli(fx.root(), &[]); + assert_eq!(code, 1, "{env:#}"); + let failed = find_event(&env, "failed", None); + let error = failed["error"].as_str().unwrap_or_default(); + assert!( + error.contains( + "the patch service's tarball for left-pad@1.3.0 cannot be checked: it unpacks to \ + at least 81 MiB, over 100 times its own size (" + ) && error.contains("KiB) and the 64 MiB every archive may use"), + "{env:#}" + ); + assert!(!error.contains("does not carry"), "{env:#}"); + assert!(!fx.tgz_path().exists(), "nothing is committed"); + assert_eq!(fx.lock_bytes(), fx.original_lock, "the lock is untouched"); +} + +/// #2330: a committed tarball with a second `package/index.js`, holding +/// the original file, exactly 64 MiB into its tar stream. Every installer +/// extracts it over the patched file. The check stopped reading at 64 MiB +/// and took the end of its input for the end of the archive, so it reported +/// the tarball verified. It is `vendor_artifact_non_canonical` now, the +/// same tarball without the second entry checks clean, and a tarball past +/// a limit is too large, with the limit named, never one read up to it. +#[test] +fn check_sees_a_second_entry_where_the_old_limit_fell() { + let fx = npm_fixture(); + let (code, env) = vendor_cli(fx.root(), &[]); + assert_eq!(code, 0, "{env:#}"); + + let manifest = br#"{"name":"left-pad","version":"1.3.0"}"#; + let filler = noise(MIB); + // Two blocks each for the manifest and the patched file, the filler's + // 2049, and a pad with its header up to the 64 MiB mark. + let pad = vec![0u8; 64 * MIB - 4 * 512 - (MIB + 512) - 512]; + let mut members: Vec<(&str, &[u8])> = vec![ + ("package/package.json", manifest), + ("package/index.js", PATCHED_INDEX), + ("package/assets.bin", &filler), + ("package/pad.bin", &pad), + ]; + + replace_committed_tarball(&fx, &npm_tarball(&members)); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 0, "a large tarball with one index.js: {env:#}"); + + members.push(("package/index.js", ORIG_INDEX)); + let shadowed = npm_tarball(&members); + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&shadowed[..])); + let second_entry = tar.entries().unwrap().last().unwrap().unwrap(); + assert_eq!( + second_entry.raw_header_position(), + 64 * MIB as u64, + "where the old limit fell" + ); + replace_committed_tarball(&fx, &shadowed); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 1, "{env:#}"); + let failed = find_event(&env, "failed", Some("vendor_check_failed")); + assert!( + failed["reason"] + .as_str() + .is_some_and(|m| m.contains("(vendor_artifact_non_canonical)")), + "{env:#}" + ); + + // The second entry behind 80 MiB of padding in a tarball of some + // 80 KiB: past what a tarball that small may unpack to. + let zeros = vec![0u8; 80 * MIB]; + replace_committed_tarball( + &fx, + &npm_tarball(&[ + ("package/package.json", manifest), + ("package/index.js", PATCHED_INDEX), + ("package/pad.bin", &zeros), + ("package/index.js", ORIG_INDEX), + ]), + ); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 1, "{env:#}"); + let failed = find_event(&env, "failed", Some("vendor_check_failed")); + let reason = failed["reason"].as_str().unwrap_or_default(); + assert!( + reason.contains( + "is past the limits archives are read within: it unpacks to at least 81 MiB, over \ + 100 times its own size (" + ) && reason.contains("(vendor_artifact_too_large), so its contents were not checked"), + "{env:#}" + ); +} From 099dd6f2b5235803ae2a7155b52fd7666693e0b9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 09:06:23 -0500 Subject: [PATCH 03/13] Document the archive limits and the too-large verdict for tarballs and wheels The CLI contract gains an "Archive limits" paragraph under the vendor command: the limits an npm tarball, a Python wheel or sdist and a .nupkg are read within, what each command reports for an archive past one, the packages the limits were measured on, and the two measured wheels that stay refused. The `vendor_artifact_too_large` row no longer says the tag is for jars only. The usage guide states the limits in its vendoring section. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 +++++++- docs/usage.md | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc7..d67a77d94e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1662,6 +1662,12 @@ path. Without hosted pins the no-manifest no-op below is unchanged. Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as the patch's prebuilt platform gems instead: for each locked platform the server's `gem-platform` artifact and its `gem-platform-stub-gemspec` (each carries its `platform`), both verified like the ruby gem and its stub. Which prebuilds exist is read from the package reference alone, and the ruby gem it also names is not downloaded. While the server lists no prebuild for a locked platform nothing is downloaded and the gem is skipped (`vendor_prebuilt_platform_pending`). A prebuild need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check against the digest the server states for that platform is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. +**Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 512 MiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 512 MiB plus the archive itself is what checking one archive may take. + +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. + +Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. Two wheels within that download size unpack to more than 512 MiB and are refused: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB). Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). + Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` and the diff archive path). Vendored runs retain patch records in memory and embed them in the vendor ledger, without staging blobs. N-API and the hosted in-memory engine remain supported for callers such as the future GitHub App. **Vendored artifact repair (v5.0)**: `repair` checks the committed artifact and downloads a replacement for the same UUID into a temporary location. Before replacement it checks transfer integrity, patched-member hashes, and the original ledger's SHA-256 and size (file artifacts) or complete file inventory (directory artifacts). JVM repair also reproduces and checks the recorded repository metadata. Different downloaded bytes or inventories are refused; the old files, ledger and lockfiles remain intact. No installed package or patch blobs are required, and none are used to construct a replacement. Missing directory inventories cannot establish an exact replacement and require explicit re-vendoring. @@ -2539,7 +2545,7 @@ command's integration tests check its output. | `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. | | `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. | | `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. | -| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large` (jars): the committed jar is past the limits jars are read within (see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact that `repair` restores from the recorded jar). `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | +| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end-of-archive marker or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | | `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. The `no_matching_variant` reason says that `apply` leaves such a copy as it is, and for a gem names `bundle pristine ` and the `apply` to run after it. | | `no_matching_variant` | `failed` | apply, and the apply that `get` / `scan --mode agent` run (gem, PyPI): an installed copy of a release-variant base (a base whose manifest records are qualified, or a gem build beside another build of its version) whose files match none of the manifest's records for it and which holds one of the patch's files with other content: an edited copy, or another build of the version. (A copy that holds none of the files its records are matched by is not told to belong to them: they stay `package_not_installed`, and the run still exits 1.) Keyed by the base purl, one event per copy. The copy is left as it is and the run exits 1 (`partialFailure`). `error` names the copy and the file that holds neither side of a record; for a gem it adds `bundle pristine ` (or `gem pristine `), which restores an edited copy to the published gem. The copy is installed, so no record of the base is `package_not_installed` in that run. | | `redirect_unconfirmed` | `skipped` (`details.mode: "hosted"`) | hosted `scan` / `get` (v5.0, additive): the patch was granted but no lockfile entry pinning it could be rewritten. The status and exit code are unchanged for now, pending the open hosted exit-policy decision (#704); `--silent` hides the human line. | diff --git a/docs/usage.md b/docs/usage.md index 5480da62fb..8a6698a302 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -208,6 +208,13 @@ Vendoring verifies downloaded archives and patched file hashes. Healthy committe artifacts can be reused offline; new artifacts require the patch service. For changes to v4's local artifact building, see the [migration guide](migrating-to-v5.md#service-only-vendoring). +Archives are read within fixed limits. An npm tarball, a Python wheel or source +distribution or a `.nupkg` may hold 200,000 entries and unpack to 512 MiB, and to +no more than 100 times its own size once past 64 MiB; a jar may inflate to 1 GiB. +A package past a limit is not vendored, and a committed one fails `vendor --check` +and is left out by `vex` (`vendor_artifact_too_large`). The message names the limit +and what the archive unpacks to. + `repair` redownloads missing or corrupt artifacts and checks them against the existing ledger before replacement. It preserves project wiring and recorded integrity; different archive bytes require an explicit new vendoring operation. From 60f8b94c445918aad59ace352cef946f0abbbc01 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 09:08:50 -0500 Subject: [PATCH 04/13] Fail a tarball extraction past its unpacked cap instead of extracting short The tarball extractor of `vendor::registry_fetch` (registry tarballs, crates, the data archive of a gem, the tarball of a vlt directory) bounded the gzip stream at 512 MiB with `Read::take`. A reader that stops at its limit hands the tar parser an end of input, and between two entries the parser takes that for the end of the archive: the files before the cap were written, the ones after it were not, and the extraction returned success. A package cut short was then judged by the files it did hold. The stream is now read through the reader that fails on the first byte past the cap, as the zip extractors beside it already count what they inflate: "tarball decompresses past the 536870912-byte cap". The caps themselves are unchanged. This is the third `take(limit)` site named in #2330; the other two are the tarball readers of `patch::package`. Co-Authored-By: Claude Fable 5.2 --- .../src/patch/archive_limits.rs | 17 ++++ .../src/vendor/registry_fetch.rs | 97 +++++++++++++++++-- 2 files changed, 108 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index c370ba8199..28ddbd791a 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -97,6 +97,18 @@ impl ArchiveLimits { ratio_floor_bytes: 64 * MIB, }; + /// One limit on the inflated bytes and no other: for an extractor with + /// its own entry count, which unpacks to disk and has no use for the + /// ratio. + pub(crate) const fn inflated_only(max_inflated_bytes: u64) -> Self { + Self { + max_entries: usize::MAX, + max_inflated_bytes, + max_inflate_ratio: 1, + ratio_floor_bytes: max_inflated_bytes, + } + } + /// What one read of an archive of `archive_len` bytes may inflate. pub(crate) fn budget(&self, archive_len: u64) -> Budget { let by_ratio = archive_len.saturating_mul(self.max_inflate_ratio); @@ -297,6 +309,11 @@ mod tests { assert_eq!(limits.budget(655 * KIB).bytes(), 64 * MIB); assert_eq!(limits.budget(MIB).bytes(), 100 * MIB); assert_eq!(limits.budget(6 * MIB).bytes(), 512 * MIB); + + // An extractor's single limit is the same for an archive of any size. + let extractor = ArchiveLimits::inflated_only(4000); + assert_eq!(extractor.budget(0).bytes(), 4000); + assert_eq!(extractor.budget(u64::MAX).bytes(), 4000); } #[test] diff --git a/crates/socket-patch-core/src/vendor/registry_fetch.rs b/crates/socket-patch-core/src/vendor/registry_fetch.rs index 6520840f8f..6a365054a6 100644 --- a/crates/socket-patch-core/src/vendor/registry_fetch.rs +++ b/crates/socket-patch-core/src/vendor/registry_fetch.rs @@ -18,9 +18,10 @@ use super::lock_inventory::LockIntegrity; /// scope, but lock-recorded `resolved` URLs already carry custom hosts). pub const DEFAULT_NPM_REGISTRY: &str = "https://registry.npmjs.org"; -/// Whole-package caps — wider than `patch/package.rs`'s patch-archive caps -/// because these are full upstream packages, but still bounded so a -/// poisoned lockfile cannot turn the fetch into a disk/memory bomb. +/// Whole-package caps for the fetches and the extractors here, which unpack +/// to disk — bounded so a poisoned lockfile cannot turn the fetch into a +/// disk/memory bomb. The readers that decode a package into memory have +/// their own (`patch::archive_limits`). pub(crate) const MAX_DOWNLOAD_BYTES: u64 = 128 * 1024 * 1024; // `pub(crate)`: `common::read_zip_members` is the in-memory twin of // [`extract_zip`] and must refuse exactly the same archives, so it reads the @@ -1268,9 +1269,51 @@ fn walk_tar_gz( skip_file_name: Option<&str>, strict: bool, ) -> Result<(), String> { - use std::io::Read as _; - let gz = flate2::read::GzDecoder::new(bytes).take(MAX_TOTAL_DECOMPRESSED_BYTES); - let mut archive = tar::Archive::new(gz); + let max_inflated = MAX_TOTAL_DECOMPRESSED_BYTES; + walk_tar_gz_within( + bytes, + dest, + strip_first, + skip_file_name, + strict, + max_inflated, + ) +} + +/// [`walk_tar_gz`] of a tarball that may unpack to `max_inflated` bytes. +fn walk_tar_gz_within( + bytes: &[u8], + dest: &Path, + strip_first: bool, + skip_file_name: Option<&str>, + strict: bool, + max_inflated: u64, +) -> Result<(), String> { + use crate::patch::archive_limits::{ArchiveLimits, Bounded}; + // The first byte past the cap fails the read. `Read::take` ends the + // input there instead, and the tar parser takes an end of input between + // two entries for the end of the archive: the tree was then extracted + // without the entries past the cap, and without an error. + let budget = ArchiveLimits::inflated_only(max_inflated).budget(bytes.len() as u64); + let mut inflated = Bounded::new(flate2::read::GzDecoder::new(bytes), &budget); + let walked = walk_tar(&mut inflated, dest, strip_first, skip_file_name, strict); + if inflated.over() { + return Err(format!( + "tarball decompresses past the {max_inflated}-byte cap" + )); + } + walked +} + +/// [`walk_tar_gz`] over the tar stream `inflated`. +fn walk_tar( + inflated: impl std::io::Read, + dest: &Path, + strip_first: bool, + skip_file_name: Option<&str>, + strict: bool, +) -> Result<(), String> { + let mut archive = tar::Archive::new(inflated); let mut out = EntrySink::new(dest).skipping(skip_file_name); let mut count = 0usize; for entry in archive @@ -1446,6 +1489,48 @@ mod tests { ) } + /// Wherever the cap falls in a tarball, the extraction either writes + /// every file or fails. A cap between two entries used to end it with + /// the files before the cap written and no error: a tree short of the + /// rest, taken for the whole package. + #[test] + fn a_tarball_past_the_unpacked_cap_fails_instead_of_extracting_short() { + let first = [1u8; 700]; + let second = [2u8; 300]; + let tgz = make_tgz(&[ + ("pkg/first.bin", &first, false), + ("pkg/second.bin", &second, false), + ]); + // Three blocks for the first file (its header and 700 bytes), two + // for the second, and one block of the end-of-archive marker: all + // the extractor reads. + let (second_entry, consumed) = (3 * 512, 6 * 512); + let around_each_block = (0..=consumed + 1024) + .step_by(512) + .flat_map(|block: u64| [block.saturating_sub(1), block, block + 1]); + for cap in around_each_block { + let tmp = tempfile::tempdir().unwrap(); + let extracted = walk_tar_gz_within(&tgz, tmp.path(), true, None, true, cap); + if cap >= consumed { + assert_eq!(extracted, Ok(()), "cap {cap}"); + assert_eq!(std::fs::read(tmp.path().join("first.bin")).unwrap(), first); + assert_eq!( + std::fs::read(tmp.path().join("second.bin")).unwrap(), + second + ); + } else { + assert_eq!( + extracted, + Err(format!("tarball decompresses past the {cap}-byte cap")), + "cap {cap}" + ); + } + } + // The cap that was silent: exactly where the second entry starts. + let tmp = tempfile::tempdir().unwrap(); + assert!(walk_tar_gz_within(&tgz, tmp.path(), true, None, true, second_entry).is_err()); + } + #[test] fn tarball_url_forms() { assert_eq!( From 04e6fdfb589a95ca82e649fc360c598648252cc6 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 09:38:27 -0500 Subject: [PATCH 05/13] Look for a second entry over a patched file as far as the installers read `vendor --check`, `vex` and `repair` refuse a committed npm tarball that holds a second entry an installer would extract over a patched file (`vendor_artifact_non_canonical`). The check ended a tarball where this crate's tar reader does, at the first all-zero block of the first gzip member. The installers read further, so a second `package/index.js` placed past that point verified here and installed the original (#2330). Measured with a tarball installed as a `file:` dependency: - npm 11.19.1 takes an entry that follows a single zero block (it ends an archive at two), passing over a block that is no tar header with a warning, and one in a second gzip member when the first has no end-of-archive marker. - Yarn 1.22.19 takes those, and an entry after the marker or in a second gzip member after it. The check now judges every entry up to the first zero block as before (an entry that cannot be read there still fails it), and then every entry after it: past zero blocks and blocks that are no header, to the end of the gzip member and through each member that follows. Nothing in that part fails the check for being unreadable, so a tarball with padding or other bytes after its marker verifies as it did. The limits count what is inflated there, and a limit that is met there is the same error. The reader that decodes the members for hashing is unchanged: it reads what it read, and the check above is what answers for the rest. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- .../tests/vendor/vendor_failure_paths.rs | 82 ++++ .../src/patch/archive_limits.rs | 10 + crates/socket-patch-core/src/patch/package.rs | 360 +++++++++++++++--- 4 files changed, 408 insertions(+), 48 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d67a77d94e..1de40c952d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1664,7 +1664,7 @@ Coverage includes npm (all lock flavors), Python wheels and source distributions **Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 512 MiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 512 MiB plus the archive itself is what checking one archive may take. -An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. That check reads the whole gzip stream, every member of it, so for it the limits count the padding and whatever else follows the end-of-archive marker. Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. Two wheels within that download size unpack to more than 512 MiB and are refused: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB). Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). @@ -2545,7 +2545,7 @@ command's integration tests check its output. | `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. | | `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. | | `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. | -| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end-of-archive marker or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | +| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). The second entry is looked for as far as any installer reads, which is further than the tarball's first all-zero block and first gzip member: npm takes an entry that follows a single zero block (passing over a block that is no tar header on the way) or that sits in a further gzip member while it has seen no end-of-archive marker, and Yarn 1 takes one after the marker and in a further gzip member as well. Zero padding and other bytes after the marker that hold no entry change nothing. Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | | `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. The `no_matching_variant` reason says that `apply` leaves such a copy as it is, and for a gem names `bundle pristine ` and the `apply` to run after it. | | `no_matching_variant` | `failed` | apply, and the apply that `get` / `scan --mode agent` run (gem, PyPI): an installed copy of a release-variant base (a base whose manifest records are qualified, or a gem build beside another build of its version) whose files match none of the manifest's records for it and which holds one of the patch's files with other content: an edited copy, or another build of the version. (A copy that holds none of the files its records are matched by is not told to belong to them: they stay `package_not_installed`, and the run still exits 1.) Keyed by the base purl, one event per copy. The copy is left as it is and the run exits 1 (`partialFailure`). `error` names the copy and the file that holds neither side of a record; for a gem it adds `bundle pristine ` (or `gem pristine `), which restores an edited copy to the published gem. The copy is installed, so no record of the base is `package_not_installed` in that run. | | `redirect_unconfirmed` | `skipped` (`details.mode: "hosted"`) | hosted `scan` / `get` (v5.0, additive): the patch was granted but no lockfile entry pinning it could be rewritten. The status and exit code are unchanged for now, pending the open hosted exit-policy decision (#704); `--silent` hides the human line. | diff --git a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs index 936a04ae4d..8aadf49cba 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs @@ -1701,3 +1701,85 @@ fn check_sees_a_second_entry_where_the_old_limit_fell() { "{env:#}" ); } + +/// #2330: the installers read a tarball further than its first zero block +/// and its first gzip member, where the check for a second entry stopped. +/// npm 11 takes a `package/index.js` that follows a single zero block, or +/// that sits in a second gzip member when the first has no end-of-archive +/// marker; Yarn 1 takes one after the marker too. Each is +/// `vendor_artifact_non_canonical`; zero padding after the marker, which +/// packers write, checks clean. +#[test] +fn check_sees_a_second_entry_past_the_first_zero_block_and_gzip_member() { + let fx = npm_fixture(); + let (code, env) = vendor_cli(fx.root(), &[]); + assert_eq!(code, 0, "{env:#}"); + + // The members as a tar stream without its end-of-archive marker. + let tar_of = |members: &[(&str, &[u8])]| -> Vec { + let mut builder = tar::Builder::new(Vec::new()); + for (name, bytes) in members { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_mtime(0); + header.set_cksum(); + builder.append_data(&mut header, name, *bytes).unwrap(); + } + let mut tar = builder.into_inner().unwrap(); + tar.truncate(tar.len() - 1024); + tar + }; + let gzip = |bytes: &[u8]| -> Vec { + use std::io::Write as _; + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gz.write_all(bytes).unwrap(); + gz.finish().unwrap() + }; + let package = tar_of(&[ + ( + "package/package.json", + br#"{"name":"left-pad","version":"1.3.0"}"#, + ), + ("package/index.js", PATCHED_INDEX), + ]); + let second = tar_of(&[("package/index.js", ORIG_INDEX)]); + let (zero, marker) = ([0u8; 512], [0u8; 1024]); + + replace_committed_tarball( + &fx, + &gzip(&[&package[..], &vec![0u8; 10240 - package.len()]].concat()), + ); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 0, "zero padding to a 10 KiB record: {env:#}"); + + for (label, tgz) in [ + ( + "after one zero block", + gzip(&[&package[..], &zero, &second, &marker].concat()), + ), + ( + "after the marker", + gzip(&[&package[..], &marker, &second, &marker].concat()), + ), + ( + "in a second gzip member", + [ + gzip(&[&package[..], &marker].concat()), + gzip(&[&second[..], &marker].concat()), + ] + .concat(), + ), + ] { + replace_committed_tarball(&fx, &tgz); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 1, "{label}: {env:#}"); + let failed = find_event(&env, "failed", Some("vendor_check_failed")); + assert!( + failed["reason"] + .as_str() + .is_some_and(|m| m.contains("(vendor_artifact_non_canonical)")), + "{label}: {env:#}" + ); + } +} diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index 28ddbd791a..fb07b378fa 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -236,6 +236,16 @@ impl Bounded { pub(crate) fn over(&self) -> bool { self.over } + + /// The reader the budget is counted on. + pub(crate) fn inner_mut(&mut self) -> &mut R { + &mut self.inner + } + + /// How many bytes of the input were read so far. + pub(crate) fn taken(&self) -> u64 { + self.read + } } impl Read for Bounded { diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 2f8d8574f6..6ba187d2d1 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -223,9 +223,29 @@ pub(crate) fn read_archive_bytes_to_map_any_root( /// files: an upstream tarball with a link, a non-ASCII name or a case twin /// somewhere else still passes. /// -/// Every entry up to the tar end-of-archive marker is judged or the call -/// fails: a tarball past a limit is [`ArchiveError::TooLarge`], never one -/// whose entries beyond the limit went unseen. +/// # How far it reads +/// +/// The decoder ends a tarball at the first all-zero block of its first gzip +/// member. The installers read further, each to a different point (npm +/// 11.19.1 and Yarn 1.22.19, each given a tarball as a `file:` dependency): +/// +/// | A second entry for a patched file | npm installs | Yarn 1 installs | +/// |---|---|---| +/// | after one zero block | the second | the second | +/// | after one zero block and a block that is no header | the second | nothing (it fails) | +/// | in a second gzip member, the first without a marker | the second | the second | +/// | after the marker (two zero blocks) | the first | the second | +/// | in a second gzip member, after the marker | the first | the second | +/// +/// So every entry up to that first zero block is judged or the call fails, +/// as the decoder would, and then every entry after it is judged too: past +/// zero blocks and past blocks that are no tar header (npm passes over one +/// with a warning), to the end of the gzip member, and through each gzip +/// member that follows. Nothing in that part fails the check for being +/// unreadable, since padding and trailing bytes are no entries: only an +/// entry there that lands on a patched file does, or a limit. A tarball +/// past a limit is [`ArchiveError::TooLarge`] wherever the limit is met, +/// never one whose entries beyond the limit went unseen. pub(crate) fn shadowed_member( bytes: &[u8], files: &[String], @@ -239,11 +259,51 @@ fn shadowed_member_within( files: &[String], budget: &Budget, ) -> Result, ArchiveError> { - let mut inflated = Bounded::new(GzDecoder::new(bytes), budget); + let mut inflated = Bounded::new(GzMembers::first_of(bytes), budget); let shadowed = shadowed_in_tar(&mut inflated, files, budget); within_budget(shadowed, &inflated, budget) } +/// The gzip members of a tarball as one stream: the first alone, as the +/// decoder reads a tarball, until [`Self::follow_the_rest`], then each +/// member that follows it. Bytes after a member that do not start another +/// one end the stream, as they do for a gunzip. +struct GzMembers<'a> { + member: flate2::bufread::GzDecoder<&'a [u8]>, + follow: bool, +} + +impl<'a> GzMembers<'a> { + fn first_of(bytes: &'a [u8]) -> Self { + GzMembers { + member: flate2::bufread::GzDecoder::new(bytes), + follow: false, + } + } + + fn follow_the_rest(&mut self) { + self.follow = true; + } +} + +impl Read for GzMembers<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + loop { + let n = self.member.read(buf)?; + if n > 0 || buf.is_empty() || !self.follow { + return Ok(n); + } + // The member has ended: the decoder took its input up to the + // end of the member's trailer and no further. + let rest: &[u8] = self.member.get_ref(); + if !rest.starts_with(&[0x1f, 0x8b]) { + return Ok(0); + } + self.member = flate2::bufread::GzDecoder::new(rest); + } + } +} + /// The outcome of a walk over `inflated`, unless the walk met the budget: /// that is the error, whatever the tar parser made of the failed read. fn within_budget( @@ -268,18 +328,14 @@ fn count_entry(entry_count: &mut usize, budget: &Budget) -> Result<(), ArchiveEr Ok(()) } -/// [`shadowed_member`] over the tar stream `inflated`. -fn shadowed_in_tar( - inflated: R, - files: &[String], - budget: &Budget, -) -> Result, ArchiveError> { - use tar::EntryType; +/// How many entries an installer writes onto each patched file. +struct Writers(HashMap); +impl Writers { // Extractors normalize `..` as well as `.` and empty segments, so // `package/x/../index.js` lands on `index.js`. A `..` above the start // is dropped: what it would reach is outside the package either way. - let fold = |path: &str| -> String { + fn fold(path: &str) -> String { let mut segments: Vec = Vec::new(); for segment in path.split('/') { match segment { @@ -291,47 +347,112 @@ fn shadowed_in_tar( } } segments.join("/") - }; - let mut writers: HashMap = files - .iter() - .map(|file| (fold(normalize_file_path(file)), 0)) - .collect(); - let mut tar = Archive::new(inflated); - let mut entry_count: usize = 0; - for entry in tar.entries()? { - let entry = entry?; - count_entry(&mut entry_count, budget)?; - let entry_type = entry.header().entry_type(); + } + + fn of(files: &[String]) -> Self { + Writers( + files + .iter() + .map(|file| (Self::fold(normalize_file_path(file)), 0)) + .collect(), + ) + } + + /// Count `entry`. `Some` is a patched file it makes unwritable: an + /// entry that is not a directory where one of the file's parent + /// directories must be. + fn judge(&mut self, entry: &tar::Entry<'_, R>) -> std::io::Result> { + use tar::EntryType; if matches!( - entry_type, + entry.header().entry_type(), EntryType::XGlobalHeader | EntryType::XHeader | EntryType::GNULongName | EntryType::GNULongLink | EntryType::Directory ) { - continue; + return Ok(None); } let raw = entry.path()?.to_string_lossy().replace('\\', "/"); - let folded = fold(&raw); + let folded = Self::fold(&raw); // What is left after the installer drops the first segment. let Some((_, installed)) = folded.split_once('/') else { - continue; + return Ok(None); }; - if let Some(count) = writers.get_mut(installed) { + if let Some(count) = self.0.get_mut(installed) { *count += 1; - } else if let Some(file) = writers.keys().find(|file| { - file.strip_prefix(installed) - .is_some_and(|rest| rest.starts_with('/')) - }) { - return Ok(Some(file.clone())); + return Ok(None); } + Ok(self + .0 + .keys() + .find(|file| { + file.strip_prefix(installed) + .is_some_and(|rest| rest.starts_with('/')) + }) + .cloned()) + } + + /// The first patched file more than one entry is written onto. + fn shadowed(self) -> Option { + self.0 + .into_iter() + .filter(|(_, count)| *count > 1) + .map(|(file, _)| file) + .min() } - Ok(writers - .into_iter() - .filter(|(_, count)| *count > 1) - .map(|(file, _)| file) - .min()) +} + +/// [`shadowed_member`] over the tar stream `inflated` (see there for how +/// far it reads). +fn shadowed_in_tar( + inflated: &mut Bounded>, + files: &[String], + budget: &Budget, +) -> Result, ArchiveError> { + let mut writers = Writers::of(files); + let mut entry_count: usize = 0; + { + // To the first zero block of the first gzip member: what the + // decoder reads, so an entry that cannot be read fails the check. + let mut tar = Archive::new(&mut *inflated); + for entry in tar.entries()? { + let entry = entry?; + count_entry(&mut entry_count, budget)?; + if let Some(file) = writers.judge(&entry)? { + return Ok(Some(file)); + } + } + } + // Then what follows it, to the end of every gzip member. The tar reader + // took the stream up to the end of that zero block, so the next reader + // starts on a block boundary. + inflated.inner_mut().follow_the_rest(); + loop { + let before = inflated.taken(); + let mut rest = Archive::new(&mut *inflated); + rest.set_ignore_zeros(true); + let mut ended = true; + for entry in rest.entries()? { + // A block that is no header: the reader took that block and + // stops for good, so another one goes on from the next block. + let Ok(entry) = entry else { + ended = false; + break; + }; + count_entry(&mut entry_count, budget)?; + // A name that cannot be read is no patched file's. + if let Ok(Some(file)) = writers.judge(&entry) { + return Ok(Some(file)); + } + } + // A limit that was met is the caller's to report. A reader that + // failed without taking a byte would fail the same way again. + if ended || inflated.over() || inflated.taken() == before { + break; + } + } + Ok(writers.shadowed()) } /// Read a source distribution without npm's `package/` prefix convention. @@ -1073,23 +1194,28 @@ mod tests { ]; let second_entry = raw_tar(&entries[..2]).len() as u64; let mut tar_bytes = raw_tar(&entries); - // What the tar reader takes: every entry and one block of the - // end-of-archive marker. - let consumed = tar_bytes.len() as u64 + 512; + // What the decoder takes: every entry and one block of the + // end-of-archive marker. The check for a second entry reads on to + // the end of the stream. + let decoded = tar_bytes.len() as u64 + 512; tar_bytes.extend([0u8; 1024]); + let stream = tar_bytes.len() as u64; let tgz = gzip(&tar_bytes); - for limit in 0..=consumed + 600 { + for limit in 0..=stream + 600 { let budget = budget(limit); + let why = budget.exceeded(Unpacked::Unknown); let shadowed = shadowed_member_within(&tgz, &files, &budget); - let map = read_archive_from_reader(&tgz[..], &budget, false, true); - if limit >= consumed { + if limit >= stream { assert_eq!(shadowed.unwrap(), Some("index.js".to_string()), "{limit}"); + } else { + assert_eq!(too_large(shadowed), why, "limit {limit}"); + } + let map = read_archive_from_reader(&tgz[..], &budget, false, true); + if limit >= decoded { assert_eq!(map.unwrap()["index.js"], b"original", "{limit}"); continue; } - let why = budget.exceeded(Unpacked::Unknown); - assert_eq!(too_large(shadowed), why, "limit {limit}"); // A member whose header says it does not fit is refused by // that header, before it is read. let why_map = too_large(map); @@ -1162,6 +1288,148 @@ mod tests { } } + /// The installers read a tarball further than the decoder, which ends + /// at the first zero block of the first gzip member (the table on + /// [`shadowed_member`]). A second entry for a patched file anywhere in + /// what they read is found; what is no entry there fails nothing. + #[test] + fn a_second_entry_past_the_first_zero_block_or_gzip_member_is_seen() { + let files = vec!["package/index.js".to_string()]; + let package = raw_tar(&[ + ("package/package.json", FILE, b"{}"), + ("package/index.js", FILE, b"patched"), + ]); + let second = raw_tar(&[("package/index.js", FILE, b"original")]); + let other = raw_tar(&[("package/other.js", FILE, b"x")]); + let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); + let whole = [&package[..], &marker].concat(); + let late = [&second[..], &marker].concat(); + + let shadowing: Vec<(&str, Vec)> = vec![ + ( + "after one zero block", + gzip(&[&package[..], &zero, &late].concat()), + ), + ( + "after one zero block and a block that is no header", + gzip(&[&package[..], &zero, &junk, &late].concat()), + ), + ( + "after a zero block, a block that is no header and a zero block", + gzip(&[&package[..], &zero, &junk, &zero, &late].concat()), + ), + ("after the marker", gzip(&[&whole[..], &late].concat())), + ( + "after the marker and one more zero block", + gzip(&[&whole[..], &zero, &late].concat()), + ), + ( + "in a second gzip member, the first without a marker", + [gzip(&package), gzip(&late)].concat(), + ), + ( + "in a second gzip member, after the marker", + [gzip(&whole), gzip(&late)].concat(), + ), + ( + "in a third gzip member", + [gzip(&whole), gzip(&marker), gzip(&late)].concat(), + ), + ( + // The header is read before the member breaks off. + "in a second gzip member that is cut short", + [gzip(&whole), { + let member = gzip(&[&second[..], &noise(4096)].concat()); + member[..member.len() - 512].to_vec() + }] + .concat(), + ), + ]; + for (label, tgz) in &shadowing { + assert_eq!( + shadowed_member(tgz, &files).unwrap(), + Some("index.js".to_string()), + "{label}" + ); + // What the decoder hashes is the first entry, which is why the + // check has to read on. + assert_eq!( + read_archive_bytes_to_map(tgz).unwrap()["index.js"], + b"patched", + "{label}" + ); + } + + let clean: Vec<(&str, Vec)> = vec![ + ("two zero blocks, as npm pack writes", gzip(&whole)), + ("no marker", gzip(&package)), + ( + "zero padding to a 10 KiB record, as GNU tar writes", + gzip(&[&package[..], &vec![0u8; 10240 - package.len()]].concat()), + ), + ( + "blocks that are no header after the marker", + gzip(&[&whole[..], &junk, &junk].concat()), + ), + ( + "less than a block after the marker", + gzip(&[&whole[..], &[7u8; 100]].concat()), + ), + ( + "bytes after the gzip member that start no other", + [gzip(&whole), b"GARBAGE".repeat(16)].concat(), + ), + ( + "the start of a gzip member and nothing else", + [gzip(&whole), gzip(&late)[..12].to_vec()].concat(), + ), + ( + "a second gzip member that holds no tar", + [gzip(&whole), gzip(b"not a tar stream")].concat(), + ), + ( + "another file after the marker", + gzip(&[&whole[..], &other, &marker].concat()), + ), + ( + "another file in a second gzip member", + [gzip(&whole), gzip(&[&other[..], &marker].concat())].concat(), + ), + ]; + for (label, tgz) in &clean { + assert_eq!(shadowed_member(tgz, &files).unwrap(), None, "{label}"); + } + + // The limits hold past the first zero block too: on what is + // inflated there, and on the entries counted. + let padded = gzip(&[&whole[..], &vec![0u8; 8192]].concat()); + assert_eq!( + shadowed_member_within(&padded, &files, &budget(whole.len() as u64 + 8192)).unwrap(), + None + ); + assert_eq!( + too_large(shadowed_member_within( + &padded, + &files, + &budget(whole.len() as u64 + 8191) + )), + "it unpacks to more than 11 KiB, the limit for one archive" + ); + let two_entries = ArchiveLimits { + max_entries: 2, + ..ArchiveLimits::IN_MEMORY + }; + let tgz = gzip(&[&whole[..], &other, &marker].concat()); + assert_eq!( + too_large(shadowed_member_within( + &tgz, + &files, + &two_entries.budget(tgz.len() as u64) + )), + "it holds more than 2 entries, the limit for one archive" + ); + } + #[test] fn test_read_archive_rejects_oversize_entry_header() { // Forge a header that claims a 1 GiB entry backed by tiny actual From 633811024a9f2e73c5d8151460faeb92cd57a386 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 11:44:37 -0500 Subject: [PATCH 06/13] Reserve a member's buffer as it arrives, and call an artifact too large on disk too large Three fixes from review of the archive limits. A tarball member's buffer was reserved in one piece for the size its header declares, once that size fit what is left of the archive's budget. The budget is up to 512 MiB for an archive of five megabytes, where the old cap on one member was 16 MiB, so a small crafted tarball could make `vendor --check` or `vex` reserve half a gigabyte on a header's claim. On a 32-bit build, or with overcommit off, that reservation fails and `Vec::with_capacity` aborts the process. The buffer now starts at 128 KiB and doubles as the content arrives, up to the declared size and never past it, and a reservation the machine cannot make is the too-large error ("it holds a member of 300 MiB, more than there is memory for"). The zip reader reserves nothing on a declared size. A committed wheel, sdist or npm tarball larger than 512 MiB on disk was still `vendor_artifact_unreadable` ("cannot be read"): the size gate before the readers returned that tag. It is `vendor_artifact_too_large` now, as the contract says of an artifact past the limits, and `vendor --check` says "it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to". `vendor --check` named no limit when the limit was met only where the check for a second entry reads, past the decoder's end of the tarball (a second gzip member that inflates to 80 MiB): the text was recomputed with the decoder, which never gets there. It is taken from the same walk now. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/patch/archive_limits.rs | 28 ++++ crates/socket-patch-core/src/patch/package.rs | 112 +++++++++++++-- crates/socket-patch-core/src/vendor/verify.rs | 131 +++++++++++++++--- 4 files changed, 239 insertions(+), 34 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 1de40c952d..d843c76486 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1664,7 +1664,7 @@ Coverage includes npm (all lock flavors), Python wheels and source distributions **Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 512 MiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 512 MiB plus the archive itself is what checking one archive may take. -An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. That check reads the whole gzip stream, every member of it, so for it the limits count the padding and whatever else follows the end-of-archive marker. +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. That check reads the whole gzip stream, every member of it, so for it the limits count the padding and whatever else follows the end-of-archive marker. Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. Two wheels within that download size unpack to more than 512 MiB and are refused: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB). Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index fb07b378fa..732edbbf6a 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -199,6 +199,25 @@ impl Budget { } } +/// The error text of an archive with a member there is no memory to hold: +/// a limit of the machine, met before any of the archive's own. +pub(crate) fn no_memory_for(member_bytes: u64) -> String { + format!( + "it holds a member of {}, more than there is memory for", + size(member_bytes) + ) +} + +/// The error text of an archive of `archive_len` bytes on disk that is not +/// read at all, being larger than the `max` bytes an archive is read up to. +pub(crate) fn larger_on_disk(archive_len: u64, max: u64) -> String { + format!( + "it is {} on disk, over the {} a committed artifact is read up to", + size(archive_len), + size(max) + ) +} + /// `bytes` rounded up to whole KiB below 1 MiB and to whole MiB above, so a /// size just past a limit never prints as the limit. fn size(bytes: u64) -> String { @@ -366,6 +385,15 @@ mod tests { "it unpacks to 300 MiB, over 100 times its own size (2 MiB) and the 64 MiB every \ archive may use" ); + + assert_eq!( + no_memory_for(300 * MIB), + "it holds a member of 300 MiB, more than there is memory for" + ); + assert_eq!( + larger_on_disk(512 * MIB + 1, 512 * MIB), + "it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to" + ); } /// A budget of exactly `bytes`, whatever the archive's size. diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 6ba187d2d1..38567defc0 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -135,10 +135,15 @@ fn budget_of(bytes: &[u8]) -> Budget { /// [`ArchiveError::TooLarge`]; `None` when it is within them all. For the /// message of a caller that holds only a reader's routing tag. pub(crate) fn limit_exceeded(bytes: &[u8]) -> Option { - match read_archive_from_reader(bytes, &budget_of(bytes), false, false) { - Err(ArchiveError::TooLarge(why)) => Some(why), + let limit = |read: Option| match read { + Some(ArchiveError::TooLarge(why)) => Some(why), _ => None, - } + }; + // The decoder first: a member's header says how much the tarball + // unpacks to. Then the check for a second entry, which reads on where + // the decoder ends and can meet a limit there that the decoder does not. + limit(read_archive_from_reader(bytes, &budget_of(bytes), false, false).err()) + .or_else(|| limit(shadowed_member(bytes, &[]).err())) } /// [`read_archive_bytes_to_map`] that additionally refuses any archive an @@ -611,9 +616,9 @@ fn members_of_tar( // The header-declared size is attacker-controlled. Reject a // member that does not fit in what is left of the archive's budget - // *before* allocating, so a single u64::MAX claim can't OOM the - // process via `Vec::with_capacity`: what a header may claim is - // bounded by the budget, and so by the archive's own size. + // *before* reading it: what a header may claim is bounded by the + // budget, and so by the archive's own size. The buffer is then + // grown as the content arrives ([`read_member`]). let size = entry.size(); let unpacked = entry.raw_file_position(); if size > budget.bytes().saturating_sub(unpacked) { @@ -622,11 +627,7 @@ fn members_of_tar( )); } - // `size` is within the budget (512 MiB at most), so the cast to - // `usize` is safe on all targets we support. - let mut bytes = Vec::with_capacity(size as usize); - entry.read_to_end(&mut bytes)?; - out.insert(normalized, bytes); + out.insert(normalized, read_member(&mut entry, size)?); } Ok(out) @@ -857,6 +858,47 @@ mod tests { /// Write a `.tar.gz` whose single regular-file entry carries `long_name` /// via a GNU `././@LongLink` (typeflag `L`) pseudo-entry. This is the only +/// What is reserved for a member before any of its content is read. +const MEMBER_FIRST_RESERVE: usize = 128 * 1024; + +/// Up to `size` bytes of a member, from `entry`; fewer when the input ends +/// first, which the walk then finds at the next header. +/// +/// The size comes from the member's header, its author's claim, and is +/// within what is left of the archive's budget: up to 512 MiB, for an +/// archive of five megabytes. So the buffer is not reserved in one piece on +/// that claim. It starts at [`MEMBER_FIRST_RESERVE`] and doubles as the +/// content arrives, up to `size` and never past it, and a reservation the +/// machine cannot make is [`ArchiveError::TooLarge`], where +/// `Vec::with_capacity` aborts the process. +fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError> { + use crate::patch::archive_limits::no_memory_for; + let no_memory = || ArchiveError::TooLarge(no_memory_for(size)); + let wanted = usize::try_from(size).map_err(|_| no_memory())?; + let mut bytes: Vec = Vec::new(); + while bytes.len() < wanted { + let held = bytes.len(); + let more = (wanted - held).min(held.max(MEMBER_FIRST_RESERVE)); + bytes.try_reserve_exact(more).map_err(|_| no_memory())?; + bytes.resize(held + more, 0); + let mut filled = held; + while filled < bytes.len() { + match entry.read(&mut bytes[filled..]) { + Ok(0) => break, + Ok(n) => filled += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e.into()), + } + } + let ended = filled < bytes.len(); + bytes.truncate(filled); + if ended { + break; + } + } + Ok(bytes) +} + /// way to smuggle bytes a plain ustar name field can't hold — notably an /// embedded NUL (the ustar name field is NUL-terminated). fn write_gnu_longname_archive(path: &Path, long_name: &[u8], data: &[u8]) { @@ -1550,3 +1592,51 @@ mod tests { ); } } + /// A limit that only the check for a second entry meets, in the part of + /// a tarball the decoder does not read, is named like any other: here a + /// second gzip member of 80 MiB of zeros after a whole package. + #[test] + fn a_limit_met_past_the_first_gzip_member_is_named() { + let files = vec!["package/index.js".to_string()]; + let package = raw_tar_gz(&[ + ("package/package.json", FILE, b"{}"), + ("package/index.js", FILE, b"patched"), + ]); + let tgz = [package, gzip(&vec![0u8; 80 * MIB])].concat(); + assert!(tgz.len() < 128 * 1024, "{}", tgz.len()); + + // The decoder ends at the first member, within every limit. + assert_eq!(read_archive_bytes_to_map(&tgz).unwrap().len(), 2); + let why = too_large(shadowed_member(&tgz, &files)); + assert!( + why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size (") + && why.ends_with(" KiB) and the 64 MiB every archive may use"), + "{why}" + ); + assert_eq!(limit_exceeded(&tgz), Some(why)); + } + + /// The size in a member's header is its author's claim. Before any of + /// the content is read it reserves 128 KiB at most, however much the + /// archive's budget would allow it, and the buffer then grows with what + /// arrives, up to the declared size and never past it. + #[test] + fn a_members_declared_size_alone_reserves_little() { + // 400 MiB claimed, ten bytes there. + let bytes = read_member(&mut &b"ten bytes!"[..], 400 * MIB as u64).unwrap(); + assert_eq!(bytes, b"ten bytes!"); + assert!( + bytes.capacity() <= 128 * 1024, + "{} bytes reserved for ten", + bytes.capacity() + ); + + let content = noise(3 * MIB + 17); + let bytes = read_member(&mut &content[..], content.len() as u64).unwrap(); + assert_eq!(bytes, content); + assert_eq!(bytes.capacity(), content.len()); + // No more than the declared size is taken from a longer input. + let bytes = read_member(&mut &content[..], 1000).unwrap(); + assert_eq!(bytes, content[..1000]); + } + diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 65b1b1ec10..763b5a2ae2 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -116,15 +116,17 @@ pub async fn verify_vendored_patch_record( let members = tokio::task::spawn_blocking(move || { let (file, meta) = crate::utils::fs::open_regular_file_sync(&artifact) .map_err(|_| "vendor_artifact_unreadable")?; + // Larger on disk than an artifact is read up to: too large, + // like one past a limit of its reader, and not read at all. if meta.len() > MAX_HEALTH_HASH_BYTES { - return Err("vendor_artifact_unreadable".into()); + return Err(ARTIFACT_TOO_LARGE.into()); } let mut bytes = Vec::new(); file.take(MAX_HEALTH_HASH_BYTES + 1) .read_to_end(&mut bytes) .map_err(|_| "vendor_artifact_unreadable")?; if bytes.len() as u64 > MAX_HEALTH_HASH_BYTES { - return Err("vendor_artifact_unreadable".into()); + return Err(ARTIFACT_TOO_LARGE.into()); } super::pypi_distribution::read_members(&bytes, &name).map_err(unread_tag) }) @@ -198,14 +200,14 @@ pub async fn verify_vendored_patch_record( let (file, meta) = crate::utils::fs::open_regular_file_sync(&artifact) .map_err(|_| "vendor_artifact_unreadable".to_string())?; if meta.len() > MAX_HEALTH_HASH_BYTES { - return Err("vendor_artifact_unreadable".to_string()); + return Err(ARTIFACT_TOO_LARGE.to_string()); } let mut bytes = Vec::new(); file.take(MAX_HEALTH_HASH_BYTES + 1) .read_to_end(&mut bytes) .map_err(|_| "vendor_artifact_unreadable".to_string())?; if bytes.len() as u64 > MAX_HEALTH_HASH_BYTES { - return Err("vendor_artifact_unreadable".to_string()); + return Err(ARTIFACT_TOO_LARGE.to_string()); } match crate::patch::package::shadowed_member(&bytes, &patched_files) { Ok(None) => {} @@ -1223,12 +1225,15 @@ pub async fn describe_artifact_failure( ArtifactHealth::Corrupt { reason } if reason == ARTIFACT_TOO_LARGE && !path.ends_with(".jar") => { - // Which limit, from the reader that met it. + // Which limit: its size on disk, or the one its reader met. let (artifact, name) = (project_root.join(path), path.clone()); let limit = tokio::task::spawn_blocking(move || { let (file, metadata) = crate::utils::fs::open_regular_file_sync(&artifact).ok()?; if metadata.len() > MAX_HEALTH_HASH_BYTES { - return None; + return Some(crate::patch::archive_limits::larger_on_disk( + metadata.len(), + MAX_HEALTH_HASH_BYTES, + )); } let mut bytes = Vec::new(); file.take(MAX_HEALTH_HASH_BYTES) @@ -3113,13 +3118,13 @@ mod tests { assert!(err.contains("exceeds 10000 files"), "got: {err}"); } - /// A committed artifact grown past the 512 MiB health-hash cap whose - /// TAIL is still a valid wheel (zip readers resolve the archive offset - /// past leading garbage) verifies member-wise but must classify - /// Corrupt/unreadable: the ledger-sha cross-check cannot vouch for - /// bytes it refuses to hash. + /// A committed artifact grown past the 512 MiB an artifact is read up + /// to, whose TAIL is still a valid wheel (zip readers resolve the + /// archive offset past leading garbage), is not read at all: it is too + /// large, and the check says how large it is on disk. It was "cannot be + /// read", which named no limit. #[tokio::test] - async fn oversize_artifact_with_valid_zip_tail_is_corrupt_unreadable() { + async fn oversize_artifact_with_valid_zip_tail_is_too_large() { use std::io::{Seek, SeekFrom}; let tmp = tempfile::tempdir().unwrap(); @@ -3144,21 +3149,103 @@ mod tests { let mut ent = entry("pypi", UUID, &rel); ent.artifact.sha256 = "0".repeat(64); - // Precondition: the zip reader tolerates the prefix, so member - // verification alone would bless the artifact… - assert!( - verify_vendored_patch_record(root, &ent, &rec) + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_too_large".to_string()) + ); + let health = check_vendored_artifact(root, &ent, &rec).await; + assert_eq!( + health, + ArtifactHealth::Corrupt { + reason: "vendor_artifact_too_large".to_string() + } + ); + assert_eq!( + describe_artifact_failure(root, &ent, &health) .await - .is_err(), - "member verification also refuses oversized archives" + .unwrap(), + format!( + "committed artifact {rel} is past the limits archives are read within: it is \ + 513 MiB on disk, over the 512 MiB a committed artifact is read up to \ + (vendor_artifact_too_large), so its contents were not checked; run \ + `socket-patch repair` to restore it, then commit it" + ) ); - // …and only the whole-file arm catches it: file_sha256_hex bails - // on the size cap, so the recorded sha is unverifiable. + } + + /// The same for a committed npm tarball: one byte more on disk than an + /// artifact is read up to. + #[tokio::test] + async fn a_committed_tarball_larger_on_disk_than_is_read_is_too_large() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let rel = format!(".socket/vendor/npm/{UUID}/x-1.0.0.tgz"); + let tgz = root.join(&rel); + std::fs::create_dir_all(tgz.parent().unwrap()).unwrap(); + // Sparse: nothing of it is read. + std::fs::File::create(&tgz) + .unwrap() + .set_len(MAX_HEALTH_HASH_BYTES + 1) + .unwrap(); + let rec = record(UUID, "package/index.js"); + let mut ent = entry("npm", UUID, &rel); + ent.artifact.sha256 = "ab".repeat(32); + assert_eq!( - check_vendored_artifact(root, &ent, &rec).await, + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_too_large".to_string()) + ); + let health = check_vendored_artifact(root, &ent, &rec).await; + let why = describe_artifact_failure(root, &ent, &health) + .await + .unwrap(); + assert!( + why.contains( + "is past the limits archives are read within: it is 513 MiB on disk, over the \ + 512 MiB a committed artifact is read up to (vendor_artifact_too_large)" + ), + "{why}" + ); + } + + /// A limit met only where the check for a second entry reads, past the + /// first gzip member of a committed npm tarball, is named by + /// `vendor --check` like one the decoder meets. + #[tokio::test] + async fn a_limit_met_past_the_first_gzip_member_of_a_committed_tarball_is_named() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let rel = format!(".socket/vendor/npm/{UUID}/x-1.0.0.tgz"); + let tgz = root.join(&rel); + std::fs::create_dir_all(tgz.parent().unwrap()).unwrap(); + write_tgz(&tgz, "package/index.js", PATCHED); + // A second gzip member: 80 MiB of zeros in some 80 KiB. + let mut member = GzEncoder::new( + std::fs::OpenOptions::new().append(true).open(&tgz).unwrap(), + flate2::Compression::new(6), + ); + member.write_all(&vec![0u8; 80 * 1024 * 1024]).unwrap(); + member.finish().unwrap(); + let rec = record(UUID, "package/index.js"); + let mut ent = entry("npm", UUID, &rel); + ent.artifact.sha256 = "ab".repeat(32); + + let health = check_vendored_artifact(root, &ent, &rec).await; + assert_eq!( + health, ArtifactHealth::Corrupt { - reason: "vendor_artifact_unreadable".to_string() + reason: "vendor_artifact_too_large".to_string() } ); + let why = describe_artifact_failure(root, &ent, &health) + .await + .unwrap(); + assert!( + why.contains( + "is past the limits archives are read within: it unpacks to more than 64 MiB, \ + over 100 times its own size (" + ), + "{why}" + ); } } From 1a8b66b79736f3b9a6ce7c0474fcb2d83d6f4aa8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 11:44:51 -0500 Subject: [PATCH 07/13] Take a header that names a tarball entry only in the shape every installer reads alike The check for a second entry over a patched file (`vendor --check`, `vex`, `repair`: `vendor_artifact_non_canonical`) counted each entry under the name this crate's tar reader gives it. An entry's name can come from a header before it, a GNU long name or a PAX header, and the readers agree on it only while that header is in its usual shape. Away from it a tarball could hold the patched `package/index.js`, then an entry the check read as `package/harmless.js`, which an installer writes to `index.js`. Review found two such shapes; installing each with npm 11.19.1 and Yarn 1.22.19 found more. The second entry was installed over the patched file, and the check verified the tarball, when the header before it was: - a long name or PAX header without the ustar or GNU magic, which this crate's reader does not apply (npm, Yarn 1); - an old GNU long name, type `N` (npm, Yarn 1), or an old PAX header, type `X` (npm); - a PAX header with two `path` records, of which this crate's reader takes the first and the installers the last (npm, Yarn 1); - a PAX header with an empty line before its `path`, where this crate's reader stops (npm); - a PAX `path` followed by a long name (Yarn 1), or a global PAX header with a `path` followed by any PAX header (Yarn 1); - after the first zero block, a long name or PAX header and then a block that is no header: the walk restarted there and dropped the name, and npm keeps it (npm). The tar stream is now walked header by header, and a header that names another entry is taken in one shape only: it has the ustar or GNU magic and comes before the first zero block; a long name ends at its first NUL; a PAX header is ` =` lines and nothing else, each as long as it says, with one `path` at most and a `size` that is the entry's own; no entry has both; neither is larger than 64 KiB; a global PAX header holds a comment only. Any other shape counts as a second entry for a patched file, whichever file the entry after it would have been, since that depends on the installer. The usual shapes keep verifying: tarballs with long paths made by `npm pack`, bsdtar (pax and gnutar), Python's tarfile and `git archive` were run through the walk, as was a tarball vendored from the patch service. The decoder that reads the members for hashing is unchanged, and gives a canonical tarball's entries the same names. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/vex.rs | 3 +- .../tests/vendor/vendor_failure_paths.rs | 116 +++ crates/socket-patch-core/src/patch/package.rs | 841 +++++++++++++++--- crates/socket-patch-core/src/vendor/verify.rs | 4 +- 5 files changed, 844 insertions(+), 122 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d843c76486..09351f454e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2545,7 +2545,7 @@ command's integration tests check its output. | `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. | | `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. | | `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. | -| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). The second entry is looked for as far as any installer reads, which is further than the tarball's first all-zero block and first gzip member: npm takes an entry that follows a single zero block (passing over a block that is no tar header on the way) or that sits in a further gzip member while it has seen no end-of-archive marker, and Yarn 1 takes one after the marker and in a further gzip member as well. Zero padding and other bytes after the marker that hold no entry change nothing. Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | +| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). The second entry is looked for as far as any installer reads, which is further than the tarball's first all-zero block and first gzip member: npm takes an entry that follows a single zero block (passing over a block that is no tar header on the way) or that sits in a further gzip member while it has seen no end-of-archive marker, and Yarn 1 takes one after the marker and in a further gzip member as well. Zero padding and other bytes after the marker that hold no entry change nothing. An entry is counted under the name a header before it gives it (a GNU long name, a PAX `path`), and such a header is taken only in the one shape every installer reads alike: it carries the ustar or GNU magic and comes before the tarball's first all-zero block; a long name ends at its first NUL; a PAX header is ` =` lines and nothing else, each as long as it says, with one `path` at most and a `size` that is the entry's own; no entry has both; neither is larger than 64 KiB; a global PAX header holds a comment only. Any other shape is read differently by npm, by Yarn 1 or by this check's own tar reader (an old-style long name or PAX header, one without the magic, two `path` records, an empty line before the `path`, a long name and a PAX `path` for one entry, a name held across a block that is no header), so the entry after it may be written onto any file: the tarball is `vendor_artifact_non_canonical` whichever file that entry would be. Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | | `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. The `no_matching_variant` reason says that `apply` leaves such a copy as it is, and for a gem names `bundle pristine ` and the `apply` to run after it. | | `no_matching_variant` | `failed` | apply, and the apply that `get` / `scan --mode agent` run (gem, PyPI): an installed copy of a release-variant base (a base whose manifest records are qualified, or a gem build beside another build of its version) whose files match none of the manifest's records for it and which holds one of the patch's files with other content: an edited copy, or another build of the version. (A copy that holds none of the files its records are matched by is not told to belong to them: they stay `package_not_installed`, and the run still exits 1.) Keyed by the base purl, one event per copy. The copy is left as it is and the run exits 1 (`partialFailure`). `error` names the copy and the file that holds neither side of a record; for a gem it adds `bundle pristine ` (or `gem pristine `), which restores an edited copy to the published gem. The copy is installed, so no record of the base is `package_not_installed` in that run. | | `redirect_unconfirmed` | `skipped` (`details.mode: "hosted"`) | hosted `scan` / `get` (v5.0, additive): the patch was granted but no lockfile entry pinning it could be rewritten. The status and exit code are unchanged for now, pending the open hosted exit-policy decision (#704); `--silent` hides the human line. | diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 3ab192df07..d0b63192b4 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2809,7 +2809,8 @@ fn omission_phrase(reason: &str) -> &'static str { "vendor_artifact_non_canonical" => { "the vendored tarball holds a second entry the package manager would extract \ over a patched file (another top-level directory, a second spelling of the \ - name, or a link), so what installs is not what was checked" + name, a link, or a name given by a header before the entry), so what installs \ + is not what was checked" } "vendor_lock_pin_mismatch" => { "the lockfile pins the vendored tarball to a sha512 that is not that file's, so \ diff --git a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs index 8aadf49cba..dcae5ff12f 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs @@ -1783,3 +1783,119 @@ fn check_sees_a_second_entry_past_the_first_zero_block_and_gzip_member() { ); } } + +/// A second entry can be given a patched file's name by a header before it +/// (a GNU long name, a PAX header) while its own header names another +/// file. The installers and this crate's tar reader read such a header +/// alike only in its usual shape: in each tarball here npm 11 writes the +/// original bytes to `index.js`, and the check read the entry as +/// `harmless.js` and verified. Each is `vendor_artifact_non_canonical`; +/// a long path named the usual way checks clean. +#[test] +fn check_sees_a_second_entry_named_by_a_header_before_it() { + let fx = npm_fixture(); + let (code, env) = vendor_cli(fx.root(), &[]); + assert_eq!(code, 0, "{env:#}"); + + // One raw tar entry: a header of type `flag`, with the ustar magic or + // without it, then the content padded to a block. + let entry = |name: &str, flag: u8, magic: bool, content: &[u8]| -> Vec { + let mut header = if magic { + tar::Header::new_ustar() + } else { + tar::Header::new_old() + }; + header.as_old_mut().name[..name.len()].copy_from_slice(name.as_bytes()); + header.set_size(content.len() as u64); + header.set_mode(0o644); + header.set_entry_type(tar::EntryType::new(flag)); + header.set_cksum(); + let mut out = header.as_bytes().to_vec(); + out.extend_from_slice(content); + out.resize(out.len() + (512 - content.len() % 512) % 512, 0); + out + }; + let gzip = |bytes: &[u8]| -> Vec { + use std::io::Write as _; + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gz.write_all(bytes).unwrap(); + gz.finish().unwrap() + }; + // PAX records, each ` =` and a newline. + let pax = |records: &[(&str, &str)]| -> Vec { + let mut out = Vec::new(); + for (key, value) in records { + let rest = format!(" {key}={value}\n"); + let mut len = rest.len() + 1; + while len.to_string().len() + rest.len() != len { + len = len.to_string().len() + rest.len(); + } + out.extend_from_slice(format!("{len}{rest}").as_bytes()); + } + out + }; + let package = [ + entry( + "package/package.json", + b'0', + true, + br#"{"name":"left-pad","version":"1.3.0"}"#, + ), + entry("package/index.js", b'0', true, PATCHED_INDEX), + ] + .concat(); + let harmless = entry("package/harmless.js", b'0', true, ORIG_INDEX); + let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); + let long = b"package/index.js\0"; + + let deep = format!("package/{}/{}.js", "d".repeat(90), "b".repeat(120)); + let usual = [ + &package[..], + &entry( + "PaxHeader/deep", + b'x', + true, + &pax(&[("path", &deep), ("size", "5")]), + ), + &entry(&deep[..99], b'0', true, b"deep\n"), + &marker, + ] + .concat(); + replace_committed_tarball(&fx, &gzip(&usual)); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 0, "a long path behind a PAX header: {env:#}"); + + for (label, named) in [ + ( + "a long name without the ustar magic", + entry("././@LongLink", b'L', false, long), + ), + ( + "a PAX header with two paths", + entry( + "PaxHeader/x", + b'x', + true, + &pax(&[("path", "package/fine.js"), ("path", "package/index.js")]), + ), + ), + ( + "after a zero block, a long name and a block that is no header", + [&zero[..], &entry("././@LongLink", b'L', true, long), &junk].concat(), + ), + ] { + replace_committed_tarball( + &fx, + &gzip(&[&package[..], &named, &harmless, &marker].concat()), + ); + let (code, env) = vendor_cli(fx.root(), &["--check"]); + assert_eq!(code, 1, "{label}: {env:#}"); + let failed = find_event(&env, "failed", Some("vendor_check_failed")); + assert!( + failed["reason"] + .as_str() + .is_some_and(|m| m.contains("(vendor_artifact_non_canonical)")), + "{label}: {env:#}" + ); + } +} diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 38567defc0..c80c4e14c3 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -251,6 +251,32 @@ pub(crate) fn read_archive_bytes_to_map_any_root( /// entry there that lands on a patched file does, or a limit. A tarball /// past a limit is [`ArchiveError::TooLarge`] wherever the limit is met, /// never one whose entries beyond the limit went unseen. +/// +/// # What an entry is called +/// +/// An entry's name can come from a header before it: a GNU long name (type +/// `L`) or a PAX header (`x`). The readers agree on that name only while +/// the header is in its usual shape. Away from it each goes its own way +/// (installed as above; "the second" is an entry whose own header names +/// another file): +/// +/// | The header before the second entry | npm installs | Yarn 1 installs | +/// |---|---|---| +/// | `L` or `x` without the ustar or GNU magic (this crate's reader applies neither) | the second | the second | +/// | an old GNU long name (`N`) | the second | the second | +/// | an old PAX header (`X`) | the second | nothing (it fails) | +/// | `x` with two `path` records (this crate's reader takes the first) | the second | the second | +/// | `x` with an empty line before its `path` (this crate's reader stops there) | the second | the first | +/// | `x` with a `path`, then `L` with another name | the first | the second | +/// | a global PAX header (`g`) with a `path`, then any `x` | the first | the second | +/// | `L` of more than 1 MiB | the first | the second | +/// | after a zero block: `L` or `x`, then a block that is no header | the second | nothing (it fails) | +/// +/// So the stream is walked header by header, and a header that names +/// another entry is taken only in the one shape every reader reads alike +/// ([`Writers::header`]). Any other shape counts as a second entry for a +/// patched file, whichever file the entry after it would have been: which +/// one it is depends on the installer. pub(crate) fn shadowed_member( bytes: &[u8], files: &[String], @@ -333,8 +359,100 @@ fn count_entry(entry_count: &mut usize, budget: &Budget) -> Result<(), ArchiveEr Ok(()) } +/// The largest body of a header that names another entry that is read. A +/// real one is a path or a few records. npm passes over one larger than a +/// megabyte where the other readers apply it, so one past this is no shape +/// every reader reads alike. +const MAX_NAMING_BYTES: u64 = 64 * 1024; + +/// Whether a header of type `flag` names another entry instead of being +/// one: a GNU long name or long link (`L`, `K`; `N`, the old long name), a +/// PAX header (`x`; `X`, the old one), a global PAX header (`g`). +fn names_another(flag: u8) -> bool { + matches!(flag, b'L' | b'N' | b'K' | b'x' | b'X' | b'g') +} + +/// The body of a header that names another entry; `None` past +/// [`MAX_NAMING_BYTES`]. +fn naming_body(entry: &mut tar::Entry<'_, R>) -> std::io::Result>> { + let size = entry.size(); + if size > MAX_NAMING_BYTES { + return Ok(None); + } + let mut body = Vec::with_capacity(size as usize); + entry.read_to_end(&mut body)?; + if body.len() as u64 != size { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + Ok(Some(body)) +} + +/// The name the body of a GNU long name gives, when every reader takes the +/// same one from it: the bytes up to the first NUL, and nothing but NULs +/// after them. +fn long_name(body: &[u8]) -> Option> { + let end = body.iter().position(|b| *b == 0).unwrap_or(body.len()); + (end > 0 && body[end..].iter().all(|b| *b == 0)).then(|| body[..end].to_vec()) +} + +/// The records of the body of a PAX header, as `(key, value)`, when every +/// reader takes the same ones from it: the body is ` =` +/// lines and nothing else, each as long as it says and one line long. A +/// reader that splits the body at newlines (npm, this crate's) and one that +/// goes by the lengths (Yarn 1) then see the same records. +fn pax_records(mut body: &[u8]) -> Option> { + let mut records = Vec::new(); + while !body.is_empty() { + let space = body.iter().position(|b| *b == b' ')?; + let digits = &body[..space]; + if digits.first().is_none_or(|first| *first == b'0') + || !digits.iter().all(u8::is_ascii_digit) + { + return None; + } + let length: usize = std::str::from_utf8(digits).ok()?.parse().ok()?; + if length > body.len() { + return None; + } + let (record, rest) = body.split_at(length); + let pair = record.strip_suffix(b"\n")?.get(space + 1..)?; + let equals = pair.iter().position(|b| *b == b'=')?; + if equals == 0 || pair.contains(&b'\n') { + return None; + } + records.push((&pair[..equals], &pair[equals + 1..])); + body = rest; + } + Some(records) +} + +/// What the headers since the last entry say of the next one. +#[derive(Default)] +struct Named { + /// The name a GNU long name gives it. + long_name: Option>, + /// The `path` and the `size` a PAX header gives it. + pax: Option<(Option>, Option)>, +} + +/// Count the header `entry` of a raw read against the entry limit, as the +/// decoder counts: a header that names another entry is none to it. +fn count_header( + entry: &tar::Entry<'_, R>, + entry_count: &mut usize, + budget: &Budget, +) -> Result<(), ArchiveError> { + if names_another(entry.header().entry_type().as_byte()) { + return Ok(()); + } + count_entry(entry_count, budget) +} + /// How many entries an installer writes onto each patched file. -struct Writers(HashMap); +struct Writers { + counts: HashMap, + named: Named, +} impl Writers { // Extractors normalize `..` as well as `.` and empty segments, so @@ -355,41 +473,144 @@ impl Writers { } fn of(files: &[String]) -> Self { - Writers( - files + Writers { + counts: files .iter() .map(|file| (Self::fold(normalize_file_path(file)), 0)) .collect(), - ) + named: Named::default(), + } + } + + /// The patched file to answer with when an entry's name cannot be told + /// for every installer: the entry may be written onto any of them. + fn any(&self) -> Option { + self.counts.keys().min().cloned() + } + + /// Whether a header named an entry and none has followed it. + fn names_no_entry(&self) -> bool { + self.named.long_name.is_some() || self.named.pax.is_some() + } + + /// Take the next header of the tar stream, read raw: the headers that + /// name another entry come as they are written, and are held here to + /// the one shape every reader reads alike (the table on + /// [`shadowed_member`]). `tail` is the part past the first zero block, + /// where a block that is no header is passed over and a reader may + /// carry a name across it: no such header is taken there. `Some` is a + /// patched file an installer may write from another entry. + fn header( + &mut self, + entry: &mut tar::Entry<'_, R>, + tail: bool, + ) -> std::io::Result> { + let header = entry.header(); + let flag = header.entry_type().as_byte(); + // What this crate's reader asks of a header before it applies it + // as a long name or a PAX header. The installers ask for less. + let magic = header.as_ustar().is_some() || header.as_gnu().is_some(); + match flag { + flag if tail && names_another(flag) => Ok(self.any()), + // The old long name and the old PAX header, which this crate's + // reader never applies, and a sparse file, whose map a raw read + // does not follow. + b'N' | b'X' | b'S' => Ok(self.any()), + b'L' | b'K' | b'x' if !magic => Ok(self.any()), + // A long link target: the entry after it is a link, counted + // under its own name. + b'K' => Ok(None), + b'L' => { + let name = naming_body(entry)?.as_deref().and_then(long_name); + match name { + Some(name) if self.named.long_name.is_none() => { + self.named.long_name = Some(name); + Ok(None) + } + _ => Ok(self.any()), + } + } + b'x' => { + let body = naming_body(entry)?; + let records = body.as_deref().and_then(pax_records); + let (Some(records), None) = (records, &self.named.pax) else { + return Ok(self.any()); + }; + let (mut path, mut size) = (None, None); + for (key, value) in records { + let usual = match key { + b"path" => !value.is_empty() && path.replace(value.to_vec()).is_none(), + b"size" => { + let digits = value.iter().all(u8::is_ascii_digit); + let bytes = + std::str::from_utf8(value).ok().and_then(|v| v.parse().ok()); + digits && bytes.is_some() && size.replace(bytes).is_none() + } + // The name of a sparse file, for a reader that + // unpacks one. + key => !key.starts_with(b"GNU.sparse."), + }; + if !usual { + return Ok(self.any()); + } + } + self.named.pax = Some((path, size.flatten())); + Ok(None) + } + // A global PAX header: what `git archive` writes, a comment. + // Yarn 1 gives a `path` in one to an entry that has a PAX + // header of its own, and npm gives every entry its `size`. + b'g' => { + let body = naming_body(entry)?; + let comment_only = body + .as_deref() + .and_then(pax_records) + .is_some_and(|records| records.iter().all(|(key, _)| *key == b"comment")); + Ok(if comment_only { None } else { self.any() }) + } + flag => self.entry(entry, flag), + } } - /// Count `entry`. `Some` is a patched file it makes unwritable: an + /// Count the entry `entry` under the name the headers before it give + /// it, or its own. `Some` is a patched file it makes unwritable (an /// entry that is not a directory where one of the file's parent - /// directories must be. - fn judge(&mut self, entry: &tar::Entry<'_, R>) -> std::io::Result> { - use tar::EntryType; - if matches!( - entry.header().entry_type(), - EntryType::XGlobalHeader - | EntryType::XHeader - | EntryType::GNULongName - | EntryType::GNULongLink - | EntryType::Directory - ) { + /// directories must be), or one it may be written onto when its name + /// cannot be told for every installer. + fn entry( + &mut self, + entry: &tar::Entry<'_, R>, + flag: u8, + ) -> std::io::Result> { + let named = std::mem::take(&mut self.named); + let (pax_path, pax_size) = named.pax.unwrap_or_default(); + // Read raw, the entry is as long as its own header says. A PAX + // size that says otherwise moves where a reader that applies it + // looks for the next header. + if pax_size.is_some_and(|size| entry.header().entry_size().ok() != Some(size)) { + return Ok(self.any()); + } + let name = match (named.long_name, pax_path) { + // npm takes the later of the two, Yarn 1 the PAX path. + (Some(_), Some(_)) => return Ok(self.any()), + (Some(name), None) | (None, Some(name)) => name, + (None, None) => entry.path_bytes().into_owned(), + }; + if flag == tar::EntryType::Directory.as_byte() { return Ok(None); } - let raw = entry.path()?.to_string_lossy().replace('\\', "/"); + let raw = String::from_utf8_lossy(&name).replace('\\', "/"); let folded = Self::fold(&raw); // What is left after the installer drops the first segment. let Some((_, installed)) = folded.split_once('/') else { return Ok(None); }; - if let Some(count) = self.0.get_mut(installed) { + if let Some(count) = self.counts.get_mut(installed) { *count += 1; return Ok(None); } Ok(self - .0 + .counts .keys() .find(|file| { file.strip_prefix(installed) @@ -400,7 +621,7 @@ impl Writers { /// The first patched file more than one entry is written onto. fn shadowed(self) -> Option { - self.0 + self.counts .into_iter() .filter(|(_, count)| *count > 1) .map(|(file, _)| file) @@ -421,14 +642,19 @@ fn shadowed_in_tar( // To the first zero block of the first gzip member: what the // decoder reads, so an entry that cannot be read fails the check. let mut tar = Archive::new(&mut *inflated); - for entry in tar.entries()? { - let entry = entry?; - count_entry(&mut entry_count, budget)?; - if let Some(file) = writers.judge(&entry)? { + for entry in tar.entries()?.raw(true) { + let mut entry = entry?; + count_header(&entry, &mut entry_count, budget)?; + if let Some(file) = writers.header(&mut entry, false)? { return Ok(Some(file)); } } } + // A name with no entry before the zero block: npm gives it to the + // entry after the block. + if writers.names_no_entry() { + return Ok(writers.any()); + } // Then what follows it, to the end of every gzip member. The tar reader // took the stream up to the end of that zero block, so the next reader // starts on a block boundary. @@ -438,16 +664,15 @@ fn shadowed_in_tar( let mut rest = Archive::new(&mut *inflated); rest.set_ignore_zeros(true); let mut ended = true; - for entry in rest.entries()? { + for entry in rest.entries()?.raw(true) { // A block that is no header: the reader took that block and // stops for good, so another one goes on from the next block. - let Ok(entry) = entry else { + let Ok(mut entry) = entry else { ended = false; break; }; - count_entry(&mut entry_count, budget)?; - // A name that cannot be read is no patched file's. - if let Ok(Some(file)) = writers.judge(&entry) { + count_header(&entry, &mut entry_count, budget)?; + if let Some(file) = writers.header(&mut entry, true)? { return Ok(Some(file)); } } @@ -633,6 +858,47 @@ fn members_of_tar( Ok(out) } +/// What is reserved for a member before any of its content is read. +const MEMBER_FIRST_RESERVE: usize = 128 * 1024; + +/// Up to `size` bytes of a member, from `entry`; fewer when the input ends +/// first, which the walk then finds at the next header. +/// +/// The size comes from the member's header, its author's claim, and is +/// within what is left of the archive's budget: up to 512 MiB, for an +/// archive of five megabytes. So the buffer is not reserved in one piece on +/// that claim. It starts at [`MEMBER_FIRST_RESERVE`] and doubles as the +/// content arrives, up to `size` and never past it, and a reservation the +/// machine cannot make is [`ArchiveError::TooLarge`], where +/// `Vec::with_capacity` aborts the process. +fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError> { + use crate::patch::archive_limits::no_memory_for; + let no_memory = || ArchiveError::TooLarge(no_memory_for(size)); + let wanted = usize::try_from(size).map_err(|_| no_memory())?; + let mut bytes: Vec = Vec::new(); + while bytes.len() < wanted { + let held = bytes.len(); + let more = (wanted - held).min(held.max(MEMBER_FIRST_RESERVE)); + bytes.try_reserve_exact(more).map_err(|_| no_memory())?; + bytes.resize(held + more, 0); + let mut filled = held; + while filled < bytes.len() { + match entry.read(&mut bytes[filled..]) { + Ok(0) => break, + Ok(n) => filled += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e.into()), + } + } + let ended = filled < bytes.len(); + bytes.truncate(filled); + if ended { + break; + } + } + Ok(bytes) +} + #[cfg(test)] mod tests { use super::*; @@ -858,47 +1124,6 @@ mod tests { /// Write a `.tar.gz` whose single regular-file entry carries `long_name` /// via a GNU `././@LongLink` (typeflag `L`) pseudo-entry. This is the only -/// What is reserved for a member before any of its content is read. -const MEMBER_FIRST_RESERVE: usize = 128 * 1024; - -/// Up to `size` bytes of a member, from `entry`; fewer when the input ends -/// first, which the walk then finds at the next header. -/// -/// The size comes from the member's header, its author's claim, and is -/// within what is left of the archive's budget: up to 512 MiB, for an -/// archive of five megabytes. So the buffer is not reserved in one piece on -/// that claim. It starts at [`MEMBER_FIRST_RESERVE`] and doubles as the -/// content arrives, up to `size` and never past it, and a reservation the -/// machine cannot make is [`ArchiveError::TooLarge`], where -/// `Vec::with_capacity` aborts the process. -fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError> { - use crate::patch::archive_limits::no_memory_for; - let no_memory = || ArchiveError::TooLarge(no_memory_for(size)); - let wanted = usize::try_from(size).map_err(|_| no_memory())?; - let mut bytes: Vec = Vec::new(); - while bytes.len() < wanted { - let held = bytes.len(); - let more = (wanted - held).min(held.max(MEMBER_FIRST_RESERVE)); - bytes.try_reserve_exact(more).map_err(|_| no_memory())?; - bytes.resize(held + more, 0); - let mut filled = held; - while filled < bytes.len() { - match entry.read(&mut bytes[filled..]) { - Ok(0) => break, - Ok(n) => filled += n, - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} - Err(e) => return Err(e.into()), - } - } - let ended = filled < bytes.len(); - bytes.truncate(filled); - if ended { - break; - } - } - Ok(bytes) -} - /// way to smuggle bytes a plain ustar name field can't hold — notably an /// embedded NUL (the ustar name field is NUL-terminated). fn write_gnu_longname_archive(path: &Path, long_name: &[u8], data: &[u8]) { @@ -1330,6 +1555,386 @@ fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError } } + /// `entry`, one raw entry, with a header that carries no ustar magic, + /// as a tar from before ustar wrote it. + fn without_magic(mut entry: Vec) -> Vec { + entry[257..265].fill(0); + entry[148..156].fill(b' '); + let sum: u32 = entry[..512].iter().map(|&b| b as u32).sum(); + entry[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + entry + } + + /// `entry`, one raw entry, with a header in the GNU format, which + /// spells the magic `ustar` and two spaces. + fn with_gnu_magic(mut entry: Vec) -> Vec { + entry[257..265].copy_from_slice(b"ustar \0"); + entry[148..156].fill(b' '); + let sum: u32 = entry[..512].iter().map(|&b| b as u32).sum(); + entry[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + entry + } + + /// PAX records, each ` =` and a newline. + fn pax(records: &[(&str, &str)]) -> Vec { + let mut out = Vec::new(); + for (key, value) in records { + let rest = format!(" {key}={value}\n"); + let mut len = rest.len() + 1; + while len.to_string().len() + rest.len() != len { + len = len.to_string().len() + rest.len(); + } + out.extend_from_slice(format!("{len}{rest}").as_bytes()); + } + out + } + + /// A header that names the entry after it (a GNU long name, a PAX + /// header) is read differently by this crate's tar reader and by the + /// installers once it is in any shape but the usual one. Each tarball + /// here holds the patched `package/index.js` and then an entry whose + /// own header says `package/harmless.js`, which npm 11.19.1 or Yarn + /// 1.22.19 (the one named) writes to `index.js`. + #[test] + fn a_second_entry_named_by_a_header_before_it_is_seen() { + const LONG: u8 = b'L'; + const PAX: u8 = b'x'; + let files = vec!["package/index.js".to_string()]; + let package = raw_tar(&[ + ("package/package.json", FILE, b"{}"), + ("package/index.js", FILE, b"patched"), + ]); + let harmless = raw_tar(&[("package/harmless.js", FILE, b"original")]); + let naming = |flag: u8, body: &[u8]| raw_tar(&[("././@LongLink", flag, body)]); + let long = b"package/index.js\0"; + let path = pax(&[("path", "package/index.js")]); + let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); + + let before_the_end: Vec<(&str, Vec)> = vec![ + ( + "npm, Yarn 1: a long name without the ustar magic", + without_magic(naming(LONG, long)), + ), + ( + "npm, Yarn 1: a PAX header without the ustar magic", + without_magic(naming(PAX, &path)), + ), + ("npm, Yarn 1: an old GNU long name", naming(b'N', long)), + ("npm: an old PAX header", naming(b'X', &path)), + ( + "npm, Yarn 1: a PAX header with two paths, the last one taken", + naming( + PAX, + &pax(&[("path", "package/fine.js"), ("path", "package/index.js")]), + ), + ), + ( + "npm: a PAX header with an empty line before its path", + naming(PAX, &[b"\n", &path[..]].concat()), + ), + ( + "Yarn 1: a PAX path and then a long name", + [naming(PAX, &path), naming(LONG, b"package/fine.js\0")].concat(), + ), + ( + "Yarn 1: a global PAX path and then a PAX header", + [naming(b'g', &path), naming(PAX, &pax(&[("mtime", "1")]))].concat(), + ), + ]; + // Every shape is tried before the test fails, so one run shows + // each that is missed. + let mut missed = Vec::new(); + for (label, named) in &before_the_end { + let tgz = gzip(&[&package[..], named, &harmless, &marker].concat()); + let shadowed = shadowed_member(&tgz, &files); + if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { + missed.push(format!("before the end: {label}: {shadowed:?}")); + } + } + + // After the first zero block, where a block that is no header is + // passed over: npm keeps the name it holds across such a block. + let after_a_zero_block: Vec<(&str, Vec)> = vec![ + ( + "npm: a long name, then a block that is no header", + [&naming(LONG, long)[..], &junk].concat(), + ), + ( + "npm, Yarn 1: two long names", + [naming(LONG, b"package/other.js\0"), naming(LONG, long)].concat(), + ), + ( + "npm: a PAX path, then a block that is no header", + [&naming(PAX, &path)[..], &junk].concat(), + ), + ]; + for (label, named) in &after_a_zero_block { + let tgz = gzip(&[&package[..], &zero, named, &harmless, &marker].concat()); + let shadowed = shadowed_member(&tgz, &files); + if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { + missed.push(format!("after a zero block: {label}: {shadowed:?}")); + } + } + + // Shapes no installer was tried on. Each is one the readers have + // cause to read differently, or that a header-by-header read + // cannot follow, so each is refused as well. + let big = [&long[..], &vec![0u8; 64 * 1024]].concat(); + let unusual: Vec<(&str, Vec)> = vec![ + // npm passes over one of more than 1 MiB; Yarn 1 applies it. + ("a long name of more than 64 KiB", naming(LONG, &big)), + ( + "a long name with bytes after its NUL", + naming(LONG, b"package/fine.js\0package/index.js\0"), + ), + ("an empty long name", naming(LONG, b"\0")), + ( + "a long link target without the ustar magic", + without_magic(naming(b'K', long)), + ), + ( + "two PAX headers", + [naming(PAX, &pax(&[("mtime", "1")])), naming(PAX, &path)].concat(), + ), + ( + "a PAX record longer than it says", + naming(PAX, b"20 path=package/index.js\n"), + ), + ( + "a PAX value of two lines", + naming(PAX, &pax(&[("comment", "x\n25 path=package/index.js")])), + ), + ( + // The entry after it is 8 bytes by its own header. + "a PAX size that is not the entry's", + naming(PAX, &pax(&[("size", "1024")])), + ), + ( + "a PAX header that names a sparse file", + naming(PAX, &pax(&[("GNU.sparse.name", "package/index.js")])), + ), + ( + "a global PAX header with more than a comment", + naming(b'g', &pax(&[("size", "1024")])), + ), + ( + "a sparse file", + raw_tar(&[("package/sparse.bin", b'S', b"")]), + ), + ]; + for (label, named) in &unusual { + let tgz = gzip(&[&package[..], named, &harmless, &marker].concat()); + let shadowed = shadowed_member(&tgz, &files); + if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { + missed.push(format!("unusual: {label}: {shadowed:?}")); + } + } + // A name with no entry before the zero block: npm gives it to the + // entry after the block. + let tgz = gzip(&[&package[..], &naming(LONG, long), &zero, &harmless, &marker].concat()); + let shadowed = shadowed_member(&tgz, &files); + if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { + missed.push(format!("a long name and then a zero block: {shadowed:?}")); + } + assert!(missed.is_empty(), "{}", missed.join("\n")); + } + + /// The headers that name an entry, as tar writers make them, are read: + /// a tarball with long paths verifies, a patched file with a long path + /// is counted once, and the decoder knows it by the same name. The + /// shapes are those of `npm pack`, bsdtar (`--format pax` and + /// `gnutar`), Python's `tarfile` and `git archive`. + #[test] + fn a_header_that_names_an_entry_in_its_usual_shape_is_read() { + const LONG: u8 = b'L'; + const PAX: u8 = b'x'; + const SYMLINK: u8 = b'2'; + let deep = format!( + "package/{}/{}.js", + vec!["d".repeat(40); 6].join("/"), + "b".repeat(120) + ); + let patched = deep.strip_prefix("package/").unwrap().to_string(); + let files = vec!["package/index.js".to_string(), deep.clone()]; + let naming = |flag: u8, body: &[u8]| raw_tar(&[("././@LongLink", flag, body)]); + let long_name = [deep.as_bytes(), b"\0"].concat(); + // Its own header holds what fits of the name. + let cut = raw_tar(&[(&deep[..99], FILE, b"deep")]); + let package = raw_tar(&[ + ("package/", DIR, b""), + ("package/package.json", FILE, b"{}"), + ("package/index.js", FILE, b"patched"), + ]); + let marker = [0u8; 1024]; + + let by_long_name = [naming(LONG, &long_name), cut.clone()].concat(); + let by_pax = [ + naming( + PAX, + &pax(&[ + ("path", &deep), + ("mtime", "1796142524.519055416"), + ("size", "4"), + ]), + ), + cut.clone(), + ] + .concat(); + let usual: Vec<(&str, Vec)> = vec![ + ("a GNU long name", by_long_name.clone()), + ( + "a GNU long name in a GNU header, as bsdtar and Python write", + [ + with_gnu_magic(naming(LONG, &long_name)), + with_gnu_magic(cut.clone()), + ] + .concat(), + ), + ("a PAX path, with the times and the size", by_pax.clone()), + ( + "a global PAX comment, as git archive writes", + [ + naming(b'g', &pax(&[("comment", &"d5".repeat(20))])), + by_pax.clone(), + ] + .concat(), + ), + ( + "a PAX header on every entry, as bsdtar writes", + [ + naming(PAX, &pax(&[("ctime", "1.5"), ("atime", "2.5")])), + raw_tar(&[("package/lib/", DIR, b"")]), + by_pax.clone(), + naming(PAX, &pax(&[("mtime", "3.5")])), + raw_tar(&[("package/lib/a.js", FILE, b"a")]), + ] + .concat(), + ), + ( + "a long link target and a long name before a link", + [ + by_long_name.clone(), + naming(b'K', b"index.js\0"), + naming(LONG, b"package/link.js\0"), + raw_tar(&[("package/link.js", SYMLINK, b"")]), + ] + .concat(), + ), + ]; + for (label, named) in &usual { + let tgz = gzip(&[&package[..], named, &marker].concat()); + assert_eq!(shadowed_member(&tgz, &files).unwrap(), None, "{label}"); + // The decoder gives the entry the same name. + assert_eq!( + read_archive_bytes_to_map(&tgz).unwrap()[&patched], + b"deep", + "{label}" + ); + // And it is that name the entry is counted under: another + // entry given it is a second one. + for second in [&by_long_name, &by_pax] { + let twice = gzip(&[&package[..], named, second, &marker].concat()); + assert_eq!( + shadowed_member(&twice, &files).unwrap(), + Some(patched.clone()), + "{label}" + ); + } + } + // A header that names another entry is none itself: 30 files, each + // behind a PAX header, are 30 entries to the limit, as they are to + // the decoder. + let thirty = ArchiveLimits { + max_entries: 30, + ..ArchiveLimits::IN_MEMORY + }; + let many: Vec = (0..30) + .flat_map(|i| { + let name = format!("package/f{i}.js"); + [ + naming(PAX, &pax(&[("path", &name), ("size", "1")])), + raw_tar(&[(&name, FILE, b"x")]), + ] + .concat() + }) + .collect(); + let tgz = gzip(&[&many[..], &marker].concat()); + let budget = thirty.budget(tgz.len() as u64); + assert_eq!(shadowed_member_within(&tgz, &files, &budget).unwrap(), None); + assert_eq!( + read_archive_from_reader(&tgz[..], &budget, false, true) + .unwrap() + .len(), + 30 + ); + } + + #[test] + fn pax_records_are_taken_only_in_the_shape_every_reader_reads_alike() { + let records = |body: &[u8]| { + pax_records(body).map(|records| { + records + .into_iter() + .map(|(key, value)| { + ( + String::from_utf8_lossy(key).into_owned(), + String::from_utf8_lossy(value).into_owned(), + ) + }) + .collect::>() + }) + }; + let pair = |key: &str, value: &str| (key.to_string(), value.to_string()); + assert_eq!(records(b""), Some(vec![])); + // The record is 25 bytes: its length, a space, the pair, a newline. + assert_eq!( + pax(&[("path", "package/index.js")]), + b"25 path=package/index.js\n" + ); + assert_eq!( + records(b"25 path=package/index.js\n11 size=27\n"), + Some(vec![pair("path", "package/index.js"), pair("size", "27")]) + ); + // A value may hold `=` and be empty. + assert_eq!( + records(b"11 a=b=c d\n5 k=\n"), + Some(vec![pair("a", "b=c d"), pair("k", "")]) + ); + for body in [ + // A length that is not the record's. + &b"24 path=package/index.js\n"[..], + b"26 path=package/index.js\n", + b"99 path=package/index.js\n", + // A length that is no plain number. + b"025 path=package/index.js\n", + b"+25 path=package/index.js\n", + b" 25 path=package/index.js\n", + b"path=package/index.js\n", + // No newline at its end, an empty line, a line inside a value. + b"25 path=package/index.js ", + b"\n25 path=package/index.js\n", + b"25 path=package/index.js\n\n", + b"38 comment=x\n25 path=package/index.js\n", + // No key. + b"7 =abc\n", + b"7 abcd\n", + // Bytes after the last record. + b"25 path=package/index.js\n\0", + ] { + assert_eq!(records(body), None, "{:?}", String::from_utf8_lossy(body)); + } + + assert_eq!(long_name(b"package/a.js\0"), Some(b"package/a.js".to_vec())); + assert_eq!(long_name(b"package/a.js"), Some(b"package/a.js".to_vec())); + assert_eq!( + long_name(b"package/a.js\0\0\0"), + Some(b"package/a.js".to_vec()) + ); + assert_eq!(long_name(b"package/a.js\0package/b.js\0"), None); + assert_eq!(long_name(b"\0"), None); + assert_eq!(long_name(b""), None); + } + /// The installers read a tarball further than the decoder, which ends /// at the first zero block of the first gzip member (the table on /// [`shadowed_member`]). A second entry for a patched file anywhere in @@ -1513,6 +2118,54 @@ fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError ); } + /// A limit that only the check for a second entry meets, in the part of + /// a tarball the decoder does not read, is named like any other: here a + /// second gzip member of 80 MiB of zeros after a whole package. + #[test] + fn a_limit_met_past_the_first_gzip_member_is_named() { + let files = vec!["package/index.js".to_string()]; + let package = raw_tar_gz(&[ + ("package/package.json", FILE, b"{}"), + ("package/index.js", FILE, b"patched"), + ]); + let tgz = [package, gzip(&vec![0u8; 80 * MIB])].concat(); + assert!(tgz.len() < 128 * 1024, "{}", tgz.len()); + + // The decoder ends at the first member, within every limit. + assert_eq!(read_archive_bytes_to_map(&tgz).unwrap().len(), 2); + let why = too_large(shadowed_member(&tgz, &files)); + assert!( + why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size (") + && why.ends_with(" KiB) and the 64 MiB every archive may use"), + "{why}" + ); + assert_eq!(limit_exceeded(&tgz), Some(why)); + } + + /// The size in a member's header is its author's claim. Before any of + /// the content is read it reserves 128 KiB at most, however much the + /// archive's budget would allow it, and the buffer then grows with what + /// arrives, up to the declared size and never past it. + #[test] + fn a_members_declared_size_alone_reserves_little() { + // 400 MiB claimed, ten bytes there. + let bytes = read_member(&mut &b"ten bytes!"[..], 400 * MIB as u64).unwrap(); + assert_eq!(bytes, b"ten bytes!"); + assert!( + bytes.capacity() <= 128 * 1024, + "{} bytes reserved for ten", + bytes.capacity() + ); + + let content = noise(3 * MIB + 17); + let bytes = read_member(&mut &content[..], content.len() as u64).unwrap(); + assert_eq!(bytes, content); + assert_eq!(bytes.capacity(), content.len()); + // No more than the declared size is taken from a longer input. + let bytes = read_member(&mut &content[..], 1000).unwrap(); + assert_eq!(bytes, content[..1000]); + } + #[test] fn test_read_archive_rejects_too_many_entries() { // One more entry than the limit. Each entry is empty so the @@ -1592,51 +2245,3 @@ fn read_member(entry: &mut impl Read, size: u64) -> Result, ArchiveError ); } } - /// A limit that only the check for a second entry meets, in the part of - /// a tarball the decoder does not read, is named like any other: here a - /// second gzip member of 80 MiB of zeros after a whole package. - #[test] - fn a_limit_met_past_the_first_gzip_member_is_named() { - let files = vec!["package/index.js".to_string()]; - let package = raw_tar_gz(&[ - ("package/package.json", FILE, b"{}"), - ("package/index.js", FILE, b"patched"), - ]); - let tgz = [package, gzip(&vec![0u8; 80 * MIB])].concat(); - assert!(tgz.len() < 128 * 1024, "{}", tgz.len()); - - // The decoder ends at the first member, within every limit. - assert_eq!(read_archive_bytes_to_map(&tgz).unwrap().len(), 2); - let why = too_large(shadowed_member(&tgz, &files)); - assert!( - why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size (") - && why.ends_with(" KiB) and the 64 MiB every archive may use"), - "{why}" - ); - assert_eq!(limit_exceeded(&tgz), Some(why)); - } - - /// The size in a member's header is its author's claim. Before any of - /// the content is read it reserves 128 KiB at most, however much the - /// archive's budget would allow it, and the buffer then grows with what - /// arrives, up to the declared size and never past it. - #[test] - fn a_members_declared_size_alone_reserves_little() { - // 400 MiB claimed, ten bytes there. - let bytes = read_member(&mut &b"ten bytes!"[..], 400 * MIB as u64).unwrap(); - assert_eq!(bytes, b"ten bytes!"); - assert!( - bytes.capacity() <= 128 * 1024, - "{} bytes reserved for ten", - bytes.capacity() - ); - - let content = noise(3 * MIB + 17); - let bytes = read_member(&mut &content[..], content.len() as u64).unwrap(); - assert_eq!(bytes, content); - assert_eq!(bytes.capacity(), content.len()); - // No more than the declared size is taken from a longer input. - let bytes = read_member(&mut &content[..], 1000).unwrap(); - assert_eq!(bytes, content[..1000]); - } - diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 763b5a2ae2..fc170724f5 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -1281,8 +1281,8 @@ pub async fn describe_artifact_failure( "vendor_artifact_unreadable" => "cannot be read", "vendor_artifact_non_canonical" => { "holds a second entry the package manager would extract over a patched \ - file (another top-level directory, a second spelling of the name, or a \ - link)" + file (another top-level directory, a second spelling of the name, a \ + link, or a name given by a header before the entry)" } "vendor_inventory_mismatch" => "has files that differ from its recorded inventory", _ => "failed verification", From 55b009a2036380980b53b18d84fd36ef0eaab640 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:47:27 -0500 Subject: [PATCH 08/13] Take the second-entry check work out of this change This change is the size limits. Two commits on it also widened the check for a second entry over a patched file: one walked a tarball past its first zero block and its first gzip member, the next read the headers that name an entry in one shape only. That work is not ready (it refuses a tarball the patch service serves and `main` verifies) and moves to a change of its own. The remaining part of #2330 is tracked there. After this commit the check for a second entry, what `vendor --check`, `vex`, `repair`, the reuse of a committed tarball and a re-download take for a shadowing entry or a non-canonical tarball, and what the decoder reads into the member map are as on `main`, with one exception: a size or count limit that is met is an error that names the limit, where `main` read up to the limit and took the end of its input for the end of the archive. So the check ends at the first zero block of the first gzip member again, as the decoder does. What stays is the limits work: the shared limits and the reader that fails on the first byte past them, the limit errors and `vendor_artifact_too_large`, the registry extractor that fails where it extracted short, a member's buffer that grows as its content arrives (now in a form that compiles: it had landed inside the test module), and the too-large verdict for an artifact larger on disk than is read. Removed with the walks: their unit and CLI tests, the helpers on the bounded reader they alone used, and their wording in the `vex` omission and the check's message. The contract row for `vendor_artifact_non_canonical` is `main`'s text again. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- crates/socket-patch-cli/src/commands/vex.rs | 3 +- .../tests/vendor/vendor_failure_paths.rs | 198 --- .../src/patch/archive_limits.rs | 10 - crates/socket-patch-core/src/patch/package.rs | 1062 ++--------------- crates/socket-patch-core/src/vendor/verify.rs | 45 +- 6 files changed, 85 insertions(+), 1237 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 09351f454e..2f6154d168 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1664,7 +1664,7 @@ Coverage includes npm (all lock flavors), Python wheels and source distributions **Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 512 MiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 512 MiB plus the archive itself is what checking one archive may take. -An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. That check reads the whole gzip stream, every member of it, so for it the limits count the padding and whatever else follows the end-of-archive marker. +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. Two wheels within that download size unpack to more than 512 MiB and are refused: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB). Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). @@ -2545,7 +2545,7 @@ command's integration tests check its output. | `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. | | `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. | | `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. | -| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). The second entry is looked for as far as any installer reads, which is further than the tarball's first all-zero block and first gzip member: npm takes an entry that follows a single zero block (passing over a block that is no tar header on the way) or that sits in a further gzip member while it has seen no end-of-archive marker, and Yarn 1 takes one after the marker and in a further gzip member as well. Zero padding and other bytes after the marker that hold no entry change nothing. An entry is counted under the name a header before it gives it (a GNU long name, a PAX `path`), and such a header is taken only in the one shape every installer reads alike: it carries the ustar or GNU magic and comes before the tarball's first all-zero block; a long name ends at its first NUL; a PAX header is ` =` lines and nothing else, each as long as it says, with one `path` at most and a `size` that is the entry's own; no entry has both; neither is larger than 64 KiB; a global PAX header holds a comment only. Any other shape is read differently by npm, by Yarn 1 or by this check's own tar reader (an old-style long name or PAX header, one without the magic, two `path` records, an empty line before the `path`, a long name and a PAX `path` for one entry, a name held across a block that is no header), so the entry after it may be written onto any file: the tarball is `vendor_artifact_non_canonical` whichever file that entry would be. Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | +| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large`: the committed artifact is past the limits it is read within (an npm tarball, a Python wheel or source distribution, a `.nupkg`: see "Archive limits" under the [Vendor command contract](#vendor-command-contract); a jar: see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact, naming the limit, that `repair` restores from the recorded artifact). A limit that is met is always this tag, never an artifact read up to the limit: a tarball is read to its end-of-archive marker or not vouched for. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | | `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. The `no_matching_variant` reason says that `apply` leaves such a copy as it is, and for a gem names `bundle pristine ` and the `apply` to run after it. | | `no_matching_variant` | `failed` | apply, and the apply that `get` / `scan --mode agent` run (gem, PyPI): an installed copy of a release-variant base (a base whose manifest records are qualified, or a gem build beside another build of its version) whose files match none of the manifest's records for it and which holds one of the patch's files with other content: an edited copy, or another build of the version. (A copy that holds none of the files its records are matched by is not told to belong to them: they stay `package_not_installed`, and the run still exits 1.) Keyed by the base purl, one event per copy. The copy is left as it is and the run exits 1 (`partialFailure`). `error` names the copy and the file that holds neither side of a record; for a gem it adds `bundle pristine ` (or `gem pristine `), which restores an edited copy to the published gem. The copy is installed, so no record of the base is `package_not_installed` in that run. | | `redirect_unconfirmed` | `skipped` (`details.mode: "hosted"`) | hosted `scan` / `get` (v5.0, additive): the patch was granted but no lockfile entry pinning it could be rewritten. The status and exit code are unchanged for now, pending the open hosted exit-policy decision (#704); `--silent` hides the human line. | diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index d0b63192b4..3ab192df07 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2809,8 +2809,7 @@ fn omission_phrase(reason: &str) -> &'static str { "vendor_artifact_non_canonical" => { "the vendored tarball holds a second entry the package manager would extract \ over a patched file (another top-level directory, a second spelling of the \ - name, a link, or a name given by a header before the entry), so what installs \ - is not what was checked" + name, or a link), so what installs is not what was checked" } "vendor_lock_pin_mismatch" => { "the lockfile pins the vendored tarball to a sha512 that is not that file's, so \ diff --git a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs index dcae5ff12f..936a04ae4d 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_failure_paths.rs @@ -1701,201 +1701,3 @@ fn check_sees_a_second_entry_where_the_old_limit_fell() { "{env:#}" ); } - -/// #2330: the installers read a tarball further than its first zero block -/// and its first gzip member, where the check for a second entry stopped. -/// npm 11 takes a `package/index.js` that follows a single zero block, or -/// that sits in a second gzip member when the first has no end-of-archive -/// marker; Yarn 1 takes one after the marker too. Each is -/// `vendor_artifact_non_canonical`; zero padding after the marker, which -/// packers write, checks clean. -#[test] -fn check_sees_a_second_entry_past_the_first_zero_block_and_gzip_member() { - let fx = npm_fixture(); - let (code, env) = vendor_cli(fx.root(), &[]); - assert_eq!(code, 0, "{env:#}"); - - // The members as a tar stream without its end-of-archive marker. - let tar_of = |members: &[(&str, &[u8])]| -> Vec { - let mut builder = tar::Builder::new(Vec::new()); - for (name, bytes) in members { - let mut header = tar::Header::new_gnu(); - header.set_size(bytes.len() as u64); - header.set_mode(0o644); - header.set_mtime(0); - header.set_cksum(); - builder.append_data(&mut header, name, *bytes).unwrap(); - } - let mut tar = builder.into_inner().unwrap(); - tar.truncate(tar.len() - 1024); - tar - }; - let gzip = |bytes: &[u8]| -> Vec { - use std::io::Write as _; - let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - gz.write_all(bytes).unwrap(); - gz.finish().unwrap() - }; - let package = tar_of(&[ - ( - "package/package.json", - br#"{"name":"left-pad","version":"1.3.0"}"#, - ), - ("package/index.js", PATCHED_INDEX), - ]); - let second = tar_of(&[("package/index.js", ORIG_INDEX)]); - let (zero, marker) = ([0u8; 512], [0u8; 1024]); - - replace_committed_tarball( - &fx, - &gzip(&[&package[..], &vec![0u8; 10240 - package.len()]].concat()), - ); - let (code, env) = vendor_cli(fx.root(), &["--check"]); - assert_eq!(code, 0, "zero padding to a 10 KiB record: {env:#}"); - - for (label, tgz) in [ - ( - "after one zero block", - gzip(&[&package[..], &zero, &second, &marker].concat()), - ), - ( - "after the marker", - gzip(&[&package[..], &marker, &second, &marker].concat()), - ), - ( - "in a second gzip member", - [ - gzip(&[&package[..], &marker].concat()), - gzip(&[&second[..], &marker].concat()), - ] - .concat(), - ), - ] { - replace_committed_tarball(&fx, &tgz); - let (code, env) = vendor_cli(fx.root(), &["--check"]); - assert_eq!(code, 1, "{label}: {env:#}"); - let failed = find_event(&env, "failed", Some("vendor_check_failed")); - assert!( - failed["reason"] - .as_str() - .is_some_and(|m| m.contains("(vendor_artifact_non_canonical)")), - "{label}: {env:#}" - ); - } -} - -/// A second entry can be given a patched file's name by a header before it -/// (a GNU long name, a PAX header) while its own header names another -/// file. The installers and this crate's tar reader read such a header -/// alike only in its usual shape: in each tarball here npm 11 writes the -/// original bytes to `index.js`, and the check read the entry as -/// `harmless.js` and verified. Each is `vendor_artifact_non_canonical`; -/// a long path named the usual way checks clean. -#[test] -fn check_sees_a_second_entry_named_by_a_header_before_it() { - let fx = npm_fixture(); - let (code, env) = vendor_cli(fx.root(), &[]); - assert_eq!(code, 0, "{env:#}"); - - // One raw tar entry: a header of type `flag`, with the ustar magic or - // without it, then the content padded to a block. - let entry = |name: &str, flag: u8, magic: bool, content: &[u8]| -> Vec { - let mut header = if magic { - tar::Header::new_ustar() - } else { - tar::Header::new_old() - }; - header.as_old_mut().name[..name.len()].copy_from_slice(name.as_bytes()); - header.set_size(content.len() as u64); - header.set_mode(0o644); - header.set_entry_type(tar::EntryType::new(flag)); - header.set_cksum(); - let mut out = header.as_bytes().to_vec(); - out.extend_from_slice(content); - out.resize(out.len() + (512 - content.len() % 512) % 512, 0); - out - }; - let gzip = |bytes: &[u8]| -> Vec { - use std::io::Write as _; - let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - gz.write_all(bytes).unwrap(); - gz.finish().unwrap() - }; - // PAX records, each ` =` and a newline. - let pax = |records: &[(&str, &str)]| -> Vec { - let mut out = Vec::new(); - for (key, value) in records { - let rest = format!(" {key}={value}\n"); - let mut len = rest.len() + 1; - while len.to_string().len() + rest.len() != len { - len = len.to_string().len() + rest.len(); - } - out.extend_from_slice(format!("{len}{rest}").as_bytes()); - } - out - }; - let package = [ - entry( - "package/package.json", - b'0', - true, - br#"{"name":"left-pad","version":"1.3.0"}"#, - ), - entry("package/index.js", b'0', true, PATCHED_INDEX), - ] - .concat(); - let harmless = entry("package/harmless.js", b'0', true, ORIG_INDEX); - let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); - let long = b"package/index.js\0"; - - let deep = format!("package/{}/{}.js", "d".repeat(90), "b".repeat(120)); - let usual = [ - &package[..], - &entry( - "PaxHeader/deep", - b'x', - true, - &pax(&[("path", &deep), ("size", "5")]), - ), - &entry(&deep[..99], b'0', true, b"deep\n"), - &marker, - ] - .concat(); - replace_committed_tarball(&fx, &gzip(&usual)); - let (code, env) = vendor_cli(fx.root(), &["--check"]); - assert_eq!(code, 0, "a long path behind a PAX header: {env:#}"); - - for (label, named) in [ - ( - "a long name without the ustar magic", - entry("././@LongLink", b'L', false, long), - ), - ( - "a PAX header with two paths", - entry( - "PaxHeader/x", - b'x', - true, - &pax(&[("path", "package/fine.js"), ("path", "package/index.js")]), - ), - ), - ( - "after a zero block, a long name and a block that is no header", - [&zero[..], &entry("././@LongLink", b'L', true, long), &junk].concat(), - ), - ] { - replace_committed_tarball( - &fx, - &gzip(&[&package[..], &named, &harmless, &marker].concat()), - ); - let (code, env) = vendor_cli(fx.root(), &["--check"]); - assert_eq!(code, 1, "{label}: {env:#}"); - let failed = find_event(&env, "failed", Some("vendor_check_failed")); - assert!( - failed["reason"] - .as_str() - .is_some_and(|m| m.contains("(vendor_artifact_non_canonical)")), - "{label}: {env:#}" - ); - } -} diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index 732edbbf6a..1f1436295f 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -255,16 +255,6 @@ impl Bounded { pub(crate) fn over(&self) -> bool { self.over } - - /// The reader the budget is counted on. - pub(crate) fn inner_mut(&mut self) -> &mut R { - &mut self.inner - } - - /// How many bytes of the input were read so far. - pub(crate) fn taken(&self) -> u64 { - self.read - } } impl Read for Bounded { diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index c80c4e14c3..c3dde7e84a 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -135,15 +135,10 @@ fn budget_of(bytes: &[u8]) -> Budget { /// [`ArchiveError::TooLarge`]; `None` when it is within them all. For the /// message of a caller that holds only a reader's routing tag. pub(crate) fn limit_exceeded(bytes: &[u8]) -> Option { - let limit = |read: Option| match read { - Some(ArchiveError::TooLarge(why)) => Some(why), + match read_archive_from_reader(bytes, &budget_of(bytes), false, false) { + Err(ArchiveError::TooLarge(why)) => Some(why), _ => None, - }; - // The decoder first: a member's header says how much the tarball - // unpacks to. Then the check for a second entry, which reads on where - // the decoder ends and can meet a limit there that the decoder does not. - limit(read_archive_from_reader(bytes, &budget_of(bytes), false, false).err()) - .or_else(|| limit(shadowed_member(bytes, &[]).err())) + } } /// [`read_archive_bytes_to_map`] that additionally refuses any archive an @@ -228,55 +223,9 @@ pub(crate) fn read_archive_bytes_to_map_any_root( /// files: an upstream tarball with a link, a non-ASCII name or a case twin /// somewhere else still passes. /// -/// # How far it reads -/// -/// The decoder ends a tarball at the first all-zero block of its first gzip -/// member. The installers read further, each to a different point (npm -/// 11.19.1 and Yarn 1.22.19, each given a tarball as a `file:` dependency): -/// -/// | A second entry for a patched file | npm installs | Yarn 1 installs | -/// |---|---|---| -/// | after one zero block | the second | the second | -/// | after one zero block and a block that is no header | the second | nothing (it fails) | -/// | in a second gzip member, the first without a marker | the second | the second | -/// | after the marker (two zero blocks) | the first | the second | -/// | in a second gzip member, after the marker | the first | the second | -/// -/// So every entry up to that first zero block is judged or the call fails, -/// as the decoder would, and then every entry after it is judged too: past -/// zero blocks and past blocks that are no tar header (npm passes over one -/// with a warning), to the end of the gzip member, and through each gzip -/// member that follows. Nothing in that part fails the check for being -/// unreadable, since padding and trailing bytes are no entries: only an -/// entry there that lands on a patched file does, or a limit. A tarball -/// past a limit is [`ArchiveError::TooLarge`] wherever the limit is met, -/// never one whose entries beyond the limit went unseen. -/// -/// # What an entry is called -/// -/// An entry's name can come from a header before it: a GNU long name (type -/// `L`) or a PAX header (`x`). The readers agree on that name only while -/// the header is in its usual shape. Away from it each goes its own way -/// (installed as above; "the second" is an entry whose own header names -/// another file): -/// -/// | The header before the second entry | npm installs | Yarn 1 installs | -/// |---|---|---| -/// | `L` or `x` without the ustar or GNU magic (this crate's reader applies neither) | the second | the second | -/// | an old GNU long name (`N`) | the second | the second | -/// | an old PAX header (`X`) | the second | nothing (it fails) | -/// | `x` with two `path` records (this crate's reader takes the first) | the second | the second | -/// | `x` with an empty line before its `path` (this crate's reader stops there) | the second | the first | -/// | `x` with a `path`, then `L` with another name | the first | the second | -/// | a global PAX header (`g`) with a `path`, then any `x` | the first | the second | -/// | `L` of more than 1 MiB | the first | the second | -/// | after a zero block: `L` or `x`, then a block that is no header | the second | nothing (it fails) | -/// -/// So the stream is walked header by header, and a header that names -/// another entry is taken only in the one shape every reader reads alike -/// ([`Writers::header`]). Any other shape counts as a second entry for a -/// patched file, whichever file the entry after it would have been: which -/// one it is depends on the installer. +/// Every entry up to the tar end-of-archive marker is judged or the call +/// fails: a tarball past a limit is [`ArchiveError::TooLarge`], never one +/// whose entries beyond the limit went unseen. pub(crate) fn shadowed_member( bytes: &[u8], files: &[String], @@ -290,51 +239,11 @@ fn shadowed_member_within( files: &[String], budget: &Budget, ) -> Result, ArchiveError> { - let mut inflated = Bounded::new(GzMembers::first_of(bytes), budget); + let mut inflated = Bounded::new(GzDecoder::new(bytes), budget); let shadowed = shadowed_in_tar(&mut inflated, files, budget); within_budget(shadowed, &inflated, budget) } -/// The gzip members of a tarball as one stream: the first alone, as the -/// decoder reads a tarball, until [`Self::follow_the_rest`], then each -/// member that follows it. Bytes after a member that do not start another -/// one end the stream, as they do for a gunzip. -struct GzMembers<'a> { - member: flate2::bufread::GzDecoder<&'a [u8]>, - follow: bool, -} - -impl<'a> GzMembers<'a> { - fn first_of(bytes: &'a [u8]) -> Self { - GzMembers { - member: flate2::bufread::GzDecoder::new(bytes), - follow: false, - } - } - - fn follow_the_rest(&mut self) { - self.follow = true; - } -} - -impl Read for GzMembers<'_> { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - loop { - let n = self.member.read(buf)?; - if n > 0 || buf.is_empty() || !self.follow { - return Ok(n); - } - // The member has ended: the decoder took its input up to the - // end of the member's trailer and no further. - let rest: &[u8] = self.member.get_ref(); - if !rest.starts_with(&[0x1f, 0x8b]) { - return Ok(0); - } - self.member = flate2::bufread::GzDecoder::new(rest); - } - } -} - /// The outcome of a walk over `inflated`, unless the walk met the budget: /// that is the error, whatever the tar parser made of the failed read. fn within_budget( @@ -359,106 +268,18 @@ fn count_entry(entry_count: &mut usize, budget: &Budget) -> Result<(), ArchiveEr Ok(()) } -/// The largest body of a header that names another entry that is read. A -/// real one is a path or a few records. npm passes over one larger than a -/// megabyte where the other readers apply it, so one past this is no shape -/// every reader reads alike. -const MAX_NAMING_BYTES: u64 = 64 * 1024; - -/// Whether a header of type `flag` names another entry instead of being -/// one: a GNU long name or long link (`L`, `K`; `N`, the old long name), a -/// PAX header (`x`; `X`, the old one), a global PAX header (`g`). -fn names_another(flag: u8) -> bool { - matches!(flag, b'L' | b'N' | b'K' | b'x' | b'X' | b'g') -} - -/// The body of a header that names another entry; `None` past -/// [`MAX_NAMING_BYTES`]. -fn naming_body(entry: &mut tar::Entry<'_, R>) -> std::io::Result>> { - let size = entry.size(); - if size > MAX_NAMING_BYTES { - return Ok(None); - } - let mut body = Vec::with_capacity(size as usize); - entry.read_to_end(&mut body)?; - if body.len() as u64 != size { - return Err(std::io::ErrorKind::UnexpectedEof.into()); - } - Ok(Some(body)) -} - -/// The name the body of a GNU long name gives, when every reader takes the -/// same one from it: the bytes up to the first NUL, and nothing but NULs -/// after them. -fn long_name(body: &[u8]) -> Option> { - let end = body.iter().position(|b| *b == 0).unwrap_or(body.len()); - (end > 0 && body[end..].iter().all(|b| *b == 0)).then(|| body[..end].to_vec()) -} - -/// The records of the body of a PAX header, as `(key, value)`, when every -/// reader takes the same ones from it: the body is ` =` -/// lines and nothing else, each as long as it says and one line long. A -/// reader that splits the body at newlines (npm, this crate's) and one that -/// goes by the lengths (Yarn 1) then see the same records. -fn pax_records(mut body: &[u8]) -> Option> { - let mut records = Vec::new(); - while !body.is_empty() { - let space = body.iter().position(|b| *b == b' ')?; - let digits = &body[..space]; - if digits.first().is_none_or(|first| *first == b'0') - || !digits.iter().all(u8::is_ascii_digit) - { - return None; - } - let length: usize = std::str::from_utf8(digits).ok()?.parse().ok()?; - if length > body.len() { - return None; - } - let (record, rest) = body.split_at(length); - let pair = record.strip_suffix(b"\n")?.get(space + 1..)?; - let equals = pair.iter().position(|b| *b == b'=')?; - if equals == 0 || pair.contains(&b'\n') { - return None; - } - records.push((&pair[..equals], &pair[equals + 1..])); - body = rest; - } - Some(records) -} - -/// What the headers since the last entry say of the next one. -#[derive(Default)] -struct Named { - /// The name a GNU long name gives it. - long_name: Option>, - /// The `path` and the `size` a PAX header gives it. - pax: Option<(Option>, Option)>, -} - -/// Count the header `entry` of a raw read against the entry limit, as the -/// decoder counts: a header that names another entry is none to it. -fn count_header( - entry: &tar::Entry<'_, R>, - entry_count: &mut usize, +/// [`shadowed_member`] over the tar stream `inflated`. +fn shadowed_in_tar( + inflated: R, + files: &[String], budget: &Budget, -) -> Result<(), ArchiveError> { - if names_another(entry.header().entry_type().as_byte()) { - return Ok(()); - } - count_entry(entry_count, budget) -} - -/// How many entries an installer writes onto each patched file. -struct Writers { - counts: HashMap, - named: Named, -} +) -> Result, ArchiveError> { + use tar::EntryType; -impl Writers { // Extractors normalize `..` as well as `.` and empty segments, so // `package/x/../index.js` lands on `index.js`. A `..` above the start // is dropped: what it would reach is outside the package either way. - fn fold(path: &str) -> String { + let fold = |path: &str| -> String { let mut segments: Vec = Vec::new(); for segment in path.split('/') { match segment { @@ -470,219 +291,47 @@ impl Writers { } } segments.join("/") - } - - fn of(files: &[String]) -> Self { - Writers { - counts: files - .iter() - .map(|file| (Self::fold(normalize_file_path(file)), 0)) - .collect(), - named: Named::default(), - } - } - - /// The patched file to answer with when an entry's name cannot be told - /// for every installer: the entry may be written onto any of them. - fn any(&self) -> Option { - self.counts.keys().min().cloned() - } - - /// Whether a header named an entry and none has followed it. - fn names_no_entry(&self) -> bool { - self.named.long_name.is_some() || self.named.pax.is_some() - } - - /// Take the next header of the tar stream, read raw: the headers that - /// name another entry come as they are written, and are held here to - /// the one shape every reader reads alike (the table on - /// [`shadowed_member`]). `tail` is the part past the first zero block, - /// where a block that is no header is passed over and a reader may - /// carry a name across it: no such header is taken there. `Some` is a - /// patched file an installer may write from another entry. - fn header( - &mut self, - entry: &mut tar::Entry<'_, R>, - tail: bool, - ) -> std::io::Result> { - let header = entry.header(); - let flag = header.entry_type().as_byte(); - // What this crate's reader asks of a header before it applies it - // as a long name or a PAX header. The installers ask for less. - let magic = header.as_ustar().is_some() || header.as_gnu().is_some(); - match flag { - flag if tail && names_another(flag) => Ok(self.any()), - // The old long name and the old PAX header, which this crate's - // reader never applies, and a sparse file, whose map a raw read - // does not follow. - b'N' | b'X' | b'S' => Ok(self.any()), - b'L' | b'K' | b'x' if !magic => Ok(self.any()), - // A long link target: the entry after it is a link, counted - // under its own name. - b'K' => Ok(None), - b'L' => { - let name = naming_body(entry)?.as_deref().and_then(long_name); - match name { - Some(name) if self.named.long_name.is_none() => { - self.named.long_name = Some(name); - Ok(None) - } - _ => Ok(self.any()), - } - } - b'x' => { - let body = naming_body(entry)?; - let records = body.as_deref().and_then(pax_records); - let (Some(records), None) = (records, &self.named.pax) else { - return Ok(self.any()); - }; - let (mut path, mut size) = (None, None); - for (key, value) in records { - let usual = match key { - b"path" => !value.is_empty() && path.replace(value.to_vec()).is_none(), - b"size" => { - let digits = value.iter().all(u8::is_ascii_digit); - let bytes = - std::str::from_utf8(value).ok().and_then(|v| v.parse().ok()); - digits && bytes.is_some() && size.replace(bytes).is_none() - } - // The name of a sparse file, for a reader that - // unpacks one. - key => !key.starts_with(b"GNU.sparse."), - }; - if !usual { - return Ok(self.any()); - } - } - self.named.pax = Some((path, size.flatten())); - Ok(None) - } - // A global PAX header: what `git archive` writes, a comment. - // Yarn 1 gives a `path` in one to an entry that has a PAX - // header of its own, and npm gives every entry its `size`. - b'g' => { - let body = naming_body(entry)?; - let comment_only = body - .as_deref() - .and_then(pax_records) - .is_some_and(|records| records.iter().all(|(key, _)| *key == b"comment")); - Ok(if comment_only { None } else { self.any() }) - } - flag => self.entry(entry, flag), - } - } - - /// Count the entry `entry` under the name the headers before it give - /// it, or its own. `Some` is a patched file it makes unwritable (an - /// entry that is not a directory where one of the file's parent - /// directories must be), or one it may be written onto when its name - /// cannot be told for every installer. - fn entry( - &mut self, - entry: &tar::Entry<'_, R>, - flag: u8, - ) -> std::io::Result> { - let named = std::mem::take(&mut self.named); - let (pax_path, pax_size) = named.pax.unwrap_or_default(); - // Read raw, the entry is as long as its own header says. A PAX - // size that says otherwise moves where a reader that applies it - // looks for the next header. - if pax_size.is_some_and(|size| entry.header().entry_size().ok() != Some(size)) { - return Ok(self.any()); - } - let name = match (named.long_name, pax_path) { - // npm takes the later of the two, Yarn 1 the PAX path. - (Some(_), Some(_)) => return Ok(self.any()), - (Some(name), None) | (None, Some(name)) => name, - (None, None) => entry.path_bytes().into_owned(), - }; - if flag == tar::EntryType::Directory.as_byte() { - return Ok(None); + }; + let mut writers: HashMap = files + .iter() + .map(|file| (fold(normalize_file_path(file)), 0)) + .collect(); + let mut tar = Archive::new(inflated); + let mut entry_count: usize = 0; + for entry in tar.entries()? { + let entry = entry?; + count_entry(&mut entry_count, budget)?; + let entry_type = entry.header().entry_type(); + if matches!( + entry_type, + EntryType::XGlobalHeader + | EntryType::XHeader + | EntryType::GNULongName + | EntryType::GNULongLink + | EntryType::Directory + ) { + continue; } - let raw = String::from_utf8_lossy(&name).replace('\\', "/"); - let folded = Self::fold(&raw); + let raw = entry.path()?.to_string_lossy().replace('\\', "/"); + let folded = fold(&raw); // What is left after the installer drops the first segment. let Some((_, installed)) = folded.split_once('/') else { - return Ok(None); + continue; }; - if let Some(count) = self.counts.get_mut(installed) { + if let Some(count) = writers.get_mut(installed) { *count += 1; - return Ok(None); + } else if let Some(file) = writers.keys().find(|file| { + file.strip_prefix(installed) + .is_some_and(|rest| rest.starts_with('/')) + }) { + return Ok(Some(file.clone())); } - Ok(self - .counts - .keys() - .find(|file| { - file.strip_prefix(installed) - .is_some_and(|rest| rest.starts_with('/')) - }) - .cloned()) - } - - /// The first patched file more than one entry is written onto. - fn shadowed(self) -> Option { - self.counts - .into_iter() - .filter(|(_, count)| *count > 1) - .map(|(file, _)| file) - .min() } -} - -/// [`shadowed_member`] over the tar stream `inflated` (see there for how -/// far it reads). -fn shadowed_in_tar( - inflated: &mut Bounded>, - files: &[String], - budget: &Budget, -) -> Result, ArchiveError> { - let mut writers = Writers::of(files); - let mut entry_count: usize = 0; - { - // To the first zero block of the first gzip member: what the - // decoder reads, so an entry that cannot be read fails the check. - let mut tar = Archive::new(&mut *inflated); - for entry in tar.entries()?.raw(true) { - let mut entry = entry?; - count_header(&entry, &mut entry_count, budget)?; - if let Some(file) = writers.header(&mut entry, false)? { - return Ok(Some(file)); - } - } - } - // A name with no entry before the zero block: npm gives it to the - // entry after the block. - if writers.names_no_entry() { - return Ok(writers.any()); - } - // Then what follows it, to the end of every gzip member. The tar reader - // took the stream up to the end of that zero block, so the next reader - // starts on a block boundary. - inflated.inner_mut().follow_the_rest(); - loop { - let before = inflated.taken(); - let mut rest = Archive::new(&mut *inflated); - rest.set_ignore_zeros(true); - let mut ended = true; - for entry in rest.entries()?.raw(true) { - // A block that is no header: the reader took that block and - // stops for good, so another one goes on from the next block. - let Ok(mut entry) = entry else { - ended = false; - break; - }; - count_header(&entry, &mut entry_count, budget)?; - if let Some(file) = writers.header(&mut entry, true)? { - return Ok(Some(file)); - } - } - // A limit that was met is the caller's to report. A reader that - // failed without taking a byte would fail the same way again. - if ended || inflated.over() || inflated.taken() == before { - break; - } - } - Ok(writers.shadowed()) + Ok(writers + .into_iter() + .filter(|(_, count)| *count > 1) + .map(|(file, _)| file) + .min()) } /// Read a source distribution without npm's `package/` prefix convention. @@ -1461,28 +1110,23 @@ mod tests { ]; let second_entry = raw_tar(&entries[..2]).len() as u64; let mut tar_bytes = raw_tar(&entries); - // What the decoder takes: every entry and one block of the - // end-of-archive marker. The check for a second entry reads on to - // the end of the stream. - let decoded = tar_bytes.len() as u64 + 512; + // What the tar reader takes: every entry and one block of the + // end-of-archive marker. + let consumed = tar_bytes.len() as u64 + 512; tar_bytes.extend([0u8; 1024]); - let stream = tar_bytes.len() as u64; let tgz = gzip(&tar_bytes); - for limit in 0..=stream + 600 { + for limit in 0..=consumed + 600 { let budget = budget(limit); - let why = budget.exceeded(Unpacked::Unknown); let shadowed = shadowed_member_within(&tgz, &files, &budget); - if limit >= stream { - assert_eq!(shadowed.unwrap(), Some("index.js".to_string()), "{limit}"); - } else { - assert_eq!(too_large(shadowed), why, "limit {limit}"); - } let map = read_archive_from_reader(&tgz[..], &budget, false, true); - if limit >= decoded { + if limit >= consumed { + assert_eq!(shadowed.unwrap(), Some("index.js".to_string()), "{limit}"); assert_eq!(map.unwrap()["index.js"], b"original", "{limit}"); continue; } + let why = budget.exceeded(Unpacked::Unknown); + assert_eq!(too_large(shadowed), why, "limit {limit}"); // A member whose header says it does not fit is refused by // that header, before it is read. let why_map = too_large(map); @@ -1555,528 +1199,6 @@ mod tests { } } - /// `entry`, one raw entry, with a header that carries no ustar magic, - /// as a tar from before ustar wrote it. - fn without_magic(mut entry: Vec) -> Vec { - entry[257..265].fill(0); - entry[148..156].fill(b' '); - let sum: u32 = entry[..512].iter().map(|&b| b as u32).sum(); - entry[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); - entry - } - - /// `entry`, one raw entry, with a header in the GNU format, which - /// spells the magic `ustar` and two spaces. - fn with_gnu_magic(mut entry: Vec) -> Vec { - entry[257..265].copy_from_slice(b"ustar \0"); - entry[148..156].fill(b' '); - let sum: u32 = entry[..512].iter().map(|&b| b as u32).sum(); - entry[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); - entry - } - - /// PAX records, each ` =` and a newline. - fn pax(records: &[(&str, &str)]) -> Vec { - let mut out = Vec::new(); - for (key, value) in records { - let rest = format!(" {key}={value}\n"); - let mut len = rest.len() + 1; - while len.to_string().len() + rest.len() != len { - len = len.to_string().len() + rest.len(); - } - out.extend_from_slice(format!("{len}{rest}").as_bytes()); - } - out - } - - /// A header that names the entry after it (a GNU long name, a PAX - /// header) is read differently by this crate's tar reader and by the - /// installers once it is in any shape but the usual one. Each tarball - /// here holds the patched `package/index.js` and then an entry whose - /// own header says `package/harmless.js`, which npm 11.19.1 or Yarn - /// 1.22.19 (the one named) writes to `index.js`. - #[test] - fn a_second_entry_named_by_a_header_before_it_is_seen() { - const LONG: u8 = b'L'; - const PAX: u8 = b'x'; - let files = vec!["package/index.js".to_string()]; - let package = raw_tar(&[ - ("package/package.json", FILE, b"{}"), - ("package/index.js", FILE, b"patched"), - ]); - let harmless = raw_tar(&[("package/harmless.js", FILE, b"original")]); - let naming = |flag: u8, body: &[u8]| raw_tar(&[("././@LongLink", flag, body)]); - let long = b"package/index.js\0"; - let path = pax(&[("path", "package/index.js")]); - let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); - - let before_the_end: Vec<(&str, Vec)> = vec![ - ( - "npm, Yarn 1: a long name without the ustar magic", - without_magic(naming(LONG, long)), - ), - ( - "npm, Yarn 1: a PAX header without the ustar magic", - without_magic(naming(PAX, &path)), - ), - ("npm, Yarn 1: an old GNU long name", naming(b'N', long)), - ("npm: an old PAX header", naming(b'X', &path)), - ( - "npm, Yarn 1: a PAX header with two paths, the last one taken", - naming( - PAX, - &pax(&[("path", "package/fine.js"), ("path", "package/index.js")]), - ), - ), - ( - "npm: a PAX header with an empty line before its path", - naming(PAX, &[b"\n", &path[..]].concat()), - ), - ( - "Yarn 1: a PAX path and then a long name", - [naming(PAX, &path), naming(LONG, b"package/fine.js\0")].concat(), - ), - ( - "Yarn 1: a global PAX path and then a PAX header", - [naming(b'g', &path), naming(PAX, &pax(&[("mtime", "1")]))].concat(), - ), - ]; - // Every shape is tried before the test fails, so one run shows - // each that is missed. - let mut missed = Vec::new(); - for (label, named) in &before_the_end { - let tgz = gzip(&[&package[..], named, &harmless, &marker].concat()); - let shadowed = shadowed_member(&tgz, &files); - if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { - missed.push(format!("before the end: {label}: {shadowed:?}")); - } - } - - // After the first zero block, where a block that is no header is - // passed over: npm keeps the name it holds across such a block. - let after_a_zero_block: Vec<(&str, Vec)> = vec![ - ( - "npm: a long name, then a block that is no header", - [&naming(LONG, long)[..], &junk].concat(), - ), - ( - "npm, Yarn 1: two long names", - [naming(LONG, b"package/other.js\0"), naming(LONG, long)].concat(), - ), - ( - "npm: a PAX path, then a block that is no header", - [&naming(PAX, &path)[..], &junk].concat(), - ), - ]; - for (label, named) in &after_a_zero_block { - let tgz = gzip(&[&package[..], &zero, named, &harmless, &marker].concat()); - let shadowed = shadowed_member(&tgz, &files); - if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { - missed.push(format!("after a zero block: {label}: {shadowed:?}")); - } - } - - // Shapes no installer was tried on. Each is one the readers have - // cause to read differently, or that a header-by-header read - // cannot follow, so each is refused as well. - let big = [&long[..], &vec![0u8; 64 * 1024]].concat(); - let unusual: Vec<(&str, Vec)> = vec![ - // npm passes over one of more than 1 MiB; Yarn 1 applies it. - ("a long name of more than 64 KiB", naming(LONG, &big)), - ( - "a long name with bytes after its NUL", - naming(LONG, b"package/fine.js\0package/index.js\0"), - ), - ("an empty long name", naming(LONG, b"\0")), - ( - "a long link target without the ustar magic", - without_magic(naming(b'K', long)), - ), - ( - "two PAX headers", - [naming(PAX, &pax(&[("mtime", "1")])), naming(PAX, &path)].concat(), - ), - ( - "a PAX record longer than it says", - naming(PAX, b"20 path=package/index.js\n"), - ), - ( - "a PAX value of two lines", - naming(PAX, &pax(&[("comment", "x\n25 path=package/index.js")])), - ), - ( - // The entry after it is 8 bytes by its own header. - "a PAX size that is not the entry's", - naming(PAX, &pax(&[("size", "1024")])), - ), - ( - "a PAX header that names a sparse file", - naming(PAX, &pax(&[("GNU.sparse.name", "package/index.js")])), - ), - ( - "a global PAX header with more than a comment", - naming(b'g', &pax(&[("size", "1024")])), - ), - ( - "a sparse file", - raw_tar(&[("package/sparse.bin", b'S', b"")]), - ), - ]; - for (label, named) in &unusual { - let tgz = gzip(&[&package[..], named, &harmless, &marker].concat()); - let shadowed = shadowed_member(&tgz, &files); - if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { - missed.push(format!("unusual: {label}: {shadowed:?}")); - } - } - // A name with no entry before the zero block: npm gives it to the - // entry after the block. - let tgz = gzip(&[&package[..], &naming(LONG, long), &zero, &harmless, &marker].concat()); - let shadowed = shadowed_member(&tgz, &files); - if !matches!(&shadowed, Ok(Some(file)) if file == "index.js") { - missed.push(format!("a long name and then a zero block: {shadowed:?}")); - } - assert!(missed.is_empty(), "{}", missed.join("\n")); - } - - /// The headers that name an entry, as tar writers make them, are read: - /// a tarball with long paths verifies, a patched file with a long path - /// is counted once, and the decoder knows it by the same name. The - /// shapes are those of `npm pack`, bsdtar (`--format pax` and - /// `gnutar`), Python's `tarfile` and `git archive`. - #[test] - fn a_header_that_names_an_entry_in_its_usual_shape_is_read() { - const LONG: u8 = b'L'; - const PAX: u8 = b'x'; - const SYMLINK: u8 = b'2'; - let deep = format!( - "package/{}/{}.js", - vec!["d".repeat(40); 6].join("/"), - "b".repeat(120) - ); - let patched = deep.strip_prefix("package/").unwrap().to_string(); - let files = vec!["package/index.js".to_string(), deep.clone()]; - let naming = |flag: u8, body: &[u8]| raw_tar(&[("././@LongLink", flag, body)]); - let long_name = [deep.as_bytes(), b"\0"].concat(); - // Its own header holds what fits of the name. - let cut = raw_tar(&[(&deep[..99], FILE, b"deep")]); - let package = raw_tar(&[ - ("package/", DIR, b""), - ("package/package.json", FILE, b"{}"), - ("package/index.js", FILE, b"patched"), - ]); - let marker = [0u8; 1024]; - - let by_long_name = [naming(LONG, &long_name), cut.clone()].concat(); - let by_pax = [ - naming( - PAX, - &pax(&[ - ("path", &deep), - ("mtime", "1796142524.519055416"), - ("size", "4"), - ]), - ), - cut.clone(), - ] - .concat(); - let usual: Vec<(&str, Vec)> = vec![ - ("a GNU long name", by_long_name.clone()), - ( - "a GNU long name in a GNU header, as bsdtar and Python write", - [ - with_gnu_magic(naming(LONG, &long_name)), - with_gnu_magic(cut.clone()), - ] - .concat(), - ), - ("a PAX path, with the times and the size", by_pax.clone()), - ( - "a global PAX comment, as git archive writes", - [ - naming(b'g', &pax(&[("comment", &"d5".repeat(20))])), - by_pax.clone(), - ] - .concat(), - ), - ( - "a PAX header on every entry, as bsdtar writes", - [ - naming(PAX, &pax(&[("ctime", "1.5"), ("atime", "2.5")])), - raw_tar(&[("package/lib/", DIR, b"")]), - by_pax.clone(), - naming(PAX, &pax(&[("mtime", "3.5")])), - raw_tar(&[("package/lib/a.js", FILE, b"a")]), - ] - .concat(), - ), - ( - "a long link target and a long name before a link", - [ - by_long_name.clone(), - naming(b'K', b"index.js\0"), - naming(LONG, b"package/link.js\0"), - raw_tar(&[("package/link.js", SYMLINK, b"")]), - ] - .concat(), - ), - ]; - for (label, named) in &usual { - let tgz = gzip(&[&package[..], named, &marker].concat()); - assert_eq!(shadowed_member(&tgz, &files).unwrap(), None, "{label}"); - // The decoder gives the entry the same name. - assert_eq!( - read_archive_bytes_to_map(&tgz).unwrap()[&patched], - b"deep", - "{label}" - ); - // And it is that name the entry is counted under: another - // entry given it is a second one. - for second in [&by_long_name, &by_pax] { - let twice = gzip(&[&package[..], named, second, &marker].concat()); - assert_eq!( - shadowed_member(&twice, &files).unwrap(), - Some(patched.clone()), - "{label}" - ); - } - } - // A header that names another entry is none itself: 30 files, each - // behind a PAX header, are 30 entries to the limit, as they are to - // the decoder. - let thirty = ArchiveLimits { - max_entries: 30, - ..ArchiveLimits::IN_MEMORY - }; - let many: Vec = (0..30) - .flat_map(|i| { - let name = format!("package/f{i}.js"); - [ - naming(PAX, &pax(&[("path", &name), ("size", "1")])), - raw_tar(&[(&name, FILE, b"x")]), - ] - .concat() - }) - .collect(); - let tgz = gzip(&[&many[..], &marker].concat()); - let budget = thirty.budget(tgz.len() as u64); - assert_eq!(shadowed_member_within(&tgz, &files, &budget).unwrap(), None); - assert_eq!( - read_archive_from_reader(&tgz[..], &budget, false, true) - .unwrap() - .len(), - 30 - ); - } - - #[test] - fn pax_records_are_taken_only_in_the_shape_every_reader_reads_alike() { - let records = |body: &[u8]| { - pax_records(body).map(|records| { - records - .into_iter() - .map(|(key, value)| { - ( - String::from_utf8_lossy(key).into_owned(), - String::from_utf8_lossy(value).into_owned(), - ) - }) - .collect::>() - }) - }; - let pair = |key: &str, value: &str| (key.to_string(), value.to_string()); - assert_eq!(records(b""), Some(vec![])); - // The record is 25 bytes: its length, a space, the pair, a newline. - assert_eq!( - pax(&[("path", "package/index.js")]), - b"25 path=package/index.js\n" - ); - assert_eq!( - records(b"25 path=package/index.js\n11 size=27\n"), - Some(vec![pair("path", "package/index.js"), pair("size", "27")]) - ); - // A value may hold `=` and be empty. - assert_eq!( - records(b"11 a=b=c d\n5 k=\n"), - Some(vec![pair("a", "b=c d"), pair("k", "")]) - ); - for body in [ - // A length that is not the record's. - &b"24 path=package/index.js\n"[..], - b"26 path=package/index.js\n", - b"99 path=package/index.js\n", - // A length that is no plain number. - b"025 path=package/index.js\n", - b"+25 path=package/index.js\n", - b" 25 path=package/index.js\n", - b"path=package/index.js\n", - // No newline at its end, an empty line, a line inside a value. - b"25 path=package/index.js ", - b"\n25 path=package/index.js\n", - b"25 path=package/index.js\n\n", - b"38 comment=x\n25 path=package/index.js\n", - // No key. - b"7 =abc\n", - b"7 abcd\n", - // Bytes after the last record. - b"25 path=package/index.js\n\0", - ] { - assert_eq!(records(body), None, "{:?}", String::from_utf8_lossy(body)); - } - - assert_eq!(long_name(b"package/a.js\0"), Some(b"package/a.js".to_vec())); - assert_eq!(long_name(b"package/a.js"), Some(b"package/a.js".to_vec())); - assert_eq!( - long_name(b"package/a.js\0\0\0"), - Some(b"package/a.js".to_vec()) - ); - assert_eq!(long_name(b"package/a.js\0package/b.js\0"), None); - assert_eq!(long_name(b"\0"), None); - assert_eq!(long_name(b""), None); - } - - /// The installers read a tarball further than the decoder, which ends - /// at the first zero block of the first gzip member (the table on - /// [`shadowed_member`]). A second entry for a patched file anywhere in - /// what they read is found; what is no entry there fails nothing. - #[test] - fn a_second_entry_past_the_first_zero_block_or_gzip_member_is_seen() { - let files = vec!["package/index.js".to_string()]; - let package = raw_tar(&[ - ("package/package.json", FILE, b"{}"), - ("package/index.js", FILE, b"patched"), - ]); - let second = raw_tar(&[("package/index.js", FILE, b"original")]); - let other = raw_tar(&[("package/other.js", FILE, b"x")]); - let (zero, marker, junk) = ([0u8; 512], [0u8; 1024], [0x41u8; 512]); - let whole = [&package[..], &marker].concat(); - let late = [&second[..], &marker].concat(); - - let shadowing: Vec<(&str, Vec)> = vec![ - ( - "after one zero block", - gzip(&[&package[..], &zero, &late].concat()), - ), - ( - "after one zero block and a block that is no header", - gzip(&[&package[..], &zero, &junk, &late].concat()), - ), - ( - "after a zero block, a block that is no header and a zero block", - gzip(&[&package[..], &zero, &junk, &zero, &late].concat()), - ), - ("after the marker", gzip(&[&whole[..], &late].concat())), - ( - "after the marker and one more zero block", - gzip(&[&whole[..], &zero, &late].concat()), - ), - ( - "in a second gzip member, the first without a marker", - [gzip(&package), gzip(&late)].concat(), - ), - ( - "in a second gzip member, after the marker", - [gzip(&whole), gzip(&late)].concat(), - ), - ( - "in a third gzip member", - [gzip(&whole), gzip(&marker), gzip(&late)].concat(), - ), - ( - // The header is read before the member breaks off. - "in a second gzip member that is cut short", - [gzip(&whole), { - let member = gzip(&[&second[..], &noise(4096)].concat()); - member[..member.len() - 512].to_vec() - }] - .concat(), - ), - ]; - for (label, tgz) in &shadowing { - assert_eq!( - shadowed_member(tgz, &files).unwrap(), - Some("index.js".to_string()), - "{label}" - ); - // What the decoder hashes is the first entry, which is why the - // check has to read on. - assert_eq!( - read_archive_bytes_to_map(tgz).unwrap()["index.js"], - b"patched", - "{label}" - ); - } - - let clean: Vec<(&str, Vec)> = vec![ - ("two zero blocks, as npm pack writes", gzip(&whole)), - ("no marker", gzip(&package)), - ( - "zero padding to a 10 KiB record, as GNU tar writes", - gzip(&[&package[..], &vec![0u8; 10240 - package.len()]].concat()), - ), - ( - "blocks that are no header after the marker", - gzip(&[&whole[..], &junk, &junk].concat()), - ), - ( - "less than a block after the marker", - gzip(&[&whole[..], &[7u8; 100]].concat()), - ), - ( - "bytes after the gzip member that start no other", - [gzip(&whole), b"GARBAGE".repeat(16)].concat(), - ), - ( - "the start of a gzip member and nothing else", - [gzip(&whole), gzip(&late)[..12].to_vec()].concat(), - ), - ( - "a second gzip member that holds no tar", - [gzip(&whole), gzip(b"not a tar stream")].concat(), - ), - ( - "another file after the marker", - gzip(&[&whole[..], &other, &marker].concat()), - ), - ( - "another file in a second gzip member", - [gzip(&whole), gzip(&[&other[..], &marker].concat())].concat(), - ), - ]; - for (label, tgz) in &clean { - assert_eq!(shadowed_member(tgz, &files).unwrap(), None, "{label}"); - } - - // The limits hold past the first zero block too: on what is - // inflated there, and on the entries counted. - let padded = gzip(&[&whole[..], &vec![0u8; 8192]].concat()); - assert_eq!( - shadowed_member_within(&padded, &files, &budget(whole.len() as u64 + 8192)).unwrap(), - None - ); - assert_eq!( - too_large(shadowed_member_within( - &padded, - &files, - &budget(whole.len() as u64 + 8191) - )), - "it unpacks to more than 11 KiB, the limit for one archive" - ); - let two_entries = ArchiveLimits { - max_entries: 2, - ..ArchiveLimits::IN_MEMORY - }; - let tgz = gzip(&[&whole[..], &other, &marker].concat()); - assert_eq!( - too_large(shadowed_member_within( - &tgz, - &files, - &two_entries.budget(tgz.len() as u64) - )), - "it holds more than 2 entries, the limit for one archive" - ); - } - #[test] fn test_read_archive_rejects_oversize_entry_header() { // Forge a header that claims a 1 GiB entry backed by tiny actual @@ -2118,54 +1240,6 @@ mod tests { ); } - /// A limit that only the check for a second entry meets, in the part of - /// a tarball the decoder does not read, is named like any other: here a - /// second gzip member of 80 MiB of zeros after a whole package. - #[test] - fn a_limit_met_past_the_first_gzip_member_is_named() { - let files = vec!["package/index.js".to_string()]; - let package = raw_tar_gz(&[ - ("package/package.json", FILE, b"{}"), - ("package/index.js", FILE, b"patched"), - ]); - let tgz = [package, gzip(&vec![0u8; 80 * MIB])].concat(); - assert!(tgz.len() < 128 * 1024, "{}", tgz.len()); - - // The decoder ends at the first member, within every limit. - assert_eq!(read_archive_bytes_to_map(&tgz).unwrap().len(), 2); - let why = too_large(shadowed_member(&tgz, &files)); - assert!( - why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size (") - && why.ends_with(" KiB) and the 64 MiB every archive may use"), - "{why}" - ); - assert_eq!(limit_exceeded(&tgz), Some(why)); - } - - /// The size in a member's header is its author's claim. Before any of - /// the content is read it reserves 128 KiB at most, however much the - /// archive's budget would allow it, and the buffer then grows with what - /// arrives, up to the declared size and never past it. - #[test] - fn a_members_declared_size_alone_reserves_little() { - // 400 MiB claimed, ten bytes there. - let bytes = read_member(&mut &b"ten bytes!"[..], 400 * MIB as u64).unwrap(); - assert_eq!(bytes, b"ten bytes!"); - assert!( - bytes.capacity() <= 128 * 1024, - "{} bytes reserved for ten", - bytes.capacity() - ); - - let content = noise(3 * MIB + 17); - let bytes = read_member(&mut &content[..], content.len() as u64).unwrap(); - assert_eq!(bytes, content); - assert_eq!(bytes.capacity(), content.len()); - // No more than the declared size is taken from a longer input. - let bytes = read_member(&mut &content[..], 1000).unwrap(); - assert_eq!(bytes, content[..1000]); - } - #[test] fn test_read_archive_rejects_too_many_entries() { // One more entry than the limit. Each entry is empty so the @@ -2244,4 +1318,28 @@ mod tests { "{why}" ); } + + /// The size in a member's header is its author's claim. Before any of + /// the content is read it reserves 128 KiB at most, however much the + /// archive's budget would allow it, and the buffer then grows with what + /// arrives, up to the declared size and never past it. + #[test] + fn a_members_declared_size_alone_reserves_little() { + // 400 MiB claimed, ten bytes there. + let bytes = read_member(&mut &b"ten bytes!"[..], 400 * 1024 * 1024).unwrap(); + assert_eq!(bytes, b"ten bytes!"); + assert!( + bytes.capacity() <= 128 * 1024, + "{} bytes reserved for ten", + bytes.capacity() + ); + + let content = crate::patch::archive_limits::noise(3 * 1024 * 1024 + 17); + let bytes = read_member(&mut &content[..], content.len() as u64).unwrap(); + assert_eq!(bytes, content); + assert_eq!(bytes.capacity(), content.len()); + // No more than the declared size is taken from a longer input. + let bytes = read_member(&mut &content[..], 1000).unwrap(); + assert_eq!(bytes, content[..1000]); + } } diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index fc170724f5..f99b50bc68 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -1281,8 +1281,8 @@ pub async fn describe_artifact_failure( "vendor_artifact_unreadable" => "cannot be read", "vendor_artifact_non_canonical" => { "holds a second entry the package manager would extract over a patched \ - file (another top-level directory, a second spelling of the name, a \ - link, or a name given by a header before the entry)" + file (another top-level directory, a second spelling of the name, or a \ + link)" } "vendor_inventory_mismatch" => "has files that differ from its recorded inventory", _ => "failed verification", @@ -3207,45 +3207,4 @@ mod tests { "{why}" ); } - - /// A limit met only where the check for a second entry reads, past the - /// first gzip member of a committed npm tarball, is named by - /// `vendor --check` like one the decoder meets. - #[tokio::test] - async fn a_limit_met_past_the_first_gzip_member_of_a_committed_tarball_is_named() { - let tmp = tempfile::tempdir().unwrap(); - let root = tmp.path(); - let rel = format!(".socket/vendor/npm/{UUID}/x-1.0.0.tgz"); - let tgz = root.join(&rel); - std::fs::create_dir_all(tgz.parent().unwrap()).unwrap(); - write_tgz(&tgz, "package/index.js", PATCHED); - // A second gzip member: 80 MiB of zeros in some 80 KiB. - let mut member = GzEncoder::new( - std::fs::OpenOptions::new().append(true).open(&tgz).unwrap(), - flate2::Compression::new(6), - ); - member.write_all(&vec![0u8; 80 * 1024 * 1024]).unwrap(); - member.finish().unwrap(); - let rec = record(UUID, "package/index.js"); - let mut ent = entry("npm", UUID, &rel); - ent.artifact.sha256 = "ab".repeat(32); - - let health = check_vendored_artifact(root, &ent, &rec).await; - assert_eq!( - health, - ArtifactHealth::Corrupt { - reason: "vendor_artifact_too_large".to_string() - } - ); - let why = describe_artifact_failure(root, &ent, &health) - .await - .unwrap(); - assert!( - why.contains( - "is past the limits archives are read within: it unpacks to more than 64 MiB, \ - over 100 times its own size (" - ), - "{why}" - ); - } } From 3602c9dc98d0270a438eded946e61a8559ace696 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:01:57 -0500 Subject: [PATCH 09/13] Hold a package to one set of size limits on every path, and raise them Each path that reads, unpacks or downloads a package had limits of its own, so one refused for its size what another took. They are one set now, defined in `patch::archive_limits` and named by the other modules: 200,000 entries, 1 GiB unpacked and at most 100 times the archive's own size past 64 MiB, 256 MiB downloaded, 512 MiB read of a committed file. What that raises: - The readers that hold an archive in memory (npm tarballs, wheels, source distributions, `.nupkg`): 512 MiB unpacked to 1 GiB, the jar reader's limit. `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB, 603 MiB of it one file) were refused and are read. - The registry extractors, which write to disk and hold a 64 KiB buffer: 60,000 entries to 200,000, 512 MiB unpacked to 1 GiB, and no limit on one entry below that (it was 128 MiB, which refused the 136 MiB file of `@next/swc-linux-x64-gnu`). A registry download: 128 MiB to 256 MiB, what a download from the patch service may be. - The inventory of a committed directory: 10,000 files to 200,000. A package past it was vendored with no inventory, which exact repair then refused (the wheel of `ansible` 11.1.0 holds 21,105 files). - A patched file recovered from a committed zip (`.nupkg`, wheel, jar): 64 MiB to what the readers let that zip unpack to, so still 64 MiB for a small one and a hundred times its size past that. A committed file that is read whole for it: 256 MiB to 512 MiB, and a file of a committed directory 64 MiB to 512 MiB. Nothing read before is refused now: no limit is lowered. A limit that is met is still an error that names the limit, and the ratio rule stands, so an archive must be 10.3 MiB itself to unpack to 1 GiB. A read holds what it unpacks once, beside the archive. With an npm tarball of 17 MiB that unpacks to 1,000 MiB, `vendor` peaked at 1,079 MiB resident, `vendor --check` at 1,055 MiB and `vex` at 1,059 MiB (macOS, aarch64, a debug build); with one that unpacks to 500 MiB, at 577, 552 and 557 MiB. Hashing members as they inflate would hold the archive alone, and is a change to every caller that takes the member map; it is not made here. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- crates/socket-patch-core/src/api/client.rs | 2 +- .../src/patch/archive_limits.rs | 86 +++++++++++++------ .../src/patch/jar_members.rs | 8 +- crates/socket-patch-core/src/patch/package.rs | 54 +++++++++++- crates/socket-patch-core/src/vendor/cargo.rs | 18 ++-- crates/socket-patch-core/src/vendor/common.rs | 2 +- .../src/vendor/composer_lock.rs | 23 +++-- crates/socket-patch-core/src/vendor/golang.rs | 17 ++-- crates/socket-patch-core/src/vendor/mod.rs | 62 ++++++++++--- .../src/vendor/registry_fetch.rs | 37 ++++++-- crates/socket-patch-core/src/vendor/verify.rs | 41 +++++---- docs/usage.md | 5 +- 13 files changed, 264 insertions(+), 97 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 2f6154d168..b89f4476a1 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1662,11 +1662,11 @@ path. Without hosted pins the no-manifest no-op below is unchanged. Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as the patch's prebuilt platform gems instead: for each locked platform the server's `gem-platform` artifact and its `gem-platform-stub-gemspec` (each carries its `platform`), both verified like the ruby gem and its stub. Which prebuilds exist is read from the package reference alone, and the ruby gem it also names is not downloaded. While the server lists no prebuild for a locked platform nothing is downloaded and the gem is skipped (`vendor_prebuilt_platform_pending`). A prebuild need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check against the digest the server states for that platform is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. -**Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 512 MiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 512 MiB plus the archive itself is what checking one archive may take. +**Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 1 GiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 1 GiB plus the archive itself is what checking one archive may take: an npm tarball of 17 MiB that unpacks to 1,000 MiB was measured at 1,079 MiB resident for `vendor`, 1,055 MiB for `vendor --check` and 1,059 MiB for `vex`. These are the limits wherever a package is read, unpacked or downloaded, so that one path does not refuse for its size what another takes: the registry extractors, which write to disk, unpack 200,000 entries and 1 GiB with no smaller limit on one entry (they were 60,000 entries, 512 MiB and 128 MiB for one entry: `@next/swc-linux-x64-gnu` holds a file of 136 MiB); a download is at most 256 MiB from the patch service and from a registry (a registry's was 128 MiB); the inventory of a committed directory covers 200,000 files (it was 10,000: the wheel of `ansible` 11.1.0 holds 21,105); a patched file recovered from a committed zip may be as large as that zip may unpack to (it was 64 MiB); and a jar has the same 200,000 entries, 1 GiB and 100 times its own size. -An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 946 MiB, over the limit of 512 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 1100 MiB, over the limit of 1024 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. -Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. Two wheels within that download size unpack to more than 512 MiB and are refused: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB). Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). +Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. The two largest wheels measured within that download size are within the limit: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB, 603 MiB of it one file). At the 512 MiB the limit was, both were refused. Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` and the diff archive path). Vendored runs retain patch records in memory and embed them in the vendor ledger, without staging blobs. N-API and the hosted in-memory engine remain supported for callers such as the future GitHub App. diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index fb137ea93f..55624ebb13 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -2380,7 +2380,7 @@ fn artifact_download_result( /// Cap on a single prebuilt-archive download (defensive bound against a /// runaway / hostile serve response). Generous enough for any real package. -pub(crate) const MAX_VENDOR_PACKAGE_BYTES: u64 = 256 * 1024 * 1024; +pub(crate) const MAX_VENDOR_PACKAGE_BYTES: u64 = crate::patch::archive_limits::MAX_DOWNLOAD_BYTES; /// A prebuilt vendored archive downloaded from the patch.socket.dev service, /// together with the service-reported integrity. The bytes are **unverified** diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index 1f1436295f..a93a509230 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -30,18 +30,17 @@ //! * `max_entries`: 200,000 entries, the jar reader's count //! ([`crate::patch::jar_members`]). Six times the largest tarball measured //! above and nine times the largest wheel. -//! * `max_inflated_bytes`: 512 MiB inflated in one read of one archive. -//! Both readers hold what they inflate, so this, beside the archive's own -//! bytes, is what reading one archive may take in memory, and it is half -//! of what the jar reader, which holds a digest per member, may inflate. -//! It is what a download at the patch service's 256 MiB cap unpacks to -//! at 2:1 and one at the registries' 128 MiB cap at 4:1 (compiled wheels -//! sit between 1.6:1 and 4.3:1), the size a committed artifact is read up -//! to, and what the registry extractors may unpack to disk -//! (`vendor::registry_fetch`). Every tarball measured is under half of -//! it. Two wheels measured within the download cap are past it and stay -//! refused: `mkl-2025.0.1` (176.2 MiB, 521.1 MiB unpacked) and -//! `tensorflow_cpu-2.18.0` (219.6 MiB, 945.6 MiB unpacked). +//! * `max_inflated_bytes`: 1 GiB inflated in one read of one archive, which +//! is what the jar reader, which holds a digest per member, may inflate +//! and what the registry extractors may unpack to disk +//! (`vendor::registry_fetch`). Both readers here hold what they inflate, +//! so this, beside the archive's own bytes, is what reading one archive +//! may take in memory (see "What a read costs" below). It is what a +//! download at the 256 MiB cap unpacks to at 4:1 (compiled wheels sit +//! between 1.6:1 and 4.3:1). The two largest wheels measured within the +//! download cap are within it: `mkl-2025.0.1` (176.2 MiB, 521.1 MiB +//! unpacked) and `tensorflow_cpu-2.18.0` (219.6 MiB, 945.6 MiB unpacked, +//! 603.3 MiB of it one member). It was 512 MiB, which refused both. //! * `max_inflate_ratio` past `ratio_floor_bytes`: no more than 100 times //! the archive's own size, once past the 64 MiB (the old limit) every //! archive may use, so nothing that was read whole before is refused now. @@ -49,7 +48,22 @@ //! between 1.6:1 and 11:1 by their members' bytes, and the tarball of //! 31,858 small files is 26:1 counted as the tarball reader counts it //! (below). This keeps a small hostile archive from spending the whole -//! 512 MiB. +//! 1 GiB: one must be 10.3 MiB on disk to inflate that far. +//! +//! # What a read costs +//! +//! A read holds every member once, beside the archive's own bytes. Measured +//! on macOS (aarch64, a debug build) with an npm tarball of 17 MiB that +//! unpacks to 1,000 MiB, `vendor` peaked at 1,079 MiB resident, +//! `vendor --check` at 1,055 MiB and `vex` at 1,059 MiB; with one that +//! unpacks to 500 MiB, at 577, 552 and 557 MiB. So a read takes what it +//! inflates, the archive and some 60 MiB: at the limits, 1.3 GiB for a +//! download of 256 MiB and 1.6 GiB for a committed file of 512 MiB. A +//! crafted archive must be 10.3 MiB itself to cost the first. A check that +//! hashed each member as it inflates would hold the archive alone; every +//! caller takes the map of members today (the checks of a tarball and of a +//! wheel, the reuse of a committed artifact, the repair download), so that +//! is a change to each of them, which this limit does not wait for. //! //! There is no separate limit on one member: `libxgboost.so` is 238.5 MiB //! and `_catboost.so` 281.9 MiB, so a member may be as large as what is left @@ -75,6 +89,26 @@ use std::io::Read; const KIB: u64 = 1024; const MIB: u64 = 1024 * KIB; +// One set of limits on a package, for every path that reads, unpacks or +// downloads one, so that a package one path takes is not refused by +// another for its size alone. The other modules name these. + +/// Entries one package may hold. +pub(crate) const MAX_ENTRIES: usize = 200_000; +/// Bytes one package may unpack to: in memory for the readers that hold +/// what they inflate, on disk for the extractors. +pub(crate) const MAX_INFLATED_BYTES: u64 = 1024 * MIB; +/// Unpacked bytes allowed per archive byte, past [`RATIO_FLOOR_BYTES`]. +pub(crate) const MAX_INFLATE_RATIO: u64 = 100; +/// What any archive may unpack to, however small it is. +pub(crate) const RATIO_FLOOR_BYTES: u64 = 64 * MIB; +/// Bytes of one package that are downloaded, from the patch service or a +/// registry. A download is held in memory. +pub(crate) const MAX_DOWNLOAD_BYTES: u64 = 256 * MIB; +/// Bytes of one committed artifact, or of one file of a committed +/// directory, that are read. A committed file is held in memory. +pub(crate) const MAX_ON_DISK_BYTES: u64 = 512 * MIB; + /// The limits one read of one archive is held to (see the module docs). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct ArchiveLimits { @@ -91,10 +125,10 @@ pub(crate) struct ArchiveLimits { impl ArchiveLimits { /// The limits of the readers that hold every member in memory. pub(crate) const IN_MEMORY: Self = Self { - max_entries: 200_000, - max_inflated_bytes: 512 * MIB, - max_inflate_ratio: 100, - ratio_floor_bytes: 64 * MIB, + max_entries: MAX_ENTRIES, + max_inflated_bytes: MAX_INFLATED_BYTES, + max_inflate_ratio: MAX_INFLATE_RATIO, + ratio_floor_bytes: RATIO_FLOOR_BYTES, }; /// One limit on the inflated bytes and no other: for an extractor with @@ -327,7 +361,11 @@ mod tests { // Below 655 KiB the floor is the larger. assert_eq!(limits.budget(655 * KIB).bytes(), 64 * MIB); assert_eq!(limits.budget(MIB).bytes(), 100 * MIB); - assert_eq!(limits.budget(6 * MIB).bytes(), 512 * MIB); + // Past the 512 MiB the limit was, and within the 1 GiB it is. + assert_eq!(limits.budget(6 * MIB).bytes(), 600 * MIB); + assert_eq!(limits.budget(10 * MIB).bytes(), 1000 * MIB); + assert_eq!(limits.budget(11 * MIB).bytes(), 1024 * MIB); + assert_eq!(limits.budget(u64::MAX).bytes(), 1024 * MIB); // An extractor's single limit is the same for an archive of any size. let extractor = ArchiveLimits::inflated_only(4000); @@ -347,19 +385,19 @@ mod tests { "it holds more than 200000 entries, the limit for one archive" ); - // Large enough for the whole 512 MiB. + // Large enough for the whole 1 GiB. let capped = limits.budget(220 * MIB); assert_eq!( - capped.exceeded(Unpacked::Declared(946 * MIB)), - "it unpacks to 946 MiB, over the limit of 512 MiB for one archive" + capped.exceeded(Unpacked::Declared(1100 * MIB)), + "it unpacks to 1100 MiB, over the limit of 1024 MiB for one archive" ); assert_eq!( - capped.exceeded(Unpacked::AtLeast(512 * MIB + 1)), - "it unpacks to at least 513 MiB, over the limit of 512 MiB for one archive" + capped.exceeded(Unpacked::AtLeast(1024 * MIB + 1)), + "it unpacks to at least 1025 MiB, over the limit of 1024 MiB for one archive" ); assert_eq!( capped.exceeded(Unpacked::Unknown), - "it unpacks to more than 512 MiB, the limit for one archive" + "it unpacks to more than 1024 MiB, the limit for one archive" ); // A small archive is held to its own size. diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index 3127c2b7f3..6002a112f0 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -77,15 +77,15 @@ use sha2::{Digest, Sha256}; use crate::hash::git_sha256::compute_git_sha256_from_std_reader; /// Entries one jar may hold (see the module docs). -pub(crate) const MAX_ENTRIES: usize = 200_000; +pub(crate) const MAX_ENTRIES: usize = super::archive_limits::MAX_ENTRIES; /// Bytes the central directory of one jar may take. pub(crate) const MAX_CENTRAL_DIRECTORY_BYTES: u64 = 64 * 1024 * 1024; /// Bytes one pass over one jar may inflate. -pub(crate) const MAX_INFLATED_BYTES: u64 = 1024 * 1024 * 1024; +pub(crate) const MAX_INFLATED_BYTES: u64 = super::archive_limits::MAX_INFLATED_BYTES; /// Inflated bytes allowed per archive byte, past [`RATIO_FLOOR_BYTES`]. -pub(crate) const MAX_INFLATE_RATIO: u64 = 100; +pub(crate) const MAX_INFLATE_RATIO: u64 = super::archive_limits::MAX_INFLATE_RATIO; /// What any archive may inflate to, however small it is. -pub(crate) const RATIO_FLOOR_BYTES: u64 = 64 * 1024 * 1024; +pub(crate) const RATIO_FLOOR_BYTES: u64 = super::archive_limits::RATIO_FLOOR_BYTES; /// Why a jar could not be read. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index c3dde7e84a..5b80aaa1aa 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -514,8 +514,8 @@ const MEMBER_FIRST_RESERVE: usize = 128 * 1024; /// first, which the walk then finds at the next header. /// /// The size comes from the member's header, its author's claim, and is -/// within what is left of the archive's budget: up to 512 MiB, for an -/// archive of five megabytes. So the buffer is not reserved in one piece on +/// within what is left of the archive's budget: up to 1 GiB, for an +/// archive of ten megabytes. So the buffer is not reserved in one piece on /// that claim. It starts at [`MEMBER_FIRST_RESERVE`] and doubles as the /// content arrives, up to `size` and never past it, and a reservation the /// machine cannot make is [`ArchiveError::TooLarge`], where @@ -1342,4 +1342,54 @@ mod tests { let bytes = read_member(&mut &content[..], 1000).unwrap(); assert_eq!(bytes, content[..1000]); } + + /// A tarball that unpacks to more than the 512 MiB the limit was is + /// read, and checked for a second entry: `mkl` 2025.0.1 unpacks to 521 + /// MiB. One that declares more than the 1 GiB the limit is fails by + /// that limit, before its content is read. + #[test] + fn a_tarball_past_the_old_512_mib_limit_is_read() { + let filler = crate::patch::archive_limits::noise(6 * MIB); + let big = 520 * MIB as u64; + let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast())); + for (name, size) in [ + ("package/noise.bin", filler.len() as u64), + ("package/big.bin", big), + ] { + let mut header = tar::Header::new_gnu(); + header.set_path(name).unwrap(); + header.set_size(size); + header.set_mode(0o644); + header.set_cksum(); + if name.ends_with("noise.bin") { + builder.append(&header, &filler[..]).unwrap(); + } else { + builder + .append(&header, std::io::repeat(0x20).take(size)) + .unwrap(); + } + } + let tgz = builder.into_inner().unwrap().finish().unwrap(); + let files = vec!["package/big.bin".to_string()]; + assert_eq!(shadowed_member(&tgz, &files).unwrap(), None); + let decoded = read_archive_bytes_to_map(&tgz).unwrap(); + assert_eq!(decoded["big.bin"].len() as u64, big); + drop(decoded); + + // 11 MiB of the tarball's own, so that it may unpack to the limit, + // and a header that declares one byte more than is left of it. + let mut over = raw_tar(&[ + ("package/noise.bin", FILE, &filler[..]), + ("package/more.bin", FILE, &filler[..5 * MIB]), + ]); + over.extend_from_slice(&ustar_block(b"package/big.bin", FILE, 1024 * MIB as u64)); + let error = read_archive_bytes_to_map(&gzip(&over)).unwrap_err(); + assert!(error.is_too_large(), "{error}"); + assert!( + error + .to_string() + .contains("over the limit of 1024 MiB for one archive"), + "{error}" + ); + } } diff --git a/crates/socket-patch-core/src/vendor/cargo.rs b/crates/socket-patch-core/src/vendor/cargo.rs index 8a745db4ad..553e927723 100644 --- a/crates/socket-patch-core/src/vendor/cargo.rs +++ b/crates/socket-patch-core/src/vendor/cargo.rs @@ -2466,12 +2466,11 @@ mod tests { ); } - /// A crate past the inventory's 10,000-file cap (well within the - /// extractor's entry cap) still vendors and is wired: the entry records - /// no inventory and says so, rather than refusing and leaving the - /// extracted copy behind unwired. + /// A crate of more than 10,000 files, where the inventory stopped and + /// the entry recorded none, vendors with its inventory: the cap is the + /// 200,000 entries one package may hold. #[tokio::test] - async fn fresh_vendor_past_the_inventory_cap_records_no_inventory() { + async fn fresh_vendor_past_the_old_inventory_cap_records_its_inventory() { let (dir, blobs, pristine, record) = fixture().await; let root = dir.path(); std::fs::create_dir_all(pristine.join("filler")).unwrap(); @@ -2482,12 +2481,15 @@ mod tests { expect_done(run_vendor(PURL, root, &blobs, &pristine, &record, false).await); assert!(result.success, "{:?}", result.error); let entry = entry.expect("the crate is vendored"); - assert!(entry.artifact.file_inventory.is_none()); + let inventory = entry.artifact.file_inventory.as_ref(); + assert!( + inventory.is_some_and(|files| files.len() > 10_000), + "the inventory of more than 10,000 files is recorded" + ); assert!( warnings .iter() - .any(|w| w.code == "vendor_inventory_unrecorded" - && w.detail.contains("exceeds 10000 files")), + .all(|w| w.code != "vendor_inventory_unrecorded"), "{warnings:?}" ); assert_eq!(manifest_path(root).await, Some(copy_rel())); diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 8f1cce2275..fd7a3aeb2c 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -260,7 +260,7 @@ pub(crate) fn write_zip_entries(entries: &[(String, Vec, u32)]) -> Result Option> { read_zip_artifact_capped(archive_path, MAX_ZIP_ARTIFACT_BYTES).await diff --git a/crates/socket-patch-core/src/vendor/composer_lock.rs b/crates/socket-patch-core/src/vendor/composer_lock.rs index 46b33ee717..d6cd8c7d55 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -4219,12 +4219,12 @@ mod tests { assert_eq!(tokio::fs::read(ledger).await.unwrap(), ledger_before); } - /// A package past the inventory's 10,000-file cap (well within the - /// extractor's entry cap) still vendors: the lock is wired, the entry - /// records no inventory and says so, and exact repair refuses it - /// cleanly instead of guessing. + /// A package of more than 10,000 files, where the inventory stopped and + /// the entry recorded none, vendors with its inventory: the cap is the + /// 200,000 entries one package may hold. An entry without an inventory + /// is still one that exact repair refuses cleanly instead of guessing. #[tokio::test] - async fn fresh_composer_vendor_past_the_inventory_cap_records_no_inventory() { + async fn fresh_composer_vendor_past_the_old_inventory_cap_records_its_inventory() { let lock = lock_value("psr/log", "3.0.2", false); let (dir, blobs, installed, record) = fixture(&lock).await; let root = dir.path(); @@ -4236,12 +4236,15 @@ mod tests { unwrap_done(run_vendor(root, &blobs, &installed, &record, PURL, false).await); assert!(result.success, "{:?}", result.error); let entry = entry.expect("the package is vendored"); - assert!(entry.artifact.file_inventory.is_none()); + let inventory = entry.artifact.file_inventory.as_ref(); + assert!( + inventory.is_some_and(|files| files.len() > 10_000), + "the inventory of more than 10,000 files is recorded" + ); assert!( warnings .iter() - .any(|w| w.code == "vendor_inventory_unrecorded" - && w.detail.contains("exceeds 10000 files")), + .all(|w| w.code != "vendor_inventory_unrecorded"), "{warnings:?}" ); let lock_after = tokio::fs::read_to_string(root.join(COMPOSER_LOCK)) @@ -4249,7 +4252,9 @@ mod tests { .unwrap(); assert!(lock_after.contains(©_rel()), "{lock_after}"); let cfg = composer_service_cfg("http://127.0.0.1:1", VendorSource::Service, false); - let err = super::super::redownload::restore(root, &entry, &record, &cfg) + let mut bare = entry.clone(); + bare.artifact.file_inventory = None; + let err = super::super::redownload::restore(root, &bare, &record, &cfg) .await .unwrap_err(); assert!(err.contains("no complete file inventory"), "{err}"); diff --git a/crates/socket-patch-core/src/vendor/golang.rs b/crates/socket-patch-core/src/vendor/golang.rs index cf9b5aee9c..af3f700fb7 100644 --- a/crates/socket-patch-core/src/vendor/golang.rs +++ b/crates/socket-patch-core/src/vendor/golang.rs @@ -1054,11 +1054,11 @@ mod tests { ); } - /// A module past the inventory's 10,000-file cap (well within the - /// extractor's entry cap) still vendors and is wired: the entry records - /// no inventory and says so. + /// A module of more than 10,000 files, where the inventory stopped and + /// the entry recorded none, vendors with its inventory: the cap is the + /// 200,000 entries one package may hold. #[tokio::test] - async fn fresh_vendor_past_the_inventory_cap_records_no_inventory() { + async fn fresh_vendor_past_the_old_inventory_cap_records_its_inventory() { let (dir, blobs, pristine, record) = fixture().await; let root = dir.path(); std::fs::create_dir_all(pristine.join("filler")).unwrap(); @@ -1069,12 +1069,15 @@ mod tests { expect_done(run_vendor(PURL, root, &blobs, &pristine, &record, false).await); assert!(result.success, "{:?}", result.error); let entry = entry.expect("the module is vendored"); - assert!(entry.artifact.file_inventory.is_none()); + let inventory = entry.artifact.file_inventory.as_ref(); + assert!( + inventory.is_some_and(|files| files.len() > 10_000), + "the inventory of more than 10,000 files is recorded" + ); assert!( warnings .iter() - .any(|w| w.code == "vendor_inventory_unrecorded" - && w.detail.contains("exceeds 10000 files")), + .all(|w| w.code != "vendor_inventory_unrecorded"), "{warnings:?}" ); assert!(root.join(copy_rel()).join("filler/f0").exists()); diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 0f7a5ebf33..c48fb5b743 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -439,11 +439,23 @@ pub async fn harvest_artifact_blobs( harvest_artifact_blobs_from(project_root, &state.entries, manifest_patches).await } -/// Hard cap on a committed artifact's own bytes, and on any one member -/// harvested out of it. Shared by [`harvest_artifact_blobs_from`] and the -/// zip reader it hands the work to. -const MAX_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024; -const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; +/// Hard cap on a committed artifact's own bytes, and on one file of a +/// committed directory: what any committed file is read up to. +const MAX_ARTIFACT_BYTES: u64 = crate::patch::archive_limits::MAX_ON_DISK_BYTES; + +/// What one member harvested out of a zip of `archive_len` bytes may +/// inflate to: what the readers let that whole archive inflate to, so 64 +/// MiB for a small one, a hundred times its own size past that, and no +/// more than a package may unpack to. One member is held at a time. +fn member_cap(archive_len: u64) -> u64 { + crate::patch::archive_limits::ArchiveLimits::IN_MEMORY + .budget(archive_len) + .bytes() +} + +/// [`member_cap`] of a small archive, for the tests' own scan. +#[cfg(test)] +const MAX_FILE_BYTES: u64 = crate::patch::archive_limits::RATIO_FLOOR_BYTES; /// [`harvest_artifact_blobs`] over an already-loaded ledger (`entries`), /// for callers that hold the run's single `load_state` result. @@ -571,7 +583,7 @@ pub async fn harvest_artifact_blobs_from( // non-regular file (FIFO wedge), bound the read up front. if !tokio::fs::metadata(&path) .await - .is_ok_and(|m| m.is_file() && m.len() <= MAX_FILE_BYTES) + .is_ok_and(|m| m.is_file() && m.len() <= MAX_ARTIFACT_BYTES) { continue; } @@ -627,19 +639,19 @@ fn harvest_zip_blobs(path: &Path, wanted: &[(String, String)]) -> HashMap Option> { + fn capped(size: u64, entry: &mut impl std::io::Read, most: u64) -> Option> { use std::io::Read as _; - if size > MAX_FILE_BYTES { + if size > most { return None; } let mut content = Vec::with_capacity(size as usize); entry .by_ref() - .take(MAX_FILE_BYTES + 1) + .take(most + 1) .read_to_end(&mut content) .ok()?; - (content.len() as u64 <= MAX_FILE_BYTES).then_some(content) + (content.len() as u64 <= most).then_some(content) } let mut out: HashMap> = HashMap::new(); @@ -649,6 +661,7 @@ fn harvest_zip_blobs(path: &Path, wanted: &[(String, String)]) -> HashMap HashMap HashMap = (0..60_001).map(|i| format!("f{i}")).collect(); + let mut files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b""[..])).collect(); + files.push(("big.bin", &big)); + let zip_bytes = make_module_zip("m@v1/", &files); + let h1 = go_h1_of_zip(&zip_bytes).unwrap(); + assert!(h1.starts_with("h1:"), "{h1}"); + } + #[test] fn go_h1_caps_actual_decompressed_bytes() { // A module zip whose entry DECLARES a tiny size while its deflate diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index f99b50bc68..eed04fb0e5 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -890,12 +890,13 @@ fn read_zip_within( /// Hard cap on whole-artifact bytes hashed by the health check — committed /// artifacts are small (a package tarball/wheel); a tampered multi-GiB file /// must not stall `repair`. -pub(crate) const MAX_HEALTH_HASH_BYTES: u64 = 512 * 1024 * 1024; +pub(crate) const MAX_HEALTH_HASH_BYTES: u64 = crate::patch::archive_limits::MAX_ON_DISK_BYTES; -/// Hard cap on inventoried files (what the zip reader's entry cap was when -/// this one was written) — a committed artifact dir is one package; a -/// tampered dir must not stall an audit with a million planted files. -const MAX_INVENTORY_ENTRIES: usize = 10_000; +/// Hard cap on inventoried files: the entries one package may hold, as an +/// archive or unpacked (the wheel of `ansible` 11.1.0 holds 21,105) — a +/// committed artifact dir is one package; a tampered dir must not stall an +/// audit with a million planted files. +const MAX_INVENTORY_ENTRIES: usize = crate::patch::archive_limits::MAX_ENTRIES; /// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar/gem) /// — whose whole-file drift check is the ledger `sha256` — as opposed to a @@ -921,18 +922,19 @@ pub fn artifact_is_file_shaped(path: &str) -> bool { /// could escape the artifact dir or wedge the audit), a non-UTF-8 name, an /// unreadable file, or a tree past the entry cap. pub async fn compute_dir_inventory(dir: &Path) -> Result, String> { - inventory_walk(dir, false).await + inventory_walk(dir, false, MAX_INVENTORY_ENTRIES).await } /// [`compute_dir_inventory`] of a vlt package dir, leaving out its top-level /// `node_modules/` (vlt's links, never part of the artifact). pub async fn compute_package_dir_inventory(dir: &Path) -> Result, String> { - inventory_walk(dir, true).await + inventory_walk(dir, true, MAX_INVENTORY_ENTRIES).await } async fn inventory_walk( dir: &Path, skip_node_modules: bool, + max_entries: usize, ) -> Result, String> { let root = dir.to_path_buf(); tokio::task::spawn_blocking(move || { @@ -972,10 +974,8 @@ async fn inventory_walk( if meta.len() > MAX_HEALTH_HASH_BYTES { return Err(format!("`{child_rel}` exceeds the inventory size cap")); } - if out.len() >= MAX_INVENTORY_ENTRIES { - return Err(format!( - "artifact dir exceeds {MAX_INVENTORY_ENTRIES} files" - )); + if out.len() >= max_entries { + return Err(format!("artifact dir exceeds {max_entries} files")); } let mut file = std::fs::File::open(entry.path()) .map_err(|e| format!("unreadable `{child_rel}`: {e}"))?; @@ -3104,18 +3104,23 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let dir = tmp.path().join("artifact"); std::fs::create_dir_all(&dir).unwrap(); - for i in 0..MAX_INVENTORY_ENTRIES { + // More files than the 10,000 the cap was: ansible's wheel unpacks + // to 21,105. + for i in 0..10_001 { std::fs::File::create(dir.join(format!("f{i}"))).unwrap(); } + assert_eq!(compute_dir_inventory(&dir).await.unwrap().len(), 10_001); + // The cap is the entries one package may hold. Past it the walk + // fails, by the count it names: shown at a count of files a test + // can write. + assert_eq!(MAX_INVENTORY_ENTRIES, 200_000); assert_eq!( - compute_dir_inventory(&dir).await.unwrap().len(), - MAX_INVENTORY_ENTRIES, + inventory_walk(&dir, false, 10_001).await.unwrap().len(), + 10_001, "a dir at exactly the entry cap still inventories" ); - - std::fs::File::create(dir.join("one-more")).unwrap(); - let err = compute_dir_inventory(&dir).await.unwrap_err(); - assert!(err.contains("exceeds 10000 files"), "got: {err}"); + let err = inventory_walk(&dir, false, 10_000).await.unwrap_err(); + assert_eq!(err, "artifact dir exceeds 10000 files"); } /// A committed artifact grown past the 512 MiB an artifact is read up diff --git a/docs/usage.md b/docs/usage.md index 8a6698a302..94c1e084e7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -209,8 +209,9 @@ artifacts can be reused offline; new artifacts require the patch service. For changes to v4's local artifact building, see the [migration guide](migrating-to-v5.md#service-only-vendoring). Archives are read within fixed limits. An npm tarball, a Python wheel or source -distribution or a `.nupkg` may hold 200,000 entries and unpack to 512 MiB, and to -no more than 100 times its own size once past 64 MiB; a jar may inflate to 1 GiB. +distribution, a `.nupkg` or a jar may hold 200,000 entries and unpack to 1 GiB, and to +no more than 100 times its own size once past 64 MiB. What is unpacked is held in +memory, beside the archive. A package past a limit is not vendored, and a committed one fails `vendor --check` and is left out by `vex` (`vendor_artifact_too_large`). The message names the limit and what the archive unpacks to. From 32bf4a3b028965877da22701760a488af70511a3 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 17:14:32 -0500 Subject: [PATCH 10/13] Reserve nothing on a declared size, and read one member where one is wanted Four things the review of the raised limits found. A patched file is recovered from a committed zip by reading its entries, and each read reserved a buffer of the size the entry declares. That size could be 64 MiB and can now be what the whole zip may unpack to: a committed wheel, `.nupkg` or jar of eleven megabytes whose entries each declare a gigabyte reserved a gigabyte for each, and where the machine refuses one (a commit limit, `ulimit -v`) `Vec::with_capacity` aborts the process. Nothing is reserved on the claim now; the buffer grows with what the entry inflates to, within the same cap. No other read the raise touched reserves on a size an archive or a response declares: the tarball reader grows a member's buffer already, and the others reserve a committed file's own size on disk, which the read then fills. Four callers read a whole tarball into memory for its `package.json`: the manifest of a hosted tarball, the name in a `file:` tarball of a Yarn lock, the manifest a vendored Yarn Berry entry is rendered from, and the one VEX discovery reads. Under the raised limit a tarball that unpacks to 800 MiB was held whole to read a name, where it stopped at 64 MiB before. They read the one member now, `read_archive_member`: the walk is the same, every entry counted and inflated within the same limits, so the same tarballs fail by the same errors, and the other members are passed over and not held. The reader that keyed every member under any top-level directory had no other caller and is gone; its rule is the one the one-member read applies. A limit error stated a multiple of the archive's own size with that size rounded up to a whole MiB: an archive of 1.2 MiB, held to 120 MiB, was "over 100 times its own size (2 MiB)". It is shown to a tenth of a MiB, rounded down. The `vex` omission for a too-large artifact still said 512 MiB for a tarball, wheel or `.nupkg`. Its numbers are the limits themselves now, and two comments that called the jar limit twice the in-memory one are corrected. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/vex.rs | 14 +- .../src/formats/yarn/copy.rs | 5 +- .../src/hosted/npm_manifest.rs | 8 +- .../src/patch/archive_limits.rs | 43 +++++- crates/socket-patch-core/src/patch/package.rs | 137 ++++++++++++++++-- crates/socket-patch-core/src/vendor/mod.rs | 70 +++++---- .../src/vendor/redownload.rs | 2 +- crates/socket-patch-core/src/vendor/verify.rs | 9 +- .../src/vendor/yarn_berry_lock.rs | 5 +- .../socket-patch-core/src/vex/discover/npm.rs | 7 +- 10 files changed, 240 insertions(+), 60 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 970d27956b..3e5e8b07cf 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2844,10 +2844,16 @@ fn omission_phrase(reason: &str) -> &'static str { "vendor_artifact_missing" => "the vendored artifact is missing", "vendor_artifact_unreadable" => "the vendored artifact cannot be read", "vendor_artifact_too_large" => { - "the vendored artifact is past the limits it is read within (200,000 entries, or \ - 100 times its own size inflated and 1 GiB for a jar, 512 MiB for a tarball, wheel \ - or .nupkg), so its contents were not checked; run socket-patch repair to restore \ - the recorded artifact" + // The numbers are the limits themselves, not a copy of them. + static PHRASE: std::sync::OnceLock = std::sync::OnceLock::new(); + PHRASE.get_or_init(|| { + format!( + "the vendored artifact is past the limits it is read within ({}), so its \ + contents were not checked; run socket-patch repair to restore the recorded \ + artifact", + socket_patch_core::vendor::archive_limits_summary() + ) + }) } "vendor_artifact_non_canonical" => { "the vendored tarball holds a second entry the package manager would extract \ diff --git a/crates/socket-patch-core/src/formats/yarn/copy.rs b/crates/socket-patch-core/src/formats/yarn/copy.rs index 5da7bac808..fae908d771 100644 --- a/crates/socket-patch-core/src/formats/yarn/copy.rs +++ b/crates/socket-patch-core/src/formats/yarn/copy.rs @@ -321,8 +321,9 @@ fn package_version(manifest: &serde_json::Value) -> Option { /// `name` of the `package.json` inside an npm tarball. fn tarball_manifest_name(bytes: &[u8]) -> Option { - let map = crate::patch::package::read_archive_bytes_to_map_any_root(bytes).ok()?; - manifest_name(map.get("package.json")?) + let manifest = + crate::patch::package::read_archive_member_any_root(bytes, "package.json").ok()??; + manifest_name(&manifest) } #[cfg(test)] diff --git a/crates/socket-patch-core/src/hosted/npm_manifest.rs b/crates/socket-patch-core/src/hosted/npm_manifest.rs index 8418ba2665..4fb0c5da5d 100644 --- a/crates/socket-patch-core/src/hosted/npm_manifest.rs +++ b/crates/socket-patch-core/src/hosted/npm_manifest.rs @@ -16,12 +16,10 @@ pub fn decode_hosted_npm_manifest(bytes: &[u8], sha512: Option<&str>) -> Result< crate::vendor::registry_fetch::verify_sri(bytes, sri) .map_err(|_| "hosted tarball does not match its published sha512".to_string())?; } - let members = crate::patch::package::read_archive_bytes_to_map(bytes) - .map_err(|error| format!("hosted tarball is not a readable npm package: {error}"))?; - let manifest = members - .get("package.json") + let manifest = crate::patch::package::read_archive_member(bytes, "package.json") + .map_err(|error| format!("hosted tarball is not a readable npm package: {error}"))? .ok_or_else(|| "hosted tarball has no package/package.json".to_string())?; - let text = std::str::from_utf8(manifest) + let text = std::str::from_utf8(&manifest) .map_err(|_| "hosted tarball package.json is not UTF-8".to_string())?; let text = crate::formats::text::strip_bom(text); if !serde_json::from_str::(text).is_ok_and(|v| v.is_object()) { diff --git a/crates/socket-patch-core/src/patch/archive_limits.rs b/crates/socket-patch-core/src/patch/archive_limits.rs index a93a509230..010561ecb3 100644 --- a/crates/socket-patch-core/src/patch/archive_limits.rs +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -226,7 +226,7 @@ impl Budget { format!( "{unpacks_to}, over {} times its own size ({}) and the {} every archive may use", limits.max_inflate_ratio, - size(self.archive_len), + own_size(self.archive_len), size(limits.ratio_floor_bytes) ) } @@ -252,6 +252,29 @@ pub(crate) fn larger_on_disk(archive_len: u64, max: u64) -> String { ) } +/// The limits in words, for a message that states them. +pub(crate) fn summary() -> String { + format!( + "{MAX_ENTRIES} entries, or {} unpacked and {MAX_INFLATE_RATIO} times its own size", + size(MAX_INFLATED_BYTES) + ) +} + +/// An archive's own size, where an error states a multiple of it: to a +/// tenth of a MiB, rounded down. Rounded up to a whole MiB, an archive of +/// 1.2 MiB read as one of 2 MiB, whose allowance would be 200 MiB and not +/// the 120 MiB it was held to. +fn own_size(bytes: u64) -> String { + let (whole, rest) = (bytes / MIB, bytes % MIB); + if whole == 0 { + format!("{} KiB", bytes.div_ceil(KIB)) + } else if rest == 0 { + format!("{whole} MiB") + } else { + format!("{whole}.{} MiB", rest * 10 / MIB) + } +} + /// `bytes` rounded up to whole KiB below 1 MiB and to whole MiB above, so a /// size just past a limit never prints as the limit. fn size(bytes: u64) -> String { @@ -400,6 +423,24 @@ mod tests { "it unpacks to more than 1024 MiB, the limit for one archive" ); + // An archive's own size is shown to a tenth of a MiB, rounded + // down: one of 1.2 MiB is allowed 120 MiB, and is not "2 MiB". + let odd = limits.budget(MIB + 205 * KIB); + assert_eq!(odd.bytes(), 100 * (MIB + 205 * KIB)); + assert_eq!( + odd.exceeded(Unpacked::Declared(300 * MIB)), + "it unpacks to 300 MiB, over 100 times its own size (1.2 MiB) and the 64 MiB every \ + archive may use" + ); + assert_eq!(own_size(2 * MIB), "2 MiB"); + assert_eq!(own_size(2 * MIB - 1), "1.9 MiB"); + assert_eq!(own_size(80 * KIB), "80 KiB"); + // The limits in words are the constants. + assert_eq!( + summary(), + "200000 entries, or 1024 MiB unpacked and 100 times its own size" + ); + // A small archive is held to its own size. let small = limits.budget(65 * KIB); assert_eq!( diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 5b80aaa1aa..843e064c3f 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -164,18 +164,16 @@ pub fn read_archive_bytes_to_map_strict( read_archive_from_reader(bytes, &budget_of(bytes), true, true) } -/// [`read_archive_bytes_to_map`] keyed the way npm-family installers -/// extract a tarball: the first path segment stripped whatever its name -/// (`package/`, `left-pad-1.3.0/` from `git archive --prefix`, a GitHub -/// release's `-/`), where the lenient decoder strips only a -/// literal `package/` (#1516). A member that two different roots both -/// spell is dropped: which one the installer keeps depends on archive -/// order, which the map does not record. Members directly at the archive -/// root (no first segment to strip) are dropped too. -pub(crate) fn read_archive_bytes_to_map_any_root( - bytes: &[u8], -) -> Result>, ArchiveError> { - let raw = read_archive_from_reader(bytes, &budget_of(bytes), false, false)?; +/// The members `raw`, keyed by their whole paths, keyed the way +/// npm-family installers extract a tarball: the first path segment +/// stripped whatever its name (`package/`, `left-pad-1.3.0/` from +/// `git archive --prefix`, a GitHub release's `-/`), where the +/// lenient decoder strips only a literal `package/` (#1516). A member that +/// two different roots both spell is dropped: which one the installer +/// keeps depends on archive order, which the map does not record. Members +/// directly at the archive root (no first segment to strip) are dropped +/// too. +fn fold_any_root(raw: HashMap>) -> HashMap> { let mut out: HashMap> = HashMap::new(); let mut ambiguous: std::collections::HashSet = std::collections::HashSet::new(); let mut roots: HashMap = HashMap::new(); @@ -199,7 +197,7 @@ pub(crate) fn read_archive_bytes_to_map_any_root( } } } - Ok(out) + out } /// The first of `files` (package-relative paths, as a patch record keys @@ -357,17 +355,58 @@ fn read_archive_from_reader( // byte past the budget fails the read, and the walk with it: a reader // that only stopped there would hand the tar parser an end of input, // which between two entries reads as the end of the archive. + read_archive_from_reader_keeping(reader, budget, strict, strip_package_prefix, &|_| true) +} + +/// [`read_archive_from_reader`] that holds only the members `keep` takes, +/// by the key the map would give them. Every entry is still walked, and +/// counted and inflated within `budget`, so the outcome is the one of the +/// full read: the same error, or the same members less those not kept. +fn read_archive_from_reader_keeping( + reader: R, + budget: &Budget, + strict: bool, + strip_package_prefix: bool, + keep: &dyn Fn(&str) -> bool, +) -> Result>, ArchiveError> { let mut inflated = Bounded::new(GzDecoder::new(reader), budget); - let members = members_of_tar(&mut inflated, budget, strict, strip_package_prefix); + let members = members_of_tar(&mut inflated, budget, strict, strip_package_prefix, keep); within_budget(members, &inflated, budget) } +/// The member `name` of the npm tarball `bytes` as +/// [`read_archive_bytes_to_map`] holds it, and no other member. For a +/// caller that wants the manifest of a package: a tarball that unpacks to +/// 800 MiB is not held to read the name in its `package.json`. +pub fn read_archive_member(bytes: &[u8], name: &str) -> Result>, ArchiveError> { + let mut members = + read_archive_from_reader_keeping(bytes, &budget_of(bytes), false, true, &|key| { + key == name + })?; + Ok(members.remove(name)) +} + +/// [`read_archive_member`] of a tarball under any top-level directory +/// ([`fold_any_root`]). +pub(crate) fn read_archive_member_any_root( + bytes: &[u8], + name: &str, +) -> Result>, ArchiveError> { + let raw = read_archive_from_reader_keeping(bytes, &budget_of(bytes), false, false, &|key| { + key.trim_start_matches("./") + .split_once('/') + .is_some_and(|(_, rest)| rest.trim_start_matches('/') == name) + })?; + Ok(fold_any_root(raw).remove(name)) +} + /// [`read_archive_from_reader`] over the tar stream `inflated`. fn members_of_tar( inflated: R, budget: &Budget, strict: bool, strip_package_prefix: bool, + keep: &dyn Fn(&str) -> bool, ) -> Result>, ArchiveError> { let mut tar = Archive::new(inflated); @@ -501,7 +540,11 @@ fn members_of_tar( )); } - out.insert(normalized, read_member(&mut entry, size)?); + // A member that is not kept is not read: the walk passes over its + // content, which is inflated and counted all the same. + if keep(&normalized) { + out.insert(normalized, read_member(&mut entry, size)?); + } } Ok(out) @@ -1319,6 +1362,70 @@ mod tests { ); } + /// One member of a tarball is read as the member map holds it, and + /// the others are not held: a caller that wants a package's manifest + /// does not hold a package of 800 MiB for it. The walk is the same, so + /// the same tarballs fail, by the same errors. + #[test] + fn one_member_is_read_without_the_others() { + let big = crate::patch::archive_limits::noise(3 * MIB); + let tgz = raw_tar_gz(&[ + ("package/package.json", FILE, b"{\"name\":\"first\"}"), + ("package/big.bin", FILE, &big[..]), + ("package/package.json", FILE, b"{\"name\":\"last\"}"), + ]); + let whole = read_archive_bytes_to_map(&tgz).unwrap(); + assert_eq!(whole.len(), 2); + assert_eq!( + read_archive_member(&tgz, "package.json").unwrap().as_ref(), + whole.get("package.json") + ); + assert_eq!(whole["package.json"], b"{\"name\":\"last\"}"); + assert_eq!(read_archive_member(&tgz, "absent.js").unwrap(), None); + let kept = + read_archive_from_reader_keeping(&tgz[..], &budget_of(&tgz), false, true, &|key| { + key == "package.json" + }) + .unwrap(); + assert_eq!(kept.len(), 1, "the 3 MiB member is not held"); + + // Under another top-level directory, and under two of them. + let rooted = raw_tar_gz(&[ + ("left-pad-v1/package.json", FILE, b"{\"name\":\"rooted\"}"), + ("left-pad-v1/big.bin", FILE, &big[..]), + ]); + assert_eq!( + read_archive_member_any_root(&rooted, "package.json").unwrap(), + Some(b"{\"name\":\"rooted\"}".to_vec()) + ); + assert_eq!(read_archive_member(&rooted, "package.json").unwrap(), None); + let two_roots = raw_tar_gz(&[ + ("a/package.json", FILE, b"{}"), + ("b/package.json", FILE, b"{}"), + ]); + assert_eq!( + read_archive_member_any_root(&two_roots, "package.json").unwrap(), + None + ); + + // The limits hold for what is passed over: a member that is not + // kept, and declares more than the tarball may unpack to. + let mut over = raw_tar(&[("package/package.json", FILE, b"{}")]); + over.extend_from_slice(&ustar_block(b"package/big.bin", FILE, 80 * MIB as u64)); + let tgz = gzip(&over); + let full = read_archive_bytes_to_map(&tgz).unwrap_err(); + let one = read_archive_member(&tgz, "package.json").unwrap_err(); + assert!(full.is_too_large() && one.is_too_large(), "{full} / {one}"); + assert_eq!(full.to_string(), one.to_string()); + // And an entry that fails the read fails it for one member too. + let unsafe_path = raw_tar_gz(&[ + ("package/package.json", FILE, b"{}"), + ("/etc/passwd", FILE, b"x"), + ]); + assert!(read_archive_bytes_to_map(&unsafe_path).is_err()); + assert!(read_archive_member(&unsafe_path, "package.json").is_err()); + } + /// The size in a member's header is its author's claim. Before any of /// the content is read it reserves 128 KiB at most, however much the /// archive's budget would allow it, and the buffer then grows with what diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 8703edcc2b..b0c487d8dc 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -139,9 +139,9 @@ pub use state::{ LEDGER_GITIGNORED, VENDOR_STATE_REL, }; pub use verify::{ - artifact_is_file_shaped, check_vendored_artifact, compute_dir_inventory, - compute_package_dir_inventory, describe_artifact_failure, file_sha256_hex, - vendored_jar_versioned_copies, ArtifactHealth, VendoredJarCopies, + archive_limits_summary, artifact_is_file_shaped, check_vendored_artifact, + compute_dir_inventory, compute_package_dir_inventory, describe_artifact_failure, + file_sha256_hex, vendored_jar_versioned_copies, ArtifactHealth, VendoredJarCopies, }; // The hosted→vendored takeover refuses a berry project the backend would // refuse BEFORE it reverts the hosted redirect. @@ -630,31 +630,35 @@ fn fallback_scans_of(f: impl FnOnce() -> T) -> (T, usize) { /// entry the caps reject — falls back to an exhaustive index scan, which is /// what keeps the result identical to reading every entry: the name path only ever admits an entry whose hash IS one of /// the wanted ones, and the scan then supplies every hash still outstanding. +/// The entry's bytes, or `None` when either cap rejects it. +/// +/// SECURITY: `size` is only the archive-DECLARED uncompressed size; the +/// entry reader is bounded solely by the COMPRESSED size, so a zip bomb +/// can declare a tiny size (past the gate) yet decompress far beyond the +/// cap. Bound the decompressed read itself and drop any entry that +/// overflows, before its bytes are all in memory. +fn capped(size: u64, entry: &mut impl std::io::Read, most: u64) -> Option> { + use std::io::Read as _; + + if size > most { + return None; + } + // Nothing is reserved on the declared size. It is the archive's claim: + // up to what the whole archive may unpack to, for each of its entries, + // and a reservation the machine cannot make aborts the process. The + // buffer grows with what the entry inflates to. + let mut content = Vec::new(); + entry + .by_ref() + .take(most + 1) + .read_to_end(&mut content) + .ok()?; + (content.len() as u64 <= most).then_some(content) +} + fn harvest_zip_blobs(path: &Path, wanted: &[(String, String)]) -> HashMap> { use crate::hash::git_sha256::compute_git_sha256_from_bytes; - /// The entry's bytes, or `None` when either cap rejects it. - /// - /// SECURITY: `size` is only the archive-DECLARED uncompressed size; the - /// entry reader is bounded solely by the COMPRESSED size, so a zip bomb - /// can declare a tiny size (past the gate) yet decompress far beyond the - /// cap. Bound the decompressed read itself and drop any entry that - /// overflows, before its bytes are all in memory. - fn capped(size: u64, entry: &mut impl std::io::Read, most: u64) -> Option> { - use std::io::Read as _; - - if size > most { - return None; - } - let mut content = Vec::with_capacity(size as usize); - entry - .by_ref() - .take(most + 1) - .read_to_end(&mut content) - .ok()?; - (content.len() as u64 <= most).then_some(content) - } - let mut out: HashMap> = HashMap::new(); // The caller's metadata gate already refused a non-regular path; the // guarded opener refuses one swapped in since, so a FIFO planted between @@ -1396,6 +1400,22 @@ mod harvest_tests { std::fs::write(path, &bytes).unwrap(); } + /// The size a zip entry declares reserves nothing. Each entry of a + /// committed archive of eleven megabytes may declare a gigabyte, and a + /// reservation of that size that fails (a commit limit, `ulimit -v`) + /// aborts the process. The buffer holds what the entry inflates to. + #[test] + fn a_zip_entry_s_declared_size_reserves_nothing() { + let gib = 1024 * 1024 * 1024; + let content = capped(gib, &mut &b"ten bytes!"[..], gib).unwrap(); + assert_eq!(content, b"ten bytes!"); + assert!(content.capacity() < 64 * 1024, "{}", content.capacity()); + // Past the cap by what it declares, or by what it inflates to. + assert!(capped(9, &mut &[0u8; 4][..], 8).is_none()); + assert!(capped(4, &mut &[0u8; 9][..], 8).is_none()); + assert_eq!(capped(8, &mut &[0u8; 8][..], 8).map(|c| c.len()), Some(8)); + } + /// A patched member of more than the 64 MiB one member could be is /// harvested: a member may be as large as its archive may inflate to, /// which is a hundred times the archive's own size past 64 MiB. (A diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index f44da5de75..4cb7ca6ac0 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -172,7 +172,7 @@ pub async fn restore( // installer-shaped strictness of the wheel reader (ASCII names, // no case-colliding pair) refuses obfuscated jars that hold // both `a.class` and `A.class`, and that reader holds every - // member in memory, within half of what a jar may inflate to. + // member in memory. // The record's members are hashed within the jar limits. super::verify::verify_jar_bytes_members(&archive.bytes, &record.files).map_err( |(tag, why)| format!("{tag}: the downloaded jar cannot be verified: {why}"), diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 5f6d582de7..501ce2c2e0 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -9,8 +9,7 @@ //! (bounded by [`crate::patch::archive_limits`] — the artifacts are //! committed and tamper-able, so a crafted archive must not OOM an audit). //! A `.jar` has its record members hashed as they are inflated, within the -//! jar limits of [`crate::patch::jar_members`]: a jar may inflate to twice -//! what a reader that holds every member may. +//! same limits ([`crate::patch::jar_members`]), and is not held. //! //! Fail-closed order (each failure is a stable snake_case routing tag): //! `no_files` → `vendor_path_unsafe` → `vendor_uuid_mismatch` → @@ -724,6 +723,12 @@ fn unread_tag(tag: String) -> String { /// What to say of an archive past the limits when its reader's words are /// not at hand. +/// The limits an archive is read within, in words, for a message that +/// states them. +pub fn archive_limits_summary() -> String { + crate::patch::archive_limits::summary() +} + const PAST_THE_LIMITS: &str = "it holds or unpacks to more than an archive of its size may"; /// Which limit the archive `bytes` is past (`name` tells a tarball from a diff --git a/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs b/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs index ae02662fee..3b3b4e440d 100644 --- a/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs +++ b/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs @@ -420,9 +420,10 @@ impl NpmLockBackend for YarnBerryBackend { // resolver's implicit `node-gyp` dependency (#737). A tarball // without a readable manifest keeps the registry's fields (yarn // cannot install it either way). - let tarball_manifest = crate::patch::package::read_archive_bytes_to_map(&tgz_bytes) + let tarball_manifest = crate::patch::package::read_archive_member(&tgz_bytes, PACKAGE_JSON) .ok() - .and_then(|members| serde_json::from_slice::(members.get(PACKAGE_JSON)?).ok()) + .flatten() + .and_then(|manifest| serde_json::from_slice::(&manifest).ok()) .filter(Value::is_object); // The exact entry yarn 4 emits for a resolutions-driven `file:` // tarball (the B3 fixture shape), fields in yarn's order (#697). diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 0f3df40970..02bda84a64 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -1667,9 +1667,10 @@ async fn record_pnpm_file_copies( } Some(rel) => match ctx.read_advisory_bytes(&rel).await { Some(bytes) => tokio::task::spawn_blocking(move || { - let map = - crate::patch::package::read_archive_bytes_to_map(&bytes).ok()?; - serde_json::from_slice::(map.get("package.json")?).ok() + let manifest = + crate::patch::package::read_archive_member(&bytes, "package.json") + .ok()??; + serde_json::from_slice::(&manifest).ok() }) .await .ok() From 0eab05d79de8553c4fa08f3a3143162d73a0ccd3 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 17:30:19 -0500 Subject: [PATCH 11/13] Test the caps against ones a test can reach, and say how far a tarball is read The tests of the registry extractors' caps built their fixtures at the caps themselves, which was affordable at 128 MiB an entry and 60,000 entries. At 1 GiB and 200,000 the test of the total cap allocated a gigabyte, deflated it and inflated it in three extractors (6.5 s and 1 GiB resident here), the test of the per-entry cap another gigabyte, and the test of the entry count built two archives of 200,001 entries. The total-cap test had also lost its case: with one entry allowed to be as large as the whole, it tripped on its second entry. The extractors take their caps as one value now, which a test can set for its own thread, and those tests run against 64 KiB an entry, 256 KiB in all and 40 entries: each in a hundredth of a second. They test the boundary again, exactly at a cap (taken) and one past it (refused), and their comments say what they do. Two tests of the raise itself are scaled down the same way: a tarball of 520 MiB read for real (590 MiB resident) is a tarball read against the limits at a 1024th, and the module zip of 60,001 entries and one of 129 MiB is an entry as large as the whole against small caps. The real values are asserted beside them. Two statements are corrected. The check for a second entry over a patched file was said to judge every entry up to the end-of-archive marker; it reads what the decoder reads, one gzip member up to the first all-zero block, and the doc comment and the contract say so, with #2330 for what lies behind. And the usage guide listed jars among the archives that are held in memory; a jar is hashed file by file. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-core/src/patch/package.rs | 96 +++--- .../src/vendor/registry_fetch.rs | 275 ++++++++++++------ docs/usage.md | 7 +- 4 files changed, 253 insertions(+), 127 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8d8aad95ea..e46ea31308 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1676,7 +1676,7 @@ Coverage includes npm (all lock flavors), Python wheels and source distributions **Archive limits.** An npm tarball, a Python wheel or source distribution and a `.nupkg` are decoded in memory within fixed limits, counted on the bytes actually inflated and on the archive's own entry count (a size an archive declares only refuses it sooner): 200,000 entries, and per read of one archive 1 GiB unpacked and at most 100 times the archive's own size (an archive smaller than 655 KiB may still unpack to 64 MiB). For a tarball the bytes are those of the tar stream, each entry's 512-byte header and padding included. One file may be as large as what is left of its archive's allowance. What is unpacked is held in memory, so 1 GiB plus the archive itself is what checking one archive may take: an npm tarball of 17 MiB that unpacks to 1,000 MiB was measured at 1,079 MiB resident for `vendor`, 1,055 MiB for `vendor --check` and 1,059 MiB for `vex`. These are the limits wherever a package is read, unpacked or downloaded, so that one path does not refuse for its size what another takes: the registry extractors, which write to disk, unpack 200,000 entries and 1 GiB with no smaller limit on one entry (they were 60,000 entries, 512 MiB and 128 MiB for one entry: `@next/swc-linux-x64-gnu` holds a file of 136 MiB); a download is at most 256 MiB from the patch service and from a registry (a registry's was 128 MiB); the inventory of a committed directory covers 200,000 files (it was 10,000: the wheel of `ansible` 11.1.0 holds 21,105); a patched file recovered from a committed zip may be as large as that zip may unpack to (it was 64 MiB); and a jar has the same 200,000 entries, 1 GiB and 100 times its own size. -An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 1100 MiB, over the limit of 1024 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: no check vouches for a tarball it has not read to its end-of-archive marker, so a second entry for a patched file (`vendor_artifact_non_canonical`) cannot sit beyond a limit unseen. +An archive past a limit is `vendor_artifact_too_large`, and the detail names the limit and, where the archive's own headers say, the count it holds or the size it unpacks to: `it unpacks to 1100 MiB, over the limit of 1024 MiB for one archive`; `it unpacks to more than 64 MiB, over 100 times its own size (80 KiB) and the 64 MiB every archive may use`; `it holds 200001 entries, over the limit of 200000`. That is a refusal when vendoring a Python distribution; the failure detail when vendoring an npm package (`the patch service's tarball for @ cannot be checked: …`, under the `apply_failed` code its failures carry); the `vex` omission tag and the `vendor --check` reason for a committed artifact (`… is past the limits archives are read within: …`), which `repair` restores from the recorded one; and the error of a `repair` whose own download is past them. In hosted mode a served npm tarball past a limit skips its patch (`npm_tarball_unavailable` / `npm_manifest_unavailable`) with the same detail. A committed wheel, source distribution or npm tarball larger than 512 MiB on disk is not read at all and is too large as well (`it is 513 MiB on disk, over the 512 MiB a committed artifact is read up to`), and so is a tarball with a file the machine has no memory to hold (`it holds a member of 300 MiB, more than there is memory for`): the size a file's header declares reserves nothing before its content arrives. A limit that is met is always that error and never the end of the archive: the check for a second entry over a patched file (`vendor_artifact_non_canonical`) reads what the decoder reads, one gzip member up to the first all-zero block of its tar stream, and within that no entry sits beyond a limit unseen. Neither reads what follows that block, or a second gzip member, which some installers do (#2330). Measured on the registries, within the 256 MiB a download from the patch service may be: npm `onnxruntime-node` 1.20.1 unpacks to 180 MiB and `@mui/icons-material` 6.2.1 holds 31,858 files; PyPI `paddlepaddle` 2.6.2 unpacks to 430 MiB, `xgboost` 2.1.3 holds one file of 239 MiB, and `ansible` 11.1.0 holds 21,105 files. The two largest wheels measured within that download size are within the limit: `mkl` 2025.0.1 (521 MiB) and `tensorflow-cpu` 2.18.0 (946 MiB, 603 MiB of it one file). At the 512 MiB the limit was, both were refused. Jars are read without being held in memory and have limits of their own ([Vendored JVM support](#vendored-jvm-support-v5)). diff --git a/crates/socket-patch-core/src/patch/package.rs b/crates/socket-patch-core/src/patch/package.rs index 843e064c3f..618848c063 100644 --- a/crates/socket-patch-core/src/patch/package.rs +++ b/crates/socket-patch-core/src/patch/package.rs @@ -221,9 +221,12 @@ fn fold_any_root(raw: HashMap>) -> HashMap> { /// files: an upstream tarball with a link, a non-ASCII name or a case twin /// somewhere else still passes. /// -/// Every entry up to the tar end-of-archive marker is judged or the call -/// fails: a tarball past a limit is [`ArchiveError::TooLarge`], never one -/// whose entries beyond the limit went unseen. +/// The walk reads what the decoder reads: one gzip member, up to the first +/// all-zero block of its tar stream. Within that every entry is judged or +/// the call fails: a tarball past a limit is [`ArchiveError::TooLarge`], +/// never one whose entries beyond the limit went unseen. An entry behind +/// that block or in a second gzip member, which some installers read on +/// to, is seen by neither (#2330). pub(crate) fn shadowed_member( bytes: &[u8], files: &[String], @@ -1450,52 +1453,63 @@ mod tests { assert_eq!(bytes, content[..1000]); } - /// A tarball that unpacks to more than the 512 MiB the limit was is - /// read, and checked for a second entry: `mkl` 2025.0.1 unpacks to 521 - /// MiB. One that declares more than the 1 GiB the limit is fails by - /// that limit, before its content is read. + /// The whole-archive limit is 1 GiB, and was 512 MiB (`mkl` 2025.0.1 + /// unpacks to 521 MiB). Shown at a 1024th of both, since a tarball of + /// 520 MiB took 590 MiB to read here: one that unpacks to more than the + /// limit was is read and checked for a second entry, and one that + /// declares more than the limit is fails by that limit, before its + /// content is read. #[test] fn a_tarball_past_the_old_512_mib_limit_is_read() { - let filler = crate::patch::archive_limits::noise(6 * MIB); - let big = 520 * MIB as u64; - let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast())); - for (name, size) in [ - ("package/noise.bin", filler.len() as u64), - ("package/big.bin", big), - ] { - let mut header = tar::Header::new_gnu(); - header.set_path(name).unwrap(); - header.set_size(size); - header.set_mode(0o644); - header.set_cksum(); - if name.ends_with("noise.bin") { - builder.append(&header, &filler[..]).unwrap(); - } else { - builder - .append(&header, std::io::repeat(0x20).take(size)) - .unwrap(); - } - } - let tgz = builder.into_inner().unwrap().finish().unwrap(); - let files = vec!["package/big.bin".to_string()]; - assert_eq!(shadowed_member(&tgz, &files).unwrap(), None); - let decoded = read_archive_bytes_to_map(&tgz).unwrap(); - assert_eq!(decoded["big.bin"].len() as u64, big); - drop(decoded); - - // 11 MiB of the tarball's own, so that it may unpack to the limit, - // and a header that declares one byte more than is left of it. - let mut over = raw_tar(&[ + const KIB: u64 = 1024; + assert_eq!( + ArchiveLimits::IN_MEMORY.max_inflated_bytes, + 1024 * 1024 * KIB + ); + let scaled = |max_inflated_bytes: u64| ArchiveLimits { + max_inflated_bytes, + ratio_floor_bytes: 64 * KIB, + ..ArchiveLimits::IN_MEMORY + }; + let (was, is) = (scaled(512 * KIB), scaled(1024 * KIB)); + let read = |tgz: &[u8], limits: ArchiveLimits| { + read_archive_from_reader(tgz, &limits.budget(tgz.len() as u64), false, true) + }; + + // 8 KiB of the tarball's own, so that it may unpack to a hundred + // times that, and 512 KiB of one byte. + let filler = crate::patch::archive_limits::noise(8 * KIB as usize); + let tgz = raw_tar_gz(&[ ("package/noise.bin", FILE, &filler[..]), - ("package/more.bin", FILE, &filler[..5 * MIB]), + ( + "package/big.bin", + FILE, + &vec![0x20u8; 512 * KIB as usize][..], + ), ]); - over.extend_from_slice(&ustar_block(b"package/big.bin", FILE, 1024 * MIB as u64)); - let error = read_archive_bytes_to_map(&gzip(&over)).unwrap_err(); + let files = vec!["package/big.bin".to_string()]; + let budget = is.budget(tgz.len() as u64); + assert_eq!(shadowed_member_within(&tgz, &files, &budget).unwrap(), None); + assert_eq!(read(&tgz, is).unwrap()["big.bin"].len() as u64, 512 * KIB); + let refused = read(&tgz, was).unwrap_err(); + assert!( + refused + .to_string() + .contains("over the limit of 512 KiB for one archive"), + "{refused}" + ); + + // 11 KiB of the tarball's own, so that it may unpack to the limit, + // and a header that declares as much as the limit after them. + let more = crate::patch::archive_limits::noise(11 * KIB as usize); + let mut over = raw_tar(&[("package/noise.bin", FILE, &more[..])]); + over.extend_from_slice(&ustar_block(b"package/big.bin", FILE, 1024 * KIB)); + let error = read(&gzip(&over), is).unwrap_err(); assert!(error.is_too_large(), "{error}"); assert!( error .to_string() - .contains("over the limit of 1024 MiB for one archive"), + .contains("over the limit of 1 MiB for one archive"), "{error}" ); } diff --git a/crates/socket-patch-core/src/vendor/registry_fetch.rs b/crates/socket-patch-core/src/vendor/registry_fetch.rs index 363d7309ec..cf9bd09696 100644 --- a/crates/socket-patch-core/src/vendor/registry_fetch.rs +++ b/crates/socket-patch-core/src/vendor/registry_fetch.rs @@ -35,6 +35,39 @@ pub(crate) const MAX_TOTAL_DECOMPRESSED_BYTES: u64 = pub(crate) const MAX_ENTRY_BYTES: u64 = MAX_TOTAL_DECOMPRESSED_BYTES; pub(crate) const MAX_ENTRIES: usize = crate::patch::archive_limits::MAX_ENTRIES; +/// The caps of the extractors here as one value, so that a test can run +/// them against caps it can reach: at the real ones a fixture one byte past +/// a cap is a gigabyte of content. +#[derive(Clone, Copy)] +struct ExtractCaps { + entries: usize, + entry_bytes: u64, + total_bytes: u64, +} + +const EXTRACT_CAPS: ExtractCaps = ExtractCaps { + entries: MAX_ENTRIES, + entry_bytes: MAX_ENTRY_BYTES, + total_bytes: MAX_TOTAL_DECOMPRESSED_BYTES, +}; + +#[cfg(test)] +thread_local! { + /// The caps a test set for its own thread, where it set any. + static TEST_EXTRACT_CAPS: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// The caps an extraction is held to: [`EXTRACT_CAPS`], or under test the +/// ones the test set for its thread. +fn extract_caps() -> ExtractCaps { + #[cfg(test)] + if let Some(caps) = TEST_EXTRACT_CAPS.with(std::cell::Cell::get) { + return caps; + } + EXTRACT_CAPS +} + #[derive(Debug)] pub enum FetchError { /// The entry cannot be verified against the lockfile (no integrity @@ -383,10 +416,15 @@ fn plan_zip( strip_first: bool, skip_file_name: Option<&str>, ) -> Result { + let ExtractCaps { + entries: max_entries, + entry_bytes: max_entry_bytes, + total_bytes: max_total_bytes, + } = extract_caps(); let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)) .map_err(|e| format!("unreadable zip: {e}"))?; - if archive.len() > MAX_ENTRIES { - return Err(format!("zip exceeds {MAX_ENTRIES} entries")); + if archive.len() > max_entries { + return Err(format!("zip exceeds {max_entries} entries")); } let mut plan = ZipPlan { entries: Vec::new(), @@ -434,18 +472,18 @@ fn plan_zip( break; } let declared = file.size(); - if declared > MAX_ENTRY_BYTES { + if declared > max_entry_bytes { plan.header_refusal = Some(( i, - format!("zip entry `{rel_str}` is {declared} bytes (cap {MAX_ENTRY_BYTES})"), + format!("zip entry `{rel_str}` is {declared} bytes (cap {max_entry_bytes})"), )); break; } total += declared; - if total > MAX_TOTAL_DECOMPRESSED_BYTES { + if total > max_total_bytes { plan.header_refusal = Some(( i, - format!("zip decompresses past the {MAX_TOTAL_DECOMPRESSED_BYTES}-byte cap"), + format!("zip decompresses past the {max_total_bytes}-byte cap"), )); break; } @@ -779,11 +817,16 @@ fn go_glob_match(pattern: &[u8], name: &[u8]) -> bool { /// Runs in the ecosystem-agnostic service-download path whenever the /// service reports a `dirhashH1`. pub(crate) fn go_h1_of_zip(bytes: &[u8]) -> Result { + let ExtractCaps { + entries: max_entries, + entry_bytes: max_entry_bytes, + total_bytes: max_total_bytes, + } = extract_caps(); use std::io::Read as _; let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)) .map_err(|e| format!("unreadable module zip: {e}"))?; - if archive.len() > MAX_ENTRIES { - return Err(format!("module zip exceeds {MAX_ENTRIES} entries")); + if archive.len() > max_entries { + return Err(format!("module zip exceeds {max_entries} entries")); } let mut files: Vec<(String, String)> = Vec::new(); let mut total: u64 = 0; @@ -799,9 +842,9 @@ pub(crate) fn go_h1_of_zip(bytes: &[u8]) -> Result { return Err("module zip entry name contains a newline".to_string()); } let declared = file.size(); - if declared > MAX_ENTRY_BYTES { + if declared > max_entry_bytes { return Err(format!( - "module zip entry `{name}` is {declared} bytes (cap {MAX_ENTRY_BYTES})" + "module zip entry `{name}` is {declared} bytes (cap {max_entry_bytes})" )); } // The caps count ACTUAL decompressed bytes — the declared size is @@ -819,17 +862,17 @@ pub(crate) fn go_h1_of_zip(bytes: &[u8]) -> Result { break; } entry_bytes += n as u64; - if entry_bytes > MAX_ENTRY_BYTES { + if entry_bytes > max_entry_bytes { return Err(format!( - "module zip entry `{name}` decompresses past the {MAX_ENTRY_BYTES}-byte cap" + "module zip entry `{name}` decompresses past the {max_entry_bytes}-byte cap" )); } hasher.update(&buf[..n]); } total += entry_bytes; - if total > MAX_TOTAL_DECOMPRESSED_BYTES { + if total > max_total_bytes { return Err(format!( - "module zip decompresses past the {MAX_TOTAL_DECOMPRESSED_BYTES}-byte cap" + "module zip decompresses past the {max_total_bytes}-byte cap" )); } files.push((name, hex::encode(hasher.finalize()))); @@ -884,11 +927,16 @@ pub(crate) fn extract_zip_with_prefix_skipping( prefix: &str, skip_file_name: Option<&str>, ) -> Result<(), String> { + let ExtractCaps { + entries: max_entries, + entry_bytes: max_entry_bytes, + total_bytes: max_total_bytes, + } = extract_caps(); use std::io::Read as _; let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)) .map_err(|e| format!("unreadable module zip: {e}"))?; - if archive.len() > MAX_ENTRIES { - return Err(format!("module zip exceeds {MAX_ENTRIES} entries")); + if archive.len() > max_entries { + return Err(format!("module zip exceeds {max_entries} entries")); } let mut out = EntrySink::new(dest).skipping(skip_file_name); let mut total: u64 = 0; @@ -915,15 +963,15 @@ pub(crate) fn extract_zip_with_prefix_skipping( // path when the service reports no `dirhashH1`), so it must bound // itself. let declared = file.size(); - if declared > MAX_ENTRY_BYTES { + if declared > max_entry_bytes { return Err(format!( - "module zip entry `{name}` is {declared} bytes (cap {MAX_ENTRY_BYTES})" + "module zip entry `{name}` is {declared} bytes (cap {max_entry_bytes})" )); } total += declared; - if total > MAX_TOTAL_DECOMPRESSED_BYTES { + if total > max_total_bytes { return Err(format!( - "module zip decompresses past the {MAX_TOTAL_DECOMPRESSED_BYTES}-byte cap" + "module zip decompresses past the {max_total_bytes}-byte cap" )); } let mut target = out.open(Path::new(rel))?; @@ -1274,7 +1322,7 @@ fn walk_tar_gz( skip_file_name: Option<&str>, strict: bool, ) -> Result<(), String> { - let max_inflated = MAX_TOTAL_DECOMPRESSED_BYTES; + let max_inflated = extract_caps().total_bytes; walk_tar_gz_within( bytes, dest, @@ -1318,6 +1366,11 @@ fn walk_tar( skip_file_name: Option<&str>, strict: bool, ) -> Result<(), String> { + let ExtractCaps { + entries: max_entries, + entry_bytes: max_entry_bytes, + .. + } = extract_caps(); let mut archive = tar::Archive::new(inflated); let mut out = EntrySink::new(dest).skipping(skip_file_name); let mut count = 0usize; @@ -1327,8 +1380,8 @@ fn walk_tar( { let mut entry = entry.map_err(|e| format!("unreadable tarball entry: {e}"))?; count += 1; - if count > MAX_ENTRIES { - return Err(format!("tarball exceeds {MAX_ENTRIES} entries")); + if count > max_entries { + return Err(format!("tarball exceeds {max_entries} entries")); } // Regular files only: symlinks/hardlinks/devices never extract // (a symlink could redirect later entries out of the stage). @@ -1369,9 +1422,9 @@ fn walk_tar( )); } let size = entry.header().size().unwrap_or(u64::MAX); - if size > MAX_ENTRY_BYTES { + if size > max_entry_bytes { return Err(format!( - "tarball entry `{rel_str}` is {size} bytes (cap {MAX_ENTRY_BYTES})" + "tarball entry `{rel_str}` is {size} bytes (cap {max_entry_bytes})" )); } let mut target = out.open(&rel)?; @@ -1768,24 +1821,55 @@ mod tests { assert!(err.contains("declares"), "{err}"); } - /// A module zip of more entries than the 60,000 the cap was, one of - /// them larger than the 128 MiB one entry could be, is hashed: the caps - /// are the 200,000 entries and the 1 GiB one package may hold, and an - /// entry may be as large as the package. (`@mui/icons-material` holds - /// 31,858 entries and `@next/swc-linux-x64-gnu` one of 135.7 MiB.) + /// The extractors run `f` against `caps` on this thread. + fn with_caps(caps: ExtractCaps, f: impl FnOnce() -> T) -> T { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + TEST_EXTRACT_CAPS.with(|caps| caps.set(None)); + } + } + TEST_EXTRACT_CAPS.with(|set| set.set(Some(caps))); + let _reset = Reset; + f() + } + + /// Caps a fixture can reach: 64 KiB an entry, 256 KiB in all, 40 entries. + const SMALL_CAPS: ExtractCaps = ExtractCaps { + entries: 40, + entry_bytes: 64 * 1024, + total_bytes: 256 * 1024, + }; + + /// The caps are the one set every path holds a package to, and there is + /// no limit on one entry below what the package may unpack to: it was + /// 128 MiB, which refused the 135.7 MiB file of `@next/swc-linux-x64-gnu`. + /// An entry as large as the whole is taken, shown against small caps. #[test] - fn a_module_zip_past_the_old_caps_is_hashed() { + fn an_entry_may_be_as_large_as_the_package() { assert_eq!(MAX_ENTRIES, 200_000); assert_eq!(MAX_ENTRY_BYTES, 1024 * 1024 * 1024); assert_eq!(MAX_TOTAL_DECOMPRESSED_BYTES, MAX_ENTRY_BYTES); assert_eq!(MAX_DOWNLOAD_BYTES, 256 * 1024 * 1024); - let big = vec![0u8; 129 * 1024 * 1024]; - let names: Vec = (0..60_001).map(|i| format!("f{i}")).collect(); - let mut files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b""[..])).collect(); - files.push(("big.bin", &big)); - let zip_bytes = make_module_zip("m@v1/", &files); - let h1 = go_h1_of_zip(&zip_bytes).unwrap(); + assert_eq!(EXTRACT_CAPS.entry_bytes, EXTRACT_CAPS.total_bytes); + + let caps = ExtractCaps { + entry_bytes: SMALL_CAPS.total_bytes, + ..SMALL_CAPS + }; + let whole = vec![0u8; caps.total_bytes as usize]; + let zip_bytes = make_module_zip("m@v1/", &[("big.bin", &whole)]); + let h1 = with_caps(caps, || go_h1_of_zip(&zip_bytes)).unwrap(); assert!(h1.starts_with("h1:"), "{h1}"); + let tmp = tempfile::tempdir().unwrap(); + with_caps(caps, || { + extract_zip_with_prefix(&zip_bytes, tmp.path(), "m@v1/") + }) + .unwrap(); + // Against the caps as they were in proportion, an entry of a + // quarter of the whole at most, the same zip is refused. + let err = with_caps(SMALL_CAPS, || go_h1_of_zip(&zip_bytes)).unwrap_err(); + assert!(err.contains("cap"), "{err}"); } #[test] @@ -1793,13 +1877,18 @@ mod tests { // A module zip whose entry DECLARES a tiny size while its deflate // stream inflates past the per-entry cap must refuse instead of // hashing unbounded decompressed bytes (a capped download can still - // inflate ~1000×; the declared-size checks alone are bypassable). - let big = vec![0u8; (MAX_ENTRY_BYTES + 64 * 1024) as usize]; + // inflate ~1000x; the declared-size checks alone are bypassable). + // Run against a small cap: at the real one this was a gigabyte of + // zeros, allocated, deflated and inflated. + let big = vec![0u8; (SMALL_CAPS.entry_bytes + 4096) as usize]; let mut zip_bytes = make_module_zip("m@v1/", &[("big.bin", &big)]); - drop(big); patch_declared_uncompressed_size(&mut zip_bytes, 4096); - let err = go_h1_of_zip(&zip_bytes).unwrap_err(); + let err = with_caps(SMALL_CAPS, || go_h1_of_zip(&zip_bytes)).unwrap_err(); assert!(err.contains("cap"), "{err}"); + // An entry of exactly the cap is hashed. + let at_the_cap = vec![0u8; SMALL_CAPS.entry_bytes as usize]; + let zip_bytes = make_module_zip("m@v1/", &[("big.bin", &at_the_cap)]); + with_caps(SMALL_CAPS, || go_h1_of_zip(&zip_bytes)).unwrap(); } #[test] @@ -2035,11 +2124,13 @@ mod tests { #[test] fn entry_count_caps_fail_closed() { - // 60,001 empty entries: the zip caps refuse up front (archive.len() + // One entry more than the cap, run against a cap of 40 (at the real + // one this built two archives of 200,001 entries): the zip caps + // refuse up front (archive.len() // is header data), the tar cap refuses during iteration. Entries are // empty/dir-typed so the fixtures stay small and nothing extracts. let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - for i in 0..=MAX_ENTRIES { + for i in 0..=SMALL_CAPS.entries { writer .start_file( format!("m@v1/f{i}"), @@ -2050,13 +2141,16 @@ mod tests { } let zip_bytes = writer.finish().unwrap().into_inner(); let tmp = tempfile::tempdir().unwrap(); - let err = extract_zip(&zip_bytes, tmp.path(), false).unwrap_err(); + let err = with_caps(SMALL_CAPS, || extract_zip(&zip_bytes, tmp.path(), false)).unwrap_err(); assert!(err.contains("entries"), "{err}"); assert!(std::fs::read_dir(tmp.path()).unwrap().next().is_none()); - let err = go_h1_of_zip(&zip_bytes).unwrap_err(); + let err = with_caps(SMALL_CAPS, || go_h1_of_zip(&zip_bytes)).unwrap_err(); assert!(err.contains("entries"), "{err}"); let tmp = tempfile::tempdir().unwrap(); - let err = extract_zip_with_prefix(&zip_bytes, tmp.path(), "m@v1/").unwrap_err(); + let err = with_caps(SMALL_CAPS, || { + extract_zip_with_prefix(&zip_bytes, tmp.path(), "m@v1/") + }) + .unwrap_err(); assert!(err.contains("entries"), "{err}"); // Tar twin: dir-typed entries count toward the cap without any @@ -2065,7 +2159,7 @@ mod tests { Vec::new(), flate2::Compression::fast(), )); - for i in 0..=MAX_ENTRIES { + for i in 0..=SMALL_CAPS.entries { let mut header = tar::Header::new_gnu(); header.set_entry_type(tar::EntryType::Directory); header.set_size(0); @@ -2077,8 +2171,15 @@ mod tests { } let tgz = builder.into_inner().unwrap().finish().unwrap(); let tmp = tempfile::tempdir().unwrap(); - let err = extract_tgz(&tgz, tmp.path()).unwrap_err(); + let err = with_caps(SMALL_CAPS, || extract_tgz(&tgz, tmp.path())).unwrap_err(); assert!(err.contains("entries"), "{err}"); + + // At the cap, not past it. + let names: Vec = (0..SMALL_CAPS.entries).map(|i| format!("f{i}")).collect(); + let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b""[..])).collect(); + let at_the_cap = make_module_zip("m@v1/", &files); + with_caps(SMALL_CAPS, || go_h1_of_zip(&at_the_cap)).unwrap(); + assert_eq!(EXTRACT_CAPS.entries, 200_000); } #[test] @@ -3063,47 +3164,57 @@ mod tests { #[test] fn total_decompressed_cap_fails_closed_across_zip_extractors() { // The per-entry actual-bytes guards mean only HONEST content reaches - // the total cap: four entries of exactly MAX_ENTRY_BYTES land the - // running total exactly ON the 512 MB cap, and a fifth 1-byte entry - // pushes past it — the cheapest honest fixture that trips the check. - // (The suite's most expensive test: ~512 MB of zeros deflate once, - // and each extractor inflates them back before refusing entry 5.) + // the total cap: four entries of exactly the entry cap land the + // running total exactly ON the total cap, which every extractor + // takes, and a fifth 1-byte entry pushes past it. Run against small + // caps (64 KiB an entry, 256 KiB in all): at the real ones, where + // an entry may be as large as the whole, this was a gigabyte of + // zeros deflated once and inflated by each extractor. use std::io::Write as _; - let zeros = vec![0u8; MAX_ENTRY_BYTES as usize]; - let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - for i in 0..4 { - writer - .start_file( - format!("m@v1/z{i}.bin"), - zip::write::SimpleFileOptions::default() - .compression_method(zip::CompressionMethod::Deflated), - ) - .unwrap(); - writer.write_all(&zeros).unwrap(); - } - drop(zeros); - writer - .start_file( - "m@v1/tip.bin", - zip::write::SimpleFileOptions::default() - .compression_method(zip::CompressionMethod::Deflated), - ) - .unwrap(); - writer.write_all(b"x").unwrap(); - let bytes = writer.finish().unwrap().into_inner(); + let zip_of = |tip: bool| { + let zeros = vec![0u8; SMALL_CAPS.entry_bytes as usize]; + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let mut names: Vec = (0..4).map(|i| format!("m@v1/z{i}.bin")).collect(); + if tip { + names.push("m@v1/tip.bin".to_string()); + } + for name in names { + let content = if name.ends_with("tip.bin") { + &b"x"[..] + } else { + &zeros[..] + }; + writer + .start_file( + name, + zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated), + ) + .unwrap(); + writer.write_all(content).unwrap(); + } + writer.finish().unwrap().into_inner() + }; + with_caps(SMALL_CAPS, || { + // Exactly at the cap: every extractor takes it. + let at_the_cap = zip_of(false); + let tmp = tempfile::tempdir().unwrap(); + extract_zip(&at_the_cap, tmp.path(), /*strip_first=*/ false).unwrap(); + let tmp = tempfile::tempdir().unwrap(); + extract_zip_with_prefix(&at_the_cap, tmp.path(), "m@v1/").unwrap(); + go_h1_of_zip(&at_the_cap).unwrap(); - { + // One byte past it. + let bytes = zip_of(true); let tmp = tempfile::tempdir().unwrap(); let err = extract_zip(&bytes, tmp.path(), /*strip_first=*/ false).unwrap_err(); assert!(err.contains("decompresses past"), "{err}"); - } - { let tmp = tempfile::tempdir().unwrap(); let err = extract_zip_with_prefix(&bytes, tmp.path(), "m@v1/").unwrap_err(); assert!(err.contains("decompresses past"), "{err}"); - } - // The dirhash pre-pass counts ACTUAL decompressed bytes, in memory. - let err = go_h1_of_zip(&bytes).unwrap_err(); - assert!(err.contains("decompresses past"), "{err}"); + // The dirhash pre-pass counts ACTUAL decompressed bytes, in memory. + let err = go_h1_of_zip(&bytes).unwrap_err(); + assert!(err.contains("decompresses past"), "{err}"); + }); } } diff --git a/docs/usage.md b/docs/usage.md index 94c1e084e7..1f2fbead3e 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -209,9 +209,10 @@ artifacts can be reused offline; new artifacts require the patch service. For changes to v4's local artifact building, see the [migration guide](migrating-to-v5.md#service-only-vendoring). Archives are read within fixed limits. An npm tarball, a Python wheel or source -distribution, a `.nupkg` or a jar may hold 200,000 entries and unpack to 1 GiB, and to -no more than 100 times its own size once past 64 MiB. What is unpacked is held in -memory, beside the archive. +distribution or a `.nupkg` may hold 200,000 entries and unpack to 1 GiB, and to +no more than 100 times its own size once past 64 MiB; what is unpacked is held in +memory, beside the archive. A jar has the same limits and is not held: its files +are hashed one by one as they are unpacked. A package past a limit is not vendored, and a committed one fails `vendor --check` and is left out by `vex` (`vendor_artifact_too_large`). The message names the limit and what the archive unpacks to. From cb1d99d0de344ecf1f746fc50572ecafd2dc474d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:19:04 +0000 Subject: [PATCH 12/13] Put the doc comment of PAST_THE_LIMITS back above it It sat above archive_limits_summary(), so the public function's rustdoc opened with the constant's sentence. Also join a jar comment in redownload.rs that was split across two blocks. Comments only. Assisted-by: Claude Code:claude-opus-5-5 --- crates/socket-patch-core/src/vendor/redownload.rs | 4 ++-- crates/socket-patch-core/src/vendor/verify.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 4cb7ca6ac0..cd42688c3d 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -172,8 +172,8 @@ pub async fn restore( // installer-shaped strictness of the wheel reader (ASCII names, // no case-colliding pair) refuses obfuscated jars that hold // both `a.class` and `A.class`, and that reader holds every - // member in memory. - // The record's members are hashed within the jar limits. + // member in memory. The record's members are hashed within the jar + // limits. super::verify::verify_jar_bytes_members(&archive.bytes, &record.files).map_err( |(tag, why)| format!("{tag}: the downloaded jar cannot be verified: {why}"), )?; diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 501ce2c2e0..8892a38e7d 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -721,14 +721,14 @@ fn unread_tag(tag: String) -> String { } } -/// What to say of an archive past the limits when its reader's words are -/// not at hand. /// The limits an archive is read within, in words, for a message that /// states them. pub fn archive_limits_summary() -> String { crate::patch::archive_limits::summary() } +/// What to say of an archive past the limits when its reader's words are +/// not at hand. const PAST_THE_LIMITS: &str = "it holds or unpacks to more than an archive of its size may"; /// Which limit the archive `bytes` is past (`name` tells a tarball from a From 301a39490c884cee3f1c3f6292b9df84b00ca0fe Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:29:54 +0000 Subject: [PATCH 13/13] Put the doc comment of harvest_zip_blobs back above it Moving capped out of harvest_zip_blobs left harvest_zip_blobs' doc comment above capped. Comment-only move. Assisted-by: Claude Code:claude-opus-5-5 --- crates/socket-patch-core/src/vendor/mod.rs | 24 +++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index b0c487d8dc..ab34d0a59a 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -618,18 +618,6 @@ fn fallback_scans_of(f: impl FnOnce() -> T) -> (T, usize) { (out, FALLBACK_SCANS.with(std::cell::Cell::get)) } -/// One zip-shaped committed artifact's contribution to the harvest: the -/// blobs whose git-sha256 is one of the `(record key, afterHash)` pairs in -/// `wanted`. Synchronous — the caller runs it on the blocking pool. -/// -/// A zip is addressable by member name and `wanted`'s keys ARE the member -/// names (modulo the `package/` prefix a manifest key may carry), so the -/// common case costs one seek and one inflate per needed hash instead of -/// inflating the whole archive. Everything the name lookup does not settle — -/// a member renamed since the patch was exported, a duplicate name, an -/// entry the caps reject — falls back to an exhaustive index scan, which is -/// what keeps the result identical to reading every entry: the name path only ever admits an entry whose hash IS one of -/// the wanted ones, and the scan then supplies every hash still outstanding. /// The entry's bytes, or `None` when either cap rejects it. /// /// SECURITY: `size` is only the archive-DECLARED uncompressed size; the @@ -656,6 +644,18 @@ fn capped(size: u64, entry: &mut impl std::io::Read, most: u64) -> Option HashMap> { use crate::hash::git_sha256::compute_git_sha256_from_bytes;