diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9ac66ac818..595ba693f1 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1812,6 +1812,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 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: 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)). + 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. @@ -2703,7 +2709,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` / `unreadable_file_mode` / `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` / `unreadable_file_mode` / `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` / `unreadable_file_mode` | `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; a file entry whose `mode` this release cannot read, see "File permissions as part of a patch"). 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 abb10e166f..fac342b07c 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2860,9 +2860,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 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 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-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:#}" + ); +} diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index c82a44209f..571ee770d3 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -2402,7 +2402,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/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 new file mode 100644 index 0000000000..010561ecb3 --- /dev/null +++ b/crates/socket-patch-core/src/patch/archive_limits.rs @@ -0,0 +1,533 @@ +//! 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`: 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. +//! 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 +//! 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 +//! 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; + +// 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 { + /// 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: 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 + /// 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); + 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, + own_size(self.archive_len), + size(limits.ratio_floor_bytes) + ) + } + } +} + +/// 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) + ) +} + +/// 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 { + 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); + // 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); + assert_eq!(extractor.budget(0).bytes(), 4000); + assert_eq!(extractor.budget(u64::MAX).bytes(), 4000); + } + + #[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 1 GiB. + let capped = limits.budget(220 * MIB); + assert_eq!( + 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(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 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!( + 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" + ); + + 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. + 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 6b2b970fc2..4711e1f82f 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. @@ -76,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)] @@ -1120,8 +1121,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 68f3264480..25950a4c3c 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -1682,10 +1682,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; @@ -1693,7 +1693,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 18de081b0c..0eea4ad812 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..618848c063 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,21 +161,19 @@ 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 -/// 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, 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(); @@ -178,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 @@ -201,9 +220,60 @@ 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. +/// +/// 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], +) -> 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 +297,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 +340,78 @@ 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. + 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, 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> { - // 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 +421,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,31 +530,74 @@ 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* 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(); - 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. - let mut bytes = Vec::with_capacity(size as usize); - entry.read_to_end(&mut bytes)?; - out.insert(normalized, bytes); + // 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) } +/// 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 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 +/// `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::*; + use crate::patch::archive_limits::noise; use flate2::write::GzEncoder; use flate2::Compression; use std::io::Write; @@ -837,20 +998,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 +1202,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 +1247,270 @@ 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. + // 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 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_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("many.tar.gz"); - let entries: Vec> = (0..(MAX_ENTRIES + 1)) - .map(|i| raw_entry(format!("f{i}").as_bytes(), 0, b"")) + 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}"); - let err = read_archive_to_map(&archive).unwrap_err(); + // 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!( - matches!(err, ArchiveError::TooManyEntries(_)), - "expected TooManyEntries, got {:?}", - err + why.starts_with("it unpacks to more than 64 MiB, over 100 times its own size ("), + "{why}" ); } + /// 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 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). - let dir = tempfile::tempdir().unwrap(); - let archive = dir.path().join("bomb.tar.gz"); + 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 + ); - // 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]); + // 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()); + } - 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 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]); + } + + /// 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() { + 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/big.bin", + FILE, + &vec![0x20u8; 512 * KIB as usize][..], + ), + ]); + 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 1 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 d721d61b4c..a25c5580d6 100644 --- a/crates/socket-patch-core/src/vendor/cargo.rs +++ b/crates/socket-patch-core/src/vendor/cargo.rs @@ -2467,12 +2467,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(); @@ -2483,12 +2482,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 5deb859cbc..60e29f93a6 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -261,7 +261,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 bf9cdc7c30..3e68c0a7db 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -4220,12 +4220,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(); @@ -4237,12 +4237,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)) @@ -4250,7 +4253,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 12c3d1c142..a1b4b3abb3 100644 --- a/crates/socket-patch-core/src/vendor/golang.rs +++ b/crates/socket-patch-core/src/vendor/golang.rs @@ -1063,11 +1063,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(); @@ -1078,12 +1078,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/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 52502d99e2..57fb44dd67 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -4855,8 +4855,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] @@ -4868,7 +4868,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/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 1c6e687ca2..f7713d0df6 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -140,9 +140,9 @@ pub use state::{ 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. @@ -441,11 +441,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. @@ -573,7 +585,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; } @@ -607,6 +619,32 @@ fn fallback_scans_of(f: impl FnOnce() -> T) -> (T, usize) { (out, FALLBACK_SCANS.with(std::cell::Cell::get)) } +/// 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) +} + /// 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. @@ -622,28 +660,6 @@ fn fallback_scans_of(f: impl FnOnce() -> T) -> (T, usize) { 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) -> Option> { - use std::io::Read as _; - - if size > MAX_FILE_BYTES { - return None; - } - let mut content = Vec::with_capacity(size as usize); - entry - .by_ref() - .take(MAX_FILE_BYTES + 1) - .read_to_end(&mut content) - .ok()?; - (content.len() as u64 <= MAX_FILE_BYTES).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 @@ -651,6 +667,7 @@ fn harvest_zip_blobs(path: &Path, wanted: &[(String, String)]) -> HashMap HashMap HashMap {} + 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 8418be8974..9e13a8d6be 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 10d8b8a5ca..923fb65db9 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. 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/registry_fetch.rs b/crates/socket-patch-core/src/vendor/registry_fetch.rs index 6520840f8f..cf9bd09696 100644 --- a/crates/socket-patch-core/src/vendor/registry_fetch.rs +++ b/crates/socket-patch-core/src/vendor/registry_fetch.rs @@ -18,16 +18,55 @@ 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. -pub(crate) const MAX_DOWNLOAD_BYTES: u64 = 128 * 1024 * 1024; +/// 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. They are the one set every path that handles a package +/// holds it to (`patch::archive_limits`): a download is held in memory, and +/// an extractor holds one 64 KiB buffer beside it, so the unpacked bytes +/// bound the disk an extraction may fill. There is no separate limit on one +/// entry: `@next/swc-linux-x64-gnu` holds one of 135.7 MiB and +/// `tensorflow_cpu` one of 603.3 MiB. +pub(crate) const MAX_DOWNLOAD_BYTES: u64 = crate::patch::archive_limits::MAX_DOWNLOAD_BYTES; // `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 // one set of caps rather than carrying a copy that can drift. -pub(crate) const MAX_TOTAL_DECOMPRESSED_BYTES: u64 = 512 * 1024 * 1024; -pub(crate) const MAX_ENTRY_BYTES: u64 = 128 * 1024 * 1024; -pub(crate) const MAX_ENTRIES: usize = 60_000; +pub(crate) const MAX_TOTAL_DECOMPRESSED_BYTES: u64 = + crate::patch::archive_limits::MAX_INFLATED_BYTES; +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 { @@ -377,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(), @@ -428,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; } @@ -773,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; @@ -793,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 @@ -813,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()))); @@ -878,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; @@ -909,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))?; @@ -1268,9 +1322,56 @@ 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 = extract_caps().total_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 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; for entry in archive @@ -1279,8 +1380,8 @@ fn walk_tar_gz( { 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). @@ -1321,9 +1422,9 @@ fn walk_tar_gz( )); } 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)?; @@ -1446,6 +1547,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!( @@ -1678,18 +1821,74 @@ mod tests { assert!(err.contains("declares"), "{err}"); } + /// 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 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); + 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] fn go_h1_caps_actual_decompressed_bytes() { // 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] @@ -1925,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}"), @@ -1940,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 @@ -1955,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); @@ -1967,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] @@ -2953,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/crates/socket-patch-core/src/vendor/reuse.rs b/crates/socket-patch-core/src/vendor/reuse.rs index a74f883b02..5d9c15efee 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 78899d696a..93fdcd46b5 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -6,11 +6,10 @@ //! `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 +//! 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` → @@ -39,17 +38,13 @@ use crate::patch::apply::{ is_missing_path, is_safe_relative_subpath, normalize_file_path, verify_file_content, 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 @@ -179,7 +174,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 @@ -192,18 +187,19 @@ 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(|_| "vendor_artifact_unreadable".to_string()) + super::pypi_distribution::read_members(&bytes, &name).map_err(unread_tag) }) .await .map_err(|e| e.to_string())??; @@ -293,24 +289,24 @@ 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) => {} 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) } @@ -732,10 +728,57 @@ 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() + } +} + +/// 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 +/// 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() @@ -808,9 +851,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 @@ -820,7 +863,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 @@ -836,30 +879,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()); } @@ -879,10 +956,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(); @@ -890,12 +972,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); } @@ -905,12 +987,13 @@ fn read_zip_to_map( /// 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, mirroring the zip reader's entry cap — a +/// 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 = 10_000; +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 @@ -936,18 +1019,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 || { @@ -987,10 +1071,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}"))?; @@ -1237,6 +1319,34 @@ 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: 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 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) + .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. @@ -2557,7 +2667,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" ); } @@ -2854,61 +2964,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_zip_within(std::io::Cursor::new(&at_limit[..]), &budget, true) + .unwrap() + .len(), + 50, + "a wheel at exactly the entry limit still reads" + ); assert_eq!( - read_wheel_to_map(&at_cap).unwrap().len(), - MAX_WHEEL_ENTRIES, - "a wheel at exactly the entry cap still reads" + 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()) ); } @@ -2983,27 +3321,32 @@ 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 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(); @@ -3028,21 +3371,62 @@ 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) - .await - .is_err(), - "member verification also refuses oversized archives" + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec).await, + Err("vendor_artifact_too_large".to_string()) ); - // …and only the whole-file arm catches it: file_sha256_hex bails - // on the size cap, so the recorded sha is unverifiable. + let health = check_vendored_artifact(root, &ent, &rec).await; assert_eq!( - check_vendored_artifact(root, &ent, &rec).await, + health, ArtifactHealth::Corrupt { - reason: "vendor_artifact_unreadable".to_string() + reason: "vendor_artifact_too_large".to_string() } ); + assert_eq!( + describe_artifact_failure(root, &ent, &health) + .await + .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" + ) + ); + } + + /// 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!( + 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}" + ); } } 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 8c5d54ec22..2fa889aef9 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 1046861426..e60109bf3a 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -1827,9 +1827,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() diff --git a/docs/usage.md b/docs/usage.md index 5480da62fb..1f2fbead3e 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -208,6 +208,15 @@ 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 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. + `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.