From bfe8bbcb455649233111223f230e41c599d11430 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 19:30:33 -0500 Subject: [PATCH 1/7] Let a patch fix a package's file permissions in agent mode A release can ship its files world-writable and be fixed by a repack with the same content (octopoller 0.2.0, GHSA-26qj-cr27-r5c4). Hosted and vendored installs already get the patched archive's modes. An in-place apply kept the installer's mode bit for bit, and a fix with no content change could not be recorded at all. A file entry of a patch record may now carry `mode` ("0644", "0755"), also when its content is unchanged (`beforeHash` equal to `afterHash`): - The mode is an upper bound on write bits. A file is patched when its content hashes to `afterHash` and it has no group-write or other-write bit the mode lacks. Nothing else of the file's mode is read or changed. - `apply` clears exactly those bits through the usual stage and rename, and reports the file with `appliedVia: "permissions"`. It needs no blob for a file that already holds the patched bytes. - `apply --check`, `vex` and the hosted stale-install check judge an installed copy by the same rule. A committed vendored artifact is judged by its content alone, as before. - `rollback` and `remove` restore content only and keep the tightened mode. - A `mode` in a spelling this release cannot read fails only its own patch (`unreadable_file_mode`): the manifest still loads, every other patch works, and the value is written back as it was read. Records without a `mode` behave exactly as before, and their manifests serialize byte for byte as before. Patch requests now carry `capabilities=file-modes`, so the patch service can keep such entries from releases that would read unchanged content as "already patched". A service that does not know the parameter ignores it. Needs a matching change in Socket's backend before any patch carries a mode. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 55 +- .../src/commands/agent_download.rs | 1 + crates/socket-patch-cli/src/commands/apply.rs | 18 +- .../src/commands/fetch_stage.rs | 1 + .../src/commands/gem_refresh.rs | 2 + crates/socket-patch-cli/src/commands/get.rs | 1 + crates/socket-patch-cli/src/commands/list.rs | 2 + .../socket-patch-cli/src/commands/rollback.rs | 6 + .../src/commands/scan/discovery.rs | 3 + .../src/commands/scan/hosted.rs | 1 + .../src/commands/scan/hosted/python.rs | 1 + .../socket-patch-cli/src/commands/vendor.rs | 2 + crates/socket-patch-cli/src/commands/vex.rs | 5 + .../src/commands/vex_sources.rs | 1 + crates/socket-patch-cli/src/json_envelope.rs | 4 + crates/socket-patch-cli/tests/cli/list_tty.rs | 7 +- .../socket-patch-cli/tests/cli/prompts_tty.rs | 14 +- .../socket-patch-cli/tests/cli_parse_list.rs | 3 + .../tests/e2e_embedded_vex.rs | 1 + .../tests/e2e_gradle_discovery_build.rs | 1 + crates/socket-patch-cli/tests/e2e_vex.rs | 1 + .../tests/e2e_vex_grype_config.rs | 1 + .../tests/e2e_vex_lockfile/bun.rs | 1 + .../tests/e2e_vex_lockfile/cargo.rs | 1 + .../tests/e2e_vex_lockfile/composer.rs | 1 + .../tests/e2e_vex_lockfile/deno.rs | 1 + .../tests/e2e_vex_lockfile/golang.rs | 1 + .../tests/e2e_vex_lockfile/maven.rs | 1 + .../tests/e2e_vex_lockfile/nuget.rs | 1 + .../tests/e2e_vex_lockfile/poetry.rs | 1 + .../tests/e2e_vex_lockfile/uv.rs | 1 + .../tests/e2e_vex_lockfile/yarn.rs | 1 + .../tests/e2e_vex_redirect.rs | 1 + .../socket-patch-cli/tests/e2e_vex_vendor.rs | 1 + .../tests/in_process_redirect.rs | 1 + .../tests/in_process_rollback_hosted.rs | 2 + .../socket-patch-cli/tests/vex/vex_fixture.rs | 1 + .../socket-patch-core/src/api/blob_fetcher.rs | 1 + crates/socket-patch-core/src/api/client.rs | 71 ++- crates/socket-patch-core/src/api/types.rs | 9 + .../maven_crawler/scala_cache_tests.rs | 1 + .../src/manifest/cleanup_blobs.rs | 3 + .../src/manifest/operations.rs | 4 + .../socket-patch-core/src/manifest/records.rs | 64 ++ .../socket-patch-core/src/manifest/schema.rs | 240 ++++++++ crates/socket-patch-core/src/patch/apply.rs | 343 ++++++++++- .../src/patch/apply_file_mode_tests.rs | 556 ++++++++++++++++++ .../socket-patch-core/src/patch/conda_copy.rs | 2 + crates/socket-patch-core/src/patch/gem_ext.rs | 12 + .../src/patch/jar_manifest.rs | 4 + crates/socket-patch-core/src/patch/jvm_jar.rs | 12 +- .../src/patch/redirect/golang_local.rs | 3 + .../src/patch/redirect/state.rs | 1 + .../socket-patch-core/src/patch/rollback.rs | 54 ++ .../src/patch/store_copies.rs | 1 + .../src/utils/purl_key_nuget_vendor_tests.rs | 1 + .../src/vendor/bun_binary.rs | 1 + .../socket-patch-core/src/vendor/bun_lock.rs | 4 + crates/socket-patch-core/src/vendor/cargo.rs | 2 + crates/socket-patch-core/src/vendor/common.rs | 10 + .../src/vendor/composer_lock.rs | 2 + crates/socket-patch-core/src/vendor/gem.rs | 4 + .../src/vendor/go_native_vendor.rs | 1 + crates/socket-patch-core/src/vendor/golang.rs | 1 + .../src/vendor/maven_repo.rs | 1 + crates/socket-patch-core/src/vendor/mod.rs | 4 + .../src/vendor/npm_common.rs | 4 + .../src/vendor/npm_flavor.rs | 1 + .../socket-patch-core/src/vendor/npm_lock.rs | 5 + .../src/vendor/nuget_feed.rs | 1 + .../socket-patch-core/src/vendor/pnpm_lock.rs | 3 + .../src/vendor/pnpm_lock/rush.rs | 1 + .../src/vendor/pnpm_lock_legacy.rs | 3 + .../socket-patch-core/src/vendor/prestage.rs | 1 + crates/socket-patch-core/src/vendor/pypi.rs | 1 + crates/socket-patch-core/src/vendor/reuse.rs | 1 + .../src/vendor/service_fetch.rs | 1 + crates/socket-patch-core/src/vendor/state.rs | 1 + crates/socket-patch-core/src/vendor/verify.rs | 44 +- .../socket-patch-core/src/vendor/vlt_lock.rs | 4 + .../src/vendor/yarn_berry_lock.rs | 3 + .../src/vendor/yarn_classic_lock.rs | 5 + .../src/vendor/yarn_layering_tests.rs | 1 + crates/socket-patch-core/src/vex/build.rs | 1 + .../src/vex/conformance_tests.rs | 1 + crates/socket-patch-core/src/vex/verify.rs | 170 +++++- .../socket-patch-core/tests/api_retry_e2e.rs | 9 +- .../tests/blob_fetcher_edges_e2e.rs | 1 + .../tests/crawler_gradle_e2e.rs | 1 + .../tests/crawler_npm_e2e.rs | 3 + .../tests/rollback_new_file_e2e.rs | 7 + crates/socket-patch-core/tests/vlt_locks.rs | 1 + crates/socket-patch-node/npm/index.d.ts | 2 +- .../src/schema/manifest-schema.test.ts | 31 + .../src/schema/manifest-schema.ts | 8 + 95 files changed, 1802 insertions(+), 72 deletions(-) create mode 100644 crates/socket-patch-core/src/patch/apply_file_mode_tests.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 4fb98ba4f3..da0878c451 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -147,6 +147,53 @@ explicit consent for file drift and additionally skips missing files, but a is not a merge: the replaced local content is not kept for rollback. Vendoring commits the service artifact without merging installed changes. +**File permissions as part of a patch.** A file entry of a patch record may +carry a `mode`: `0` and three octal digits (`"0644"`, `"0755"`), the file's +permission bits in the patched package. It marks a fix that includes the +file's permissions, and such an entry may leave the content as it is +(`beforeHash` equal to `afterHash`): a release that shipped its files +world-writable is fixed by the bits alone. Entries without a `mode`, which is +every entry of a patch that fixes content only, are handled exactly as before. + +- The mode is an upper bound on write bits, never a mode to set. A file is + patched when its content hashes to `afterHash` **and** it has no group-write + or other-write bit the mode lacks. Read, execute, owner-write, setuid, + setgid and sticky bits are never looked at or changed, so a read-only + (`0444`) or owner-only (`0600`) copy satisfies `"0644"` as it is. +- `apply` (and the apply step of agent-mode `get` / `scan`) clears exactly the + excess bits, through the same stage and rename as a content change: a file + that is hard-linked into a store keeps its other links untouched. A file + that already holds the patched bytes is replaced with the bytes it holds; it + is reported in `files` with `appliedVia: "permissions"`, and needs no blob. +- Every command that asks whether an installed copy is patched uses the same + rule (`apply --check`, `vex`, the hosted stale-install check): a file with + the patched bytes and an excess write bit is not applied yet. A committed + vendored artifact is judged by its content alone, as before: this tool + wrote its files with the modes the patched archive gives them, and the bits + git checks out afterwards follow the umask. +- `rollback` and `remove` restore content only. They never give back a write + bit a patch cleared, so a rolled-back file keeps the tightened mode, and an + entry whose content the patch did not change has nothing to restore. +- Off Unix a file has no such bits and a `mode` changes nothing. +- A `mode` in any other spelling, or any other JSON value, is one this release + cannot read. It fails only the patch it belongs to. The manifest (or the + API response) still loads, every other patch works as before, and the value + is written back exactly as it was read. A file with such an entry cannot be + checked, so its patch is never reported as applied: `apply` fails it with + `errorCode: unreadable_file_mode` before writing any of its files, under + `--force` as well, and `apply --check` and `vex` report the same code. + `rollback`, `remove`, and hosted and vendored use of the patch do not read + the `mode` and work as for any other patch. +- A release that predates `mode` ignores it and reads an entry with unchanged + content as already patched. The patch service therefore sends such entries + only to a client that names the `file-modes` capability (see + [API client construction](#api-client-construction)). That does not cover a + manifest shared with an older release: any of its commands that saves the + manifest writes every entry back without its `mode`, and the record then + reads as applied to every release, this one included, until it is removed + and downloaded again. A project whose manifest holds a `mode` must not be + driven by a release that predates it. + ## Existing project patches **Release classification: fix (shipped in 5.1.0).** This tightens the default @@ -2315,6 +2362,8 @@ Building the API client is what reads the token, prints the client's stderr advi Telemetry does not build it: see [Telemetry](#telemetry) for the route a client-less run reports on. +Every patch request (`view`, `by-package`, `by-cve`, `by-ghsa`, `batch`, `package`, on the org API and the public proxy alike) carries the query parameter `capabilities`, a comma-separated list of what this release reads in a patch record beyond its file hashes. Its one value so far is `file-modes` (a file entry may carry a `mode`; see "File permissions as part of a patch"). A service that does not know the parameter ignores it. + ### Registry override env vars Env-only knobs used for hosted upstream restoration and JVM metadata verification. They do not enable local artifact construction. Trailing slashes are trimmed and empty values use the default. @@ -2421,7 +2470,7 @@ command's integration tests check its output. { "path": "package/index.js", "verified": true, - "appliedVia": "blob" // only on action=applied; v5.0 drops "package" and "diff" + "appliedVia": "blob" | "permissions" // only on action=applied; v5.0 drops "package" and "diff". "permissions": the file held the patched bytes and lost the write bits its entry's `mode` does not grant } ], "bytes": 1234, // only on the GC carrier event and --update's downloaded @@ -2541,8 +2590,8 @@ command's integration tests check its output. | `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. | | `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. | | `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. | -| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large` (jars): the committed jar is past the limits jars are read within (see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact that `repair` restores from the recorded jar). `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). | -| `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. The `no_matching_variant` reason says that `apply` leaves such a copy as it is, and for a gem names `bundle pristine ` and the `apply` to run after it. | +| `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"). | +| `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. | | `lockfile_unreadable` / `lockfile_unparseable` / `patched_ref_invalid` / `patched_ref_unattributable` | run-level `warnings[]` | vex (every form): lockfile-discovery diagnostics — see "Manifest-less VEX (lockfile discovery)". Never flip the exit on their own. | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 4d5926dcf2..6add7e9cdf 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -302,6 +302,7 @@ pub(crate) fn files_with_both_hashes(patch: &PatchResponse) -> HashMap &'static str { "not_applied" => "patch not applied (an installed copy is still unpatched)", "hash_mismatch" => "an installed copy matches neither the original nor the patched bytes", "file_not_found" => "a patched file is missing from an installed copy", + "unreadable_file_mode" => { + "the patch record gives a file a mode this release of socket-patch cannot read \ + (a newer release may read it)" + } "no_files" => "the patch record lists no files to verify", "native_extension_not_rebuilt" => { "the patched native-extension sources were not compiled into the extension \ @@ -1170,7 +1174,12 @@ fn all_files_already_patched(result: &ApplyResult) -> bool { pub(crate) fn variant_matches_installed(first_file_status: Option<&VerifyStatus>) -> bool { match first_file_status { None => true, - Some(status) => *status == VerifyStatus::Ready || *status == VerifyStatus::AlreadyPatched, + // `UnreadableMode` is a file whose content matches: the variant + // is the installed one, and applying it reports the mode. + Some(status) => matches!( + status, + VerifyStatus::Ready | VerifyStatus::AlreadyPatched | VerifyStatus::UnreadableMode + ), } } @@ -3065,6 +3074,7 @@ fn print_verbose_verification(results: &[ApplyResult]) { VerifyStatus::AlreadyPatched => "already patched", VerifyStatus::HashMismatch => "hash mismatch", VerifyStatus::NotFound => "not found", + VerifyStatus::UnreadableMode => "unreadable file mode", }; println!(" {} [{}]", f.file, status_str); if let Some(ref msg) = f.message { @@ -5309,6 +5319,7 @@ mod tests { current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }], files_patched: vec!["package/index.js".to_string()], applied_via, @@ -5588,6 +5599,7 @@ mod tests { current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }) .collect(); ApplyResult { @@ -5685,6 +5697,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "1".repeat(64), + mode: None, }, ); // Content-modifying file whose beforeHash does NOT match the @@ -5695,6 +5708,7 @@ mod tests { PatchFileInfo { before_hash: "2".repeat(64), after_hash: "3".repeat(64), + mode: None, }, ); @@ -5721,6 +5735,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "1".repeat(64), + mode: None, }, ); assert!(representative_file(&files).is_none()); @@ -6555,6 +6570,7 @@ mod tests { PatchFileInfo { before_hash: "1".repeat(64), after_hash: "2".repeat(64), + mode: None, }, ); let result = tokio::time::timeout( diff --git a/crates/socket-patch-cli/src/commands/fetch_stage.rs b/crates/socket-patch-cli/src/commands/fetch_stage.rs index e4d9f0f39b..115ca21537 100644 --- a/crates/socket-patch-cli/src/commands/fetch_stage.rs +++ b/crates/socket-patch-cli/src/commands/fetch_stage.rs @@ -271,6 +271,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: HASH.to_string(), + mode: None, }, ); let mut manifest = PatchManifest::new(); diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 5c3f61d959..032a20f284 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1835,6 +1835,7 @@ mod tests { hash(before) }, after_hash: hash(after), + mode: None, }; (name.to_string(), info) }) @@ -2249,6 +2250,7 @@ mod tests { PatchFileInfo { before_hash: git_sha(b"upstream\n"), after_hash: git_sha(after.as_bytes()), + mode: None, }, )] .into(), diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index c418c32af0..4a78c747e7 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -4104,6 +4104,7 @@ mod tests { socket_blob: None, blob_content: None, before_blob_content: None, + mode: None, } } diff --git a/crates/socket-patch-cli/src/commands/list.rs b/crates/socket-patch-cli/src/commands/list.rs index 5a3d302745..37744c22f0 100644 --- a/crates/socket-patch-cli/src/commands/list.rs +++ b/crates/socket-patch-cli/src/commands/list.rs @@ -1192,6 +1192,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: "a".repeat(64), + mode: None, }, ); @@ -1506,6 +1507,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: "a".repeat(64), + mode: None, }, ); } diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 1d045b4b2f..a34211785c 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -5028,6 +5028,7 @@ mod tests { after_hash: socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes( b"patched by A", ), + mode: None, }, )]); let target = CopyTarget::plain("pkg:npm/foo@1.0.0", tmp.path()); @@ -5281,6 +5282,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.to_string(), after_hash: "after".to_string(), + mode: None, }, ); rec.files = files; @@ -6482,6 +6484,7 @@ mod tests { PatchFileInfo { before_hash: index_before_hash.clone(), after_hash: index_after_hash.clone(), + mode: None, }, ); rec.files.insert( @@ -6489,6 +6492,7 @@ mod tests { PatchFileInfo { before_hash: lib_before_hash.clone(), after_hash: lib_after_hash.clone(), + mode: None, }, ); let mut patches = HashMap::new(); @@ -6584,6 +6588,7 @@ mod tests { PatchFileInfo { before_hash: index_before_hash.clone(), after_hash: index_after_hash, + mode: None, }, ); rec.files.insert( @@ -6591,6 +6596,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), // created-by-patch sentinel after_hash: created_hash, + mode: None, }, ); let mut patches = HashMap::new(); diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 478df431a3..f3eb1e1cf7 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -458,6 +458,7 @@ pub(super) async fn preverify_vendor_baselines( PatchFileInfo { before_hash: info.before_hash.clone().unwrap_or_default(), after_hash: info.after_hash.clone().unwrap_or_default(), + mode: None, }, ) }) @@ -2734,6 +2735,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: "c".repeat(64), + mode: None, }, )]), vulnerabilities: HashMap::new(), @@ -2898,6 +2900,7 @@ mod tests { PatchFileInfo { before_hash: "0".repeat(64), after_hash: "1".repeat(64), + mode: None, }, )]), vulnerabilities: HashMap::new(), diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 33f77b8645..4ed4ac8aa3 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -4505,6 +4505,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-cli/src/commands/scan/hosted/python.rs b/crates/socket-patch-cli/src/commands/scan/hosted/python.rs index 3f3071adf2..08459e3b6d 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted/python.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted/python.rs @@ -344,6 +344,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"upstream"), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, )] .into(), diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1c2af7c4fe..153b9a2810 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -6037,6 +6037,7 @@ mod plan_gate_tests { PatchFileInfo { before_hash: "1".repeat(64), after_hash: "2".repeat(64), + mode: None, }, )]), vulnerabilities: HashMap::new(), @@ -6540,6 +6541,7 @@ mod variant_probe_tests { PatchFileInfo { before_hash: (*before).to_string(), after_hash: (*after).to_string(), + mode: None, }, ) }) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..66b2843be7 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2795,6 +2795,10 @@ fn omission_phrase(reason: &str) -> &'static str { "not_applied" => "the patched files still hold the original content", "hash_mismatch" => "a patched file matches neither the original nor the patched content", "file_not_found" => "a patched file is missing", + "unreadable_file_mode" => { + "the patch record gives a file a mode this release of socket-patch cannot read, so \ + the file cannot be checked; a newer release may read it" + } "no_files" => "the patch record lists no files", "vendor_hash_mismatch" => "the vendored artifact does not match the patch", "go_vendor_content_mismatch" => "the native Go vendor tree does not contain the patch; run go mod vendor (or go work vendor for a workspace)", @@ -3870,6 +3874,7 @@ mod npm_prior_tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, )]), vulnerabilities: HashMap::from([( diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index f650a8199f..2ab76dcf60 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -1426,6 +1426,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "a".repeat(64), + mode: None, }, )] .into_iter() diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index e399cb2917..1bf8ffef09 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -535,6 +535,9 @@ pub enum PatchAction { #[serde(rename_all = "camelCase")] pub enum AppliedVia { Blob, + /// The file held the patched bytes; the write bits its entry's `mode` + /// does not grant were cleared. + Permissions, } impl AppliedVia { @@ -542,6 +545,7 @@ impl AppliedVia { use socket_patch_core::patch::apply::AppliedVia as Core; match via { Core::Blob => AppliedVia::Blob, + Core::Permissions => AppliedVia::Permissions, } } } diff --git a/crates/socket-patch-cli/tests/cli/list_tty.rs b/crates/socket-patch-cli/tests/cli/list_tty.rs index 452c68feff..43227bb556 100644 --- a/crates/socket-patch-cli/tests/cli/list_tty.rs +++ b/crates/socket-patch-cli/tests/cli/list_tty.rs @@ -505,9 +505,10 @@ fn list_fills_its_rows_in_from_the_patch_service() { let requests = rt.block_on(mock.received_requests()).unwrap_or_default(); assert_eq!(requests.len(), 2, "{requests:#?}"); assert!( - requests - .iter() - .all(|r| r.url.query() == Some("include_blobs=false")), + requests.iter().all(|r| r + .url + .query_pairs() + .any(|(key, value)| key == "include_blobs" && value == "false")), "{requests:#?}" ); } diff --git a/crates/socket-patch-cli/tests/cli/prompts_tty.rs b/crates/socket-patch-cli/tests/cli/prompts_tty.rs index 391f833e79..3c5b0197e6 100644 --- a/crates/socket-patch-cli/tests/cli/prompts_tty.rs +++ b/crates/socket-patch-cli/tests/cli/prompts_tty.rs @@ -184,7 +184,7 @@ async fn received_paths(mock: &MockServer) -> Vec { .await .expect("wiremock must record received requests") .iter() - .filter(|r| r.url.query() != Some("include_blobs=false")) + .filter(|r| !is_summary_request(r)) .map(|r| r.url.path().to_string()) .collect() } @@ -197,13 +197,23 @@ async fn measured_uuids(mock: &MockServer) -> Vec { .await .expect("wiremock must record received requests") .iter() - .filter(|r| r.url.query() == Some("include_blobs=false")) + .filter(|r| is_summary_request(r)) .filter_map(|r| r.url.path().rsplit('/').next().map(str::to_string)) .collect(); uuids.sort(); uuids } +/// Whether `request` asks for a view without its file content: the +/// `include_blobs=false` parameter, beside whatever else the query carries +/// (every patch request also names the client's capabilities). +fn is_summary_request(request: &wiremock::Request) -> bool { + request + .url + .query_pairs() + .any(|(key, value)| key == "include_blobs" && value == "false") +} + /// A single-file patch-view `files` map that survives the "patch has /// no applicable files" guardrail: one net-new file with an all-zero /// `beforeHash`, a real git-blob `afterHash`, and matching base64 diff --git a/crates/socket-patch-cli/tests/cli_parse_list.rs b/crates/socket-patch-cli/tests/cli_parse_list.rs index c25878af94..45e31eeffe 100644 --- a/crates/socket-patch-cli/tests/cli_parse_list.rs +++ b/crates/socket-patch-cli/tests/cli_parse_list.rs @@ -95,6 +95,7 @@ fn populated_manifest() -> PatchManifest { .to_string(), after_hash: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1111" .to_string(), + mode: None, }, ); @@ -599,6 +600,7 @@ fn multi_manifest() -> PatchManifest { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); } @@ -952,6 +954,7 @@ fn hosted_record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: "c".repeat(64), after_hash: "d".repeat(64), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_embedded_vex.rs b/crates/socket-patch-cli/tests/e2e_embedded_vex.rs index 058482b826..7bca847f20 100644 --- a/crates/socket-patch-cli/tests/e2e_embedded_vex.rs +++ b/crates/socket-patch-cli/tests/e2e_embedded_vex.rs @@ -70,6 +70,7 @@ fn make_record( PatchFileInfo { before_hash: before_hash.to_string(), after_hash: after_hash.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_gradle_discovery_build.rs b/crates/socket-patch-cli/tests/e2e_gradle_discovery_build.rs index ce5a2bd5e3..aedd7fb6a6 100644 --- a/crates/socket-patch-cli/tests/e2e_gradle_discovery_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gradle_discovery_build.rs @@ -578,6 +578,7 @@ fn gradle_agent_349_scan_finds_gradle_cache() { PatchFileInfo { before_hash: "x".into(), after_hash: "y".into(), + mode: None, }, )]); let copies = gradle_cache::installed_copies_detailed(&version_dir, &files); diff --git a/crates/socket-patch-cli/tests/e2e_vex.rs b/crates/socket-patch-cli/tests/e2e_vex.rs index be00d13397..5cd3538653 100644 --- a/crates/socket-patch-cli/tests/e2e_vex.rs +++ b/crates/socket-patch-cli/tests/e2e_vex.rs @@ -79,6 +79,7 @@ fn make_record( PatchFileInfo { before_hash: before_hash.to_string(), after_hash: after_hash.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs b/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs index 1dac9a6c26..162401c0c2 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs @@ -25,6 +25,7 @@ fn write_manifest(cwd: &Path, purls: &[&str]) { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bun.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bun.rs index bdbffaa9c0..e96c1bfc6c 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bun.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bun.rs @@ -1091,6 +1091,7 @@ fn write_ledger_record(cwd: &Path, uuid: &str) { PatchFileInfo { before_hash: git(PRISTINE), after_hash: git(PATCHED), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/cargo.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/cargo.rs index 7fc847b18b..aa5877ee42 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/cargo.rs @@ -275,6 +275,7 @@ fn record(uuid: &str, file: &str, before: &[u8], after: &[u8]) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/composer.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/composer.rs index 8fad683d4c..4d786f6ee8 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/composer.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/composer.rs @@ -330,6 +330,7 @@ fn record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: git_sha256(BEFORE), after_hash: git_sha256(AFTER), + mode: None, }, ); let mut vulns = std::collections::HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/deno.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/deno.rs index c466b72aa6..634db8951a 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/deno.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/deno.rs @@ -141,6 +141,7 @@ fn record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ) }) diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/golang.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/golang.rs index da02645f8e..bc3ca83757 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/golang.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/golang.rs @@ -284,6 +284,7 @@ fn record(uuid: &str, file: &str, before: &[u8], after: &[u8]) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs index c762a6f1e5..1ff1c9c31f 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs @@ -314,6 +314,7 @@ fn record(uuid: &str, files: &[(&str, &[u8], &[u8])]) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ) }) diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/nuget.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/nuget.rs index a3a9835398..1493b96983 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/nuget.rs @@ -295,6 +295,7 @@ fn record(uuid: &str, files: &[(&str, &[u8], &[u8])]) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ) }) diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/poetry.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/poetry.rs index 90bbb4a647..8ecdada187 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/poetry.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/poetry.rs @@ -367,6 +367,7 @@ fn record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/uv.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/uv.rs index fec6fd71d6..1835196341 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/uv.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/uv.rs @@ -477,6 +477,7 @@ fn record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/yarn.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/yarn.rs index cf64027e9d..be4fb6f2bd 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/yarn.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/yarn.rs @@ -375,6 +375,7 @@ fn record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index f981d445c1..200579caf3 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -111,6 +111,7 @@ fn make_record(uuid: &str, after_hash: &str, vuln_id: &str, cves: &[&str]) -> Pa PatchFileInfo { before_hash: "a".repeat(64), after_hash: after_hash.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs index 0efc064f9d..2a57d9bd67 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs @@ -74,6 +74,7 @@ fn make_record( PatchFileInfo { before_hash: "a".repeat(64), after_hash: after_hash.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/in_process_redirect.rs b/crates/socket-patch-cli/tests/in_process_redirect.rs index 789afee3c0..2c0f52a246 100644 --- a/crates/socket-patch-cli/tests/in_process_redirect.rs +++ b/crates/socket-patch-cli/tests/in_process_redirect.rs @@ -343,6 +343,7 @@ fn npm_record(uuid: &str, before: &str, after: &str, ghsa: &str) -> PatchRecord PatchFileInfo { before_hash: before.to_string(), after_hash: after.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-cli/tests/in_process_rollback_hosted.rs b/crates/socket-patch-cli/tests/in_process_rollback_hosted.rs index 323b9c5987..f76211714c 100644 --- a/crates/socket-patch-cli/tests/in_process_rollback_hosted.rs +++ b/crates/socket-patch-cli/tests/in_process_rollback_hosted.rs @@ -394,6 +394,7 @@ fn patch_record(uuid: &str, ghsa: &str) -> PatchRecord { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); let mut vulns = HashMap::new(); @@ -1545,6 +1546,7 @@ async fn write_superseded_agent_fixture( PatchFileInfo { before_hash: before.clone(), after_hash: after, + mode: None, }, ); let mut manifest = socket_patch_core::manifest::schema::PatchManifest::new(); diff --git a/crates/socket-patch-cli/tests/vex/vex_fixture.rs b/crates/socket-patch-cli/tests/vex/vex_fixture.rs index cbc99b9435..6422785ef9 100644 --- a/crates/socket-patch-cli/tests/vex/vex_fixture.rs +++ b/crates/socket-patch-cli/tests/vex/vex_fixture.rs @@ -55,6 +55,7 @@ pub(crate) fn make_record( PatchFileInfo { before_hash: before_hash.to_string(), after_hash: after_hash.to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-core/src/api/blob_fetcher.rs b/crates/socket-patch-core/src/api/blob_fetcher.rs index 6d7e796fc8..bf88855b46 100644 --- a/crates/socket-patch-core/src/api/blob_fetcher.rs +++ b/crates/socket-patch-core/src/api/blob_fetcher.rs @@ -569,6 +569,7 @@ mod tests { PatchFileInfo { before_hash: format!("before{}{:06}", "0".repeat(58), i), after_hash: ah.to_string(), + mode: None, }, ); } diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index fb137ea93f..4a2d5856a9 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -27,6 +27,25 @@ use crate::utils::redact::{redact_url, redact_urls_in}; use crate::utils::socket_cli_config; use crate::utils::target::is_uuid_shaped; +/// What this release reads in a patch record beyond the hashes of its +/// files, as the value of the `capabilities` query parameter every patch +/// request carries (a comma-separated list). +/// +/// `file-modes`: a file entry may carry a `mode`, and may then leave the +/// file's content as it is (see +/// [`FileMode`](crate::manifest::schema::FileMode)). The service sends +/// such entries only to a client that names the capability: a release +/// without it would read an entry whose content is unchanged as already +/// patched, whatever the file's permission bits are. +pub const CAPABILITIES: &str = "file-modes"; + +/// `url` (a path or a full URL, with or without a query) with the +/// `capabilities` parameter added. +fn with_capabilities(url: &str) -> String { + let separator = if url.contains('?') { '&' } else { '?' }; + format!("{url}{separator}capabilities={CAPABILITIES}") +} + // Each client advisory prints at most once per process: commands build // several clients (telemetry, discovery, download) in one run. static PROXY_NOTICE_SHOWN: AtomicBool = AtomicBool::new(false); @@ -1022,10 +1041,10 @@ impl ApiClient { /// place the route picks the path for the JSON family /// (`get_json`/`post_json` prefix `api_url`). fn patches_path(&self, suffix: &str) -> String { - match &self.route { + with_capabilities(&match &self.route { ApiRoute::Org { slug } => format!("/v0/orgs/{slug}/patches/{suffix}"), ApiRoute::Proxy => format!("/patch/{suffix}"), - } + }) } // ── Public API methods ──────────────────────────────────────────── @@ -1302,7 +1321,7 @@ impl ApiClient { &self, purls: &[String], ) -> Result, ApiError> { - let url = format!("{}/patch/batch", self.api_url); + let url = with_capabilities(&format!("{}/patch/batch", self.api_url)); let body = BatchSearchBody::new(purls); // Held until this call returns, response body read. @@ -1889,10 +1908,11 @@ impl ApiClient { Some(v) => v.trim_end_matches('/'), None => self.api_url.as_str(), }; - match &self.route { + let (url, authenticated) = match &self.route { ApiRoute::Org { slug } => (format!("{base}/v0/orgs/{slug}/patches/package"), true), ApiRoute::Proxy => (format!("{base}/patch/package"), false), - } + }; + (with_capabilities(&url), authenticated) } /// The retry hint for a vendor-service answer with this `status`: @@ -3969,6 +3989,19 @@ mod tests { assert!(reason.contains("stored hash format"), "{reason}"); } + /// The capabilities parameter joins a query the path already has. + #[test] + fn capabilities_are_added_to_a_path_with_or_without_a_query() { + assert_eq!( + with_capabilities("/patch/batch"), + "/patch/batch?capabilities=file-modes" + ); + assert_eq!( + with_capabilities("/v0/orgs/acme/patches/view/u?include_blobs=false"), + "/v0/orgs/acme/patches/view/u?include_blobs=false&capabilities=file-modes" + ); + } + /// Every URL a run builds — patch view, batch search, blob, diff, /// vendor package reference and telemetry — follows the one route the /// client was built with: all org-scoped with the bearer, or all @@ -3997,6 +4030,15 @@ mod tests { client.vendor_package_url(None).0, TelemetryAuth::for_client(client).url().to_string(), ]; + // Every patch request names what this release reads in a + // record; a blob, a diff and telemetry are not patch records. + for (i, url) in urls.iter().enumerate() { + assert_eq!( + url.ends_with("?capabilities=file-modes"), + matches!(i, 0 | 1 | 4), + "{case}: {url}" + ); + } let auth = [ client.binary_url("blob", HASH).1, client.binary_url("diff", UUID).1, @@ -4755,7 +4797,10 @@ mod tests { .await; let (url, use_auth) = client.vendor_package_url(None); assert!(!use_auth, "no org → unauthenticated proxy request"); - assert_eq!(url, "https://proxy.example.test/patch/package"); + assert_eq!( + url, + "https://proxy.example.test/patch/package?capabilities=file-modes" + ); } #[test] @@ -4765,7 +4810,10 @@ mod tests { let client = proxy_client("https://custom.proxy.example"); let (url, use_auth) = client.vendor_package_url(None); assert!(!use_auth); - assert_eq!(url, "https://custom.proxy.example/patch/package"); + assert_eq!( + url, + "https://custom.proxy.example/patch/package?capabilities=file-modes" + ); } #[test] @@ -4777,7 +4825,10 @@ mod tests { }); let (url, use_auth) = client.vendor_package_url(None); assert!(use_auth); - assert_eq!(url, "https://api.socket.dev/v0/orgs/my-org/patches/package"); + assert_eq!( + url, + "https://api.socket.dev/v0/orgs/my-org/patches/package?capabilities=file-modes" + ); } #[test] @@ -4790,12 +4841,12 @@ mod tests { }); assert_eq!( auth.vendor_package_url(Some("http://localhost:9099/")).0, - "http://localhost:9099/v0/orgs/my-org/patches/package" + "http://localhost:9099/v0/orgs/my-org/patches/package?capabilities=file-modes" ); let no_org = proxy_client("https://patches-api.socket.dev"); assert_eq!( no_org.vendor_package_url(Some("http://localhost:9099")).0, - "http://localhost:9099/patch/package" + "http://localhost:9099/patch/package?capabilities=file-modes" ); } diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index cbb947141e..432b3e5d41 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -1,6 +1,8 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use crate::manifest::schema::FileMode; + use crate::patch::redirect::{Integrity, RegistryOverride}; /// Organization info returned by the `/v0/organizations` endpoint. @@ -178,6 +180,13 @@ pub struct PatchFileResponse { pub socket_blob: Option, pub blob_content: Option, pub before_blob_content: Option, + /// The file's permissions are part of the fix (see [`FileMode`]). Sent + /// only to a client that asked for it + /// ([`CAPABILITIES`](crate::api::client::CAPABILITIES)). A spelling + /// this release cannot read fails the whole view: the entry could not + /// be checked, so the patch is not one to record. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler/scala_cache_tests.rs b/crates/socket-patch-core/src/crawlers/maven_crawler/scala_cache_tests.rs index 0ec3b1185d..59e2ff17a1 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler/scala_cache_tests.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler/scala_cache_tests.rs @@ -447,6 +447,7 @@ fn installed_copies_expands_an_ivy_artifact_dir() { let info = |h: &str| PatchFileInfo { before_hash: h.repeat(64), after_hash: h.repeat(64), + mode: None, }; let files: HashMap = [ ("package/lib-1.jar", "a"), diff --git a/crates/socket-patch-core/src/manifest/cleanup_blobs.rs b/crates/socket-patch-core/src/manifest/cleanup_blobs.rs index ecd36b415e..3e9602b908 100644 --- a/crates/socket-patch-core/src/manifest/cleanup_blobs.rs +++ b/crates/socket-patch-core/src/manifest/cleanup_blobs.rs @@ -303,6 +303,7 @@ mod tests { PatchFileInfo { before_hash: BEFORE_HASH_1.to_string(), after_hash: AFTER_HASH_1.to_string(), + mode: None, }, ); files.insert( @@ -310,6 +311,7 @@ mod tests { PatchFileInfo { before_hash: BEFORE_HASH_2.to_string(), after_hash: AFTER_HASH_2.to_string(), + mode: None, }, ); @@ -353,6 +355,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "created-file".into(), + mode: None, }, ); if policy == "created-only" { diff --git a/crates/socket-patch-core/src/manifest/operations.rs b/crates/socket-patch-core/src/manifest/operations.rs index d93eb73f38..f76d287c44 100644 --- a/crates/socket-patch-core/src/manifest/operations.rs +++ b/crates/socket-patch-core/src/manifest/operations.rs @@ -234,6 +234,7 @@ mod tests { PatchFileInfo { before_hash: BEFORE_HASH_1.to_string(), after_hash: AFTER_HASH_1.to_string(), + mode: None, }, ); files_a.insert( @@ -241,6 +242,7 @@ mod tests { PatchFileInfo { before_hash: BEFORE_HASH_2.to_string(), after_hash: AFTER_HASH_2.to_string(), + mode: None, }, ); @@ -263,6 +265,7 @@ mod tests { PatchFileInfo { before_hash: BEFORE_HASH_3.to_string(), after_hash: AFTER_HASH_3.to_string(), + mode: None, }, ); @@ -343,6 +346,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), // new-file sentinel after_hash: AFTER_HASH_1.to_string(), + mode: None, }, ); diff --git a/crates/socket-patch-core/src/manifest/records.rs b/crates/socket-patch-core/src/manifest/records.rs index 7032d435cf..9b9211b050 100644 --- a/crates/socket-patch-core/src/manifest/records.rs +++ b/crates/socket-patch-core/src/manifest/records.rs @@ -70,6 +70,7 @@ pub fn files_for_manifest(patch: &PatchResponse) -> HashMap (String, PatchRecord build_patch_record(patch, files_for_manifest(patch)), ) } + +#[cfg(test)] +mod tests { + use super::*; + + fn view(mode: &str) -> String { + let hash = "ab".repeat(32); + format!( + r#"{{ + "uuid": "11111111-1111-4111-8111-111111111111", + "purl": "pkg:gem/octopoller@0.2.0", + "publishedAt": "2024-01-01T00:00:00Z", + "files": {{ + "lib/octopoller.rb": {{ + "beforeHash": "{hash}", + "afterHash": "{hash}"{mode} + }} + }}, + "vulnerabilities": {{}}, + "description": "", + "license": "MIT", + "tier": "free" + }}"# + ) + } + + /// A file entry's `mode` reaches the manifest record with its hashes: + /// without it, an entry whose content the fix leaves alone would be + /// recorded as one that is already patched. + #[test] + fn a_file_mode_is_recorded_with_the_entry() { + let patch: PatchResponse = serde_json::from_str(&view(r#", "mode": "0644""#)).unwrap(); + let (_, record) = record_from_patch_response(&patch); + let entry = &record.files["lib/octopoller.rb"]; + assert_eq!(entry.before_hash, entry.after_hash); + assert_eq!( + entry.mode.as_ref().map(|m| m.to_string()).as_deref(), + Some("0644") + ); + + let plain: PatchResponse = serde_json::from_str(&view("")).unwrap(); + assert_eq!(files_for_manifest(&plain)["lib/octopoller.rb"].mode, None); + } + + /// A view whose mode this release cannot read still parses, so one + /// such patch cannot fail the response it arrives in, and the mode is + /// recorded as it was sent: dropping it would leave an entry that reads + /// as patched whatever the file's permission bits are. + #[test] + fn a_file_mode_this_release_cannot_read_is_recorded_as_sent() { + for (mode, sent) in [ + (r#", "mode": "644""#, r#""644""#), + (r#", "mode": "u=rw,go=r""#, r#""u=rw,go=r""#), + (r#", "mode": 420"#, "420"), + ] { + let patch: PatchResponse = serde_json::from_str(&view(mode)).unwrap(); + let (_, record) = record_from_patch_response(&patch); + let recorded = record.files["lib/octopoller.rb"].mode.as_ref().unwrap(); + assert!(!recorded.is_readable(), "{mode}"); + assert_eq!(recorded.to_string(), sent, "{mode}"); + } + } +} diff --git a/crates/socket-patch-core/src/manifest/schema.rs b/crates/socket-patch-core/src/manifest/schema.rs index 9ec859ed41..874ef3e398 100644 --- a/crates/socket-patch-core/src/manifest/schema.rs +++ b/crates/socket-patch-core/src/manifest/schema.rs @@ -11,6 +11,106 @@ pub struct VulnerabilityInfo { pub description: String, } +/// The permission bits a patched file may have, for a patch that fixes a +/// package's file permissions: the `mode` of a file entry, spelled `0` and +/// three octal digits (`"0644"`, `"0755"`). +/// +/// It is an upper bound on the write bits of the installed file, never a +/// mode to set: a file is patched while it has no group-write or +/// other-write bit that the mode lacks ([`FileMode::excess_write_bits`]), +/// and patching it clears exactly those bits. Read, execute and owner bits +/// are never changed, so a read-only (`0444`) or owner-only (`0600`) copy +/// satisfies `"0644"` as it is. +/// +/// A `mode` in any other spelling still loads, and is written back as it +/// was read: it is one this release cannot read +/// ([`FileMode::is_readable`]), so the patch it belongs to can be neither +/// applied in place nor reported as applied, and every other patch of the +/// manifest works as before. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileMode(ModeRepr); + +#[derive(Debug, Clone, PartialEq, Eq)] +enum ModeRepr { + /// `0` and three octal digits: the permission bits. + Bits(u16), + /// Any other value, as the manifest or the API response holds it. + Unreadable(serde_json::Value), +} + +impl FileMode { + /// The mode `text` spells: exactly `0` and three octal digits. + /// Anything else is `None`. + pub fn parse(text: &str) -> Option { + let digits = text.strip_prefix('0')?; + if digits.len() != 3 { + return None; + } + digits + .bytes() + .try_fold(0u16, |bits, digit| match digit { + b'0'..=b'7' => Some(bits << 3 | u16::from(digit - b'0')), + _ => None, + }) + .map(|bits| Self(ModeRepr::Bits(bits))) + } + + /// The permission bits (`0o644`); `None` for a mode this release + /// cannot read. + pub fn bits(&self) -> Option { + match &self.0 { + ModeRepr::Bits(bits) => Some(u32::from(*bits)), + ModeRepr::Unreadable(_) => None, + } + } + + /// Whether this release can read the mode. A file whose entry has one + /// it cannot read is never patched and never reported as patched + /// ([`VerifyStatus::UnreadableMode`](crate::patch::apply::VerifyStatus::UnreadableMode)). + pub fn is_readable(&self) -> bool { + self.bits().is_some() + } + + /// The group-write and other-write bits a file with permission bits + /// `file_mode` has and this mode does not grant: what makes the file + /// unpatched, and what patching it clears. `0` when it has none, and + /// for a mode this release cannot read, which names no bit to clear + /// (such an entry is refused before its file's bits are looked at). + pub fn excess_write_bits(&self, file_mode: u32) -> u32 { + self.bits().map_or(0, |bits| file_mode & 0o022 & !bits) + } +} + +/// `0644` for a mode this release reads; the JSON it was read from +/// (`"0o644"`, `420`) for one it does not. +impl std::fmt::Display for FileMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + ModeRepr::Bits(bits) => write!(f, "0{bits:03o}"), + ModeRepr::Unreadable(value) => write!(f, "{value}"), + } + } +} + +impl Serialize for FileMode { + fn serialize(&self, serializer: S) -> Result { + match &self.0 { + ModeRepr::Bits(_) => serializer.collect_str(self), + ModeRepr::Unreadable(value) => value.serialize(serializer), + } + } +} + +impl<'de> Deserialize<'de> for FileMode { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + Ok(value + .as_str() + .and_then(Self::parse) + .unwrap_or(Self(ModeRepr::Unreadable(value)))) + } +} + /// Hash information for a single patched file. /// /// Both hashes are lowercase hex once deserialized, whatever case the @@ -25,6 +125,12 @@ pub struct PatchFileInfo { pub before_hash: String, #[serde(deserialize_with = "deserialize_hash")] pub after_hash: String, + /// Set when the file's permissions are part of the fix (see + /// [`FileMode`]). Such an entry may leave the content as it is + /// (`before_hash == after_hash`): the fix is the permission bits alone. + /// Absent on every other entry, which is patched by its content only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, } /// The manifest's hash case policy: a loaded hash is lowercase hex. @@ -182,6 +288,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaa".to_string(), after_hash: "bbb".to_string(), + mode: None, }; let json = serde_json::to_string(&file_info).unwrap(); assert!(json.contains("beforeHash")); @@ -421,6 +528,7 @@ mod tests { PatchFileInfo { before_hash: "b1".to_string(), after_hash: "a1".to_string(), + mode: None, }, ); files.insert( @@ -428,6 +536,7 @@ mod tests { PatchFileInfo { before_hash: "b2".to_string(), after_hash: "a2".to_string(), + mode: None, }, ); let mut vulns = HashMap::new(); @@ -584,6 +693,137 @@ mod tests { ); } + /// A file entry's `mode` is `0` and three octal digits, kept as + /// written; an entry without one neither reads nor writes the key, so + /// every manifest written before the field existed round-trips + /// byte-for-byte. + #[test] + fn test_patch_file_info_mode_round_trips_and_is_absent_by_default() { + let plain: PatchFileInfo = + serde_json::from_str(r#"{"beforeHash": "a", "afterHash": "b"}"#).unwrap(); + assert_eq!(plain.mode, None); + assert_eq!( + serde_json::to_string(&plain).unwrap(), + r#"{"beforeHash":"a","afterHash":"b"}"# + ); + + for (text, bits) in [ + ("0644", 0o644), + ("0755", 0o755), + ("0000", 0), + ("0777", 0o777), + ] { + let json = format!(r#"{{"beforeHash":"a","afterHash":"a","mode":"{text}"}}"#); + let parsed: PatchFileInfo = serde_json::from_str(&json).unwrap(); + let mode = parsed.mode.as_ref().unwrap(); + assert!(mode.is_readable(), "{text}"); + assert_eq!(mode.bits(), Some(bits), "{text}"); + assert_eq!(mode.to_string(), text); + assert_eq!(serde_json::to_string(&parsed).unwrap(), json); + } + } + + /// A mode in any other spelling is one this release cannot read. The + /// entry still loads, so one such entry cannot take the rest of the + /// manifest with it, and the mode is written back exactly as it was + /// read, so a rewrite of the manifest never drops or changes it. + #[test] + fn test_patch_file_info_keeps_a_mode_it_cannot_read_as_written() { + for mode in [ + r#""644""#, + r#""00644""#, + r#""0o644""#, + r#""0788""#, + r#""4755""#, + r#""rw-r--r--""#, + r#""""#, + r#""0644 ""#, + "420", + "true", + r#"["0644"]"#, + r#"{"bits":"0644","owner":"root"}"#, + ] { + let json = format!(r#"{{"beforeHash":"a","afterHash":"a","mode":{mode}}}"#); + let parsed: PatchFileInfo = serde_json::from_str(&json).unwrap(); + let held = parsed.mode.as_ref().unwrap(); + assert!(!held.is_readable(), "mode {mode} must not be read"); + assert_eq!(held.bits(), None, "{mode}"); + assert_eq!(held.excess_write_bits(0o777), 0, "{mode}"); + assert_eq!(held.to_string(), mode, "{mode}"); + assert_eq!(serde_json::to_string(&parsed).unwrap(), json, "{mode}"); + } + // An explicit null is an absent mode, and is not written back. + let null: PatchFileInfo = + serde_json::from_str(r#"{"beforeHash":"a","afterHash":"b","mode":null}"#).unwrap(); + assert_eq!(null.mode, None); + assert_eq!( + serde_json::to_string(&null).unwrap(), + r#"{"beforeHash":"a","afterHash":"b"}"# + ); + } + + /// One entry with a mode this release cannot read leaves the manifest + /// loadable, every other record as it was, and its own mode in place + /// through a load and a save. + #[test] + fn test_manifest_with_an_unreadable_mode_loads_and_round_trips() { + let json = r#"{ + "patches": { + "pkg:gem/a@1.0.0": { + "uuid": "11111111-1111-4111-8111-111111111111", + "exportedAt": "2026-01-01T00:00:00Z", + "files": { + "lib/a.rb": { "beforeHash": "aa", "afterHash": "aa", "mode": "u=rw,go=r" } + }, + "vulnerabilities": {}, + "description": "a", + "license": "MIT", + "tier": "free" + }, + "pkg:gem/b@1.0.0": { + "uuid": "22222222-2222-4222-8222-222222222222", + "exportedAt": "2026-01-01T00:00:00Z", + "files": { + "lib/b.rb": { "beforeHash": "bb", "afterHash": "cc", "mode": "0644" }, + "lib/c.rb": { "beforeHash": "dd", "afterHash": "ee" } + }, + "vulnerabilities": {}, + "description": "b", + "license": "MIT", + "tier": "free" + } + } +}"#; + let manifest: PatchManifest = serde_json::from_str(json).unwrap(); + let unreadable = &manifest.patches["pkg:gem/a@1.0.0"].files["lib/a.rb"]; + assert!(!unreadable.mode.as_ref().unwrap().is_readable()); + let other = &manifest.patches["pkg:gem/b@1.0.0"].files; + assert_eq!(other["lib/b.rb"].mode, FileMode::parse("0644")); + assert_eq!(other["lib/c.rb"].mode, None); + + let saved = serde_json::to_value(&manifest).unwrap(); + assert_eq!( + saved, + serde_json::from_str::(json).unwrap() + ); + } + + /// The write bits a mode does not grant are the group-write and + /// other-write bits it lacks, and nothing else of a file's mode. + #[test] + fn test_file_mode_excess_write_bits() { + let mode = |text| FileMode::parse(text).unwrap(); + assert_eq!(mode("0644").excess_write_bits(0o666), 0o022); + assert_eq!(mode("0644").excess_write_bits(0o664), 0o020); + assert_eq!(mode("0644").excess_write_bits(0o646), 0o002); + assert_eq!(mode("0755").excess_write_bits(0o777), 0o022); + assert_eq!(mode("0664").excess_write_bits(0o666), 0o002); + for held in [0o644, 0o444, 0o600, 0o755, 0o4755, 0o100644, 0o711] { + assert_eq!(mode("0644").excess_write_bits(held), 0, "{held:o}"); + } + assert_eq!(mode("0666").excess_write_bits(0o7777), 0); + } + /// #707: a hand-edited or third-party manifest may spell its hashes in /// uppercase. They load as lowercase, the case every computed /// git-sha256 and every blob name uses; an empty `beforeHash` (a diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index f738bb996d..9142c56e3c 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::hash::git_sha256::compute_git_sha256_from_bytes; -use crate::manifest::schema::PatchFileInfo; +use crate::manifest::schema::{FileMode, PatchFileInfo}; use crate::patch::file_hash::compute_file_git_sha256; use crate::utils::fs::read_regular_to_bytes; @@ -18,6 +18,11 @@ pub enum VerifyStatus { HashMismatch, /// File was not found on disk. NotFound, + /// The file holds content its entry describes (it would otherwise be + /// `Ready` or `AlreadyPatched`), but the entry's `mode` is one this + /// release cannot read ([`FileMode::is_readable`]): the file can be + /// neither patched nor judged patched. No policy overrides it. + UnreadableMode, } /// Result of verifying whether a single file can be patched. @@ -29,6 +34,10 @@ pub struct VerifyResult { pub current_hash: Option, pub expected_hash: Option, pub target_hash: Option, + /// `Ready` for the file's permission bits alone: it holds the patched + /// content, with a group-write or other-write bit its entry's `mode` + /// does not grant. Patching it replaces the file with the bytes it has. + pub permissions_only: bool, } /// How the apply pipeline treats a file whose on-disk content matches @@ -71,6 +80,9 @@ pub enum AppliedVia { /// Bytes came from a per-file blob (`.socket/blobs/` or the in-memory /// overlay). Blob, + /// The file already held the patched bytes; the patch cleared the + /// write bits its entry's `mode` does not grant. + Permissions, } impl AppliedVia { @@ -78,6 +90,7 @@ impl AppliedVia { pub fn as_tag(&self) -> &'static str { match self { AppliedVia::Blob => "blob", + AppliedVia::Permissions => "permissions", } } } @@ -286,11 +299,112 @@ pub fn is_valid_blob_hash(hash: &str) -> bool { hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) } -/// Verify a single file can be patched. +/// The group-write and other-write bits the file at `path` has and `mode` +/// (a patch entry's, see [`FileMode`]) does not grant: `0` for an entry +/// without a mode, for a file that cannot be read, and off Unix, where a +/// file has no such bits. +pub(crate) async fn excess_write_bits(path: &Path, mode: Option<&FileMode>) -> u32 { + let Some(mode) = mode else { + return 0; + }; + match tokio::fs::metadata(path).await { + Ok(meta) => mode_excess(&meta, mode), + Err(_) => 0, + } +} + +/// The permissions of a file with `meta` less the write bits `mode` does +/// not grant; `None` when it has none of them (and off Unix). +#[cfg_attr(not(unix), allow(unused_variables))] +fn without_excess_write_bits( + meta: &std::fs::Metadata, + mode: &FileMode, +) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let held = meta.permissions().mode(); + let excess = mode.excess_write_bits(held); + (excess != 0).then(|| std::fs::Permissions::from_mode(held & !excess)) + } + #[cfg(not(unix))] + { + None + } +} + +/// [`excess_write_bits`] of a file's metadata. +#[cfg_attr(not(unix), allow(unused_variables))] +pub(crate) fn mode_excess(meta: &std::fs::Metadata, mode: &FileMode) -> u32 { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + mode.excess_write_bits(meta.permissions().mode()) + } + #[cfg(not(unix))] + { + 0 + } +} + +/// The failure code of a patch with a file entry whose `mode` this release +/// cannot read ([`VerifyStatus::UnreadableMode`]). +pub const UNREADABLE_FILE_MODE: &str = "unreadable_file_mode"; + +/// What [`verify_file_patch`] says of a file whose entry has a `mode` this +/// release cannot read. +pub(crate) fn unreadable_mode_message(mode: &FileMode) -> String { + format!( + "its file mode {mode} is not one this release of socket-patch can read \ + (a mode is spelled like \"0644\"); a newer release may read it" + ) +} + +/// Verify a single file can be patched: its content, and for an entry +/// with a `mode` its permission bits (a file holding the patched bytes +/// under a write bit the mode does not grant is `Ready`, with +/// [`VerifyResult::permissions_only`] set). A file that would be `Ready` +/// or `AlreadyPatched` under a `mode` this release cannot read is +/// [`VerifyStatus::UnreadableMode`] instead. pub async fn verify_file_patch( pkg_path: &Path, file_name: &str, file_info: &PatchFileInfo, +) -> VerifyResult { + let mode = file_info.mode.as_ref(); + let mut result = verify_file(pkg_path, file_name, file_info, mode).await; + if let Some(mode) = mode.filter(|mode| !mode.is_readable()) { + if matches!( + result.status, + VerifyStatus::Ready | VerifyStatus::AlreadyPatched + ) { + result.status = VerifyStatus::UnreadableMode; + result.message = Some(unreadable_mode_message(mode)); + result.permissions_only = false; + } + } + result +} + +/// [`verify_file_patch`] by the file's content alone, whatever `mode` its +/// entry has: for a copy this tool wrote itself and git may have checked +/// out since (a vendored artifact), whose permission bits are the +/// extraction's and the checkout's, never the upstream package's. +pub async fn verify_file_content( + pkg_path: &Path, + file_name: &str, + file_info: &PatchFileInfo, +) -> VerifyResult { + verify_file(pkg_path, file_name, file_info, None).await +} + +/// The file's content against the entry's hashes, and its permission bits +/// against `mode` when that is one this release reads. +async fn verify_file( + pkg_path: &Path, + file_name: &str, + file_info: &PatchFileInfo, + mode: Option<&FileMode>, ) -> VerifyResult { let normalized = normalize_file_path(file_name); // SECURITY: never resolve a key that escapes the package directory. @@ -302,6 +416,7 @@ pub async fn verify_file_patch( current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }; } let filepath = pkg_path.join(normalized); @@ -323,6 +438,7 @@ pub async fn verify_file_patch( current_hash: None, expected_hash: None, target_hash: Some(file_info.after_hash.clone()), + permissions_only: false, }; } return VerifyResult { @@ -332,6 +448,7 @@ pub async fn verify_file_patch( current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }; } Err(e) => { @@ -342,6 +459,7 @@ pub async fn verify_file_patch( current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }; } }; @@ -361,6 +479,20 @@ pub async fn verify_file_patch( if current_hash == file_info.after_hash || source_hash.as_deref() == Some(file_info.after_hash.as_str()) { + // An entry with a `mode` is patched by its permission bits too: the + // patched bytes under a write bit the mode does not grant are still + // to patch, and patching them changes the bits alone. + if excess_write_bits(&filepath, mode).await != 0 { + return VerifyResult { + file: file_name.to_string(), + status: VerifyStatus::Ready, + message: None, + current_hash: Some(current_hash), + expected_hash: None, + target_hash: Some(file_info.after_hash.clone()), + permissions_only: true, + }; + } return VerifyResult { file: file_name.to_string(), status: VerifyStatus::AlreadyPatched, @@ -368,6 +500,7 @@ pub async fn verify_file_patch( current_hash: Some(current_hash), expected_hash: None, target_hash: None, + permissions_only: false, }; } @@ -381,6 +514,7 @@ pub async fn verify_file_patch( current_hash: Some(current_hash), expected_hash: None, target_hash: Some(file_info.after_hash.clone()), + permissions_only: false, }; } @@ -395,6 +529,7 @@ pub async fn verify_file_patch( current_hash: Some(current_hash), expected_hash: Some(file_info.before_hash.clone()), target_hash: Some(file_info.after_hash.clone()), + permissions_only: false, }; } @@ -405,6 +540,7 @@ pub async fn verify_file_patch( current_hash: Some(current_hash), expected_hash: None, target_hash: Some(file_info.after_hash.clone()), + permissions_only: false, } } @@ -576,9 +712,12 @@ async fn variant_installed_at( for (dir, copy_files) in crate::crawlers::gradle_cache::installed_copies(pkg_path, &single) { for (name, info) in ©_files { let verify = verify_file_patch(&dir, name, info).await; + // `UnreadableMode` is a file whose content matches: the + // variant is the installed one, and applying it reports the + // mode. if matches!( verify.status, - VerifyStatus::Ready | VerifyStatus::AlreadyPatched + VerifyStatus::Ready | VerifyStatus::AlreadyPatched | VerifyStatus::UnreadableMode ) { return true; } @@ -622,6 +761,7 @@ pub(crate) async fn apply_file_patch_at( let change = FileChange::Write { content: patched_content.to_vec(), hash: expected_hash.to_string(), + mode: None, }; let (write, warning) = stage_change(PackageWrite::new(), pkg_path, file_name, change) .await @@ -640,8 +780,13 @@ pub(crate) async fn apply_file_patch_at( /// One file's change in a [`PackageWrite`]. pub(crate) enum FileChange { /// Replace (or create) the file with `content`, which must hash to - /// `hash`. - Write { content: Vec, hash: String }, + /// `hash`. With `mode` (a patch entry's, see [`FileMode`]) the file + /// replaced loses the write bits that mode does not grant. + Write { + content: Vec, + hash: String, + mode: Option, + }, /// Remove the file (rollback of a file the patch added). Delete, } @@ -920,12 +1065,17 @@ impl PackageWrite { /// Stage `content` for the manifest key `file_name` of the package at /// `pkg_path`. `Ok(Some(warning))` when the stage could not be given /// the file's owner. Nothing the package holds has changed yet. + /// + /// The stage has the mode of the file it replaces, bit for bit, less + /// the group-write and other-write bits `mode` (the entry's, see + /// [`FileMode`]) does not grant; without a `mode` nothing is cleared. pub(crate) fn stage_write( &mut self, pkg_path: &Path, file_name: &str, content: &[u8], expected_hash: &str, + mode: Option<&FileMode>, ) -> std::io::Result> { use crate::utils::fs::{stage_blocking, StageAttrs, StageMode, StageSync}; let normalized = normalize_file_path(file_name); @@ -957,7 +1107,7 @@ impl PackageWrite { if let Some(parent) = &parent { self.open_dir(parent)?; } - let attrs = match &existing { + let mut attrs = match &existing { Some(meta) => StageAttrs::of(meta), None => StageAttrs { mode: StageMode::ReadOnly, @@ -967,6 +1117,27 @@ impl PackageWrite { .and_then(|meta| StageAttrs::of(&meta).owner), }, }; + // The write bits the entry's mode does not grant are left out of + // the stage's mode, so the rename is also what clears them. + let tightened = existing + .as_ref() + .zip(mode) + .and_then(|(meta, mode)| without_excess_write_bits(meta, mode)); + if let Some(perms) = &tightened { + attrs.mode = StageMode::Of(perms.clone()); + // A captured write (below) is given the mode its file has when + // the group commit replaces it, and one that changes no byte is + // never written: the bits are cleared here, under the bytes the + // file holds now. + if crate::utils::group_commit::is_capturing(&dest) { + let held = std::fs::read(&dest)?; + let staged = stage_blocking(&dest, &held, &attrs, StageSync::Now)?; + if let Err(e) = staged.commit() { + staged.discard(); + return Err(e); + } + } + } // Inside an open group commit a commit point under its root is // captured instead of written (see `utils::group_commit`). if crate::utils::group_commit::capture_write(&dest, content, existing.is_some()) { @@ -1182,9 +1353,11 @@ pub(crate) async fn stage_change( let (pkg_path, file) = (pkg_path.to_path_buf(), file.to_string()); crate::utils::fs::run_blocking(move || { let staged = match &change { - FileChange::Write { content, hash } => { - write.stage_write(&pkg_path, &file, content, hash) - } + FileChange::Write { + content, + hash, + mode, + } => write.stage_write(&pkg_path, &file, content, hash, mode.as_ref()), FileChange::Delete => write.stage_delete(&pkg_path, &file).map(|()| None), }; match staged { @@ -1612,6 +1785,7 @@ fn mark_new_file_collision(verify: &mut VerifyResult, file_info: &PatchFileInfo) if file_info.before_hash.is_empty() && verify.status == VerifyStatus::Ready && verify.current_hash.is_some() + && !verify.permissions_only { verify.status = VerifyStatus::HashMismatch; verify.message = Some(NEW_FILE_COLLISION_MESSAGE.to_string()); @@ -1632,7 +1806,9 @@ async fn mark_crlf_bin_rewrite( file_info: &PatchFileInfo, verify: &mut VerifyResult, ) { - if verify.status == VerifyStatus::AlreadyPatched + // A bin that is also `Ready` for its permission bits is written in + // npm's form by the same write, not replaced with the bytes it holds. + if (verify.status == VerifyStatus::AlreadyPatched || verify.permissions_only) && verify.current_hash.as_deref() == Some(file_info.after_hash.as_str()) && crate::patch::npm_bin::needs_fix( package_key, @@ -1644,6 +1820,7 @@ async fn mark_crlf_bin_rewrite( { verify.status = VerifyStatus::Ready; verify.target_hash = Some(file_info.after_hash.clone()); + verify.permissions_only = false; } } @@ -1836,10 +2013,12 @@ async fn apply_package_patch_at( .clone() .unwrap_or_else(|| format!("{:?}", verify_result.status)); result.fail( - if verify_result.status == VerifyStatus::NotFound { - ApplyFailureCause::FileNotFound - } else { - ApplyFailureCause::HashMismatch + match verify_result.status { + VerifyStatus::NotFound => ApplyFailureCause::FileNotFound, + VerifyStatus::UnreadableMode => { + ApplyFailureCause::Coded(UNREADABLE_FILE_MODE) + } + _ => ApplyFailureCause::HashMismatch, }, format!("Cannot apply patch: {} - {}", verify_result.file, msg), ); @@ -2008,14 +2187,69 @@ async fn apply_package_patch_at( .filter(|v| v.status == VerifyStatus::Ready) .map(|v| v.file.as_str()) .collect(); + // Files holding the patched bytes already, `Ready` for their + // permission bits alone (see `verify_file_patch`), with the hash of + // the bytes they were verified to hold. + let permissions_only: HashMap<&str, Option<&str>> = result + .files_verified + .iter() + .filter(|v| v.status == VerifyStatus::Ready && v.permissions_only) + .map(|v| (v.file.as_str(), v.current_hash.as_deref())) + .collect(); let mut write = PackageWrite::new(); - let mut written: Vec<&String> = Vec::new(); + let mut written: Vec<(&String, AppliedVia)> = Vec::new(); for (file_name, file_info) in files_in_order(files) { if !ready.contains(file_name.as_str()) { continue; } let normalized = normalize_file_path(file_name); + // A file whose bytes are the patched ones is replaced with the + // bytes it holds, in the form it holds them (npm's LF-shebang bin + // included): the stage and rename change its permission bits + // alone, and no blob is needed for it. + if let Some(verified_hash) = permissions_only.get(file_name.as_str()) { + let held = match read_regular_to_bytes(&pkg_path.join(normalized)).await { + Ok(bytes) => bytes, + Err(e) => { + abort_package(write).await; + result.fail( + ApplyFailureCause::WriteFailed, + format!("Cannot apply patch: {file_name} - {e}"), + ); + return result; + } + }; + let hash = compute_git_sha256_from_bytes(&held); + if Some(hash.as_str()) != *verified_hash { + abort_package(write).await; + result.fail( + ApplyFailureCause::WriteFailed, + format!( + "Cannot apply patch: {file_name} - the file changed while it was being patched" + ), + ); + return result; + } + let change = FileChange::Write { + content: held, + hash, + mode: file_info.mode.clone(), + }; + write = match stage_change(write, pkg_path, file_name, change).await { + Ok((write, warning)) => { + warnings.extend(warning); + write + } + Err(e) => { + write_failed(&mut result, e); + return result; + } + }; + written.push((file_name, AppliedVia::Permissions)); + continue; + } + // Resolve the patched bytes: the in-memory blob overlay first (the // vendor flows stage there, so vendoring writes no `.socket/blobs` // entries), then the on-disk blob, which must hold the bytes its @@ -2074,6 +2308,7 @@ async fn apply_package_patch_at( let change = FileChange::Write { content: content.into_owned(), hash, + mode: file_info.mode.clone(), }; write = match stage_change(write, pkg_path, file_name, change).await { Ok((write, warning)) => { @@ -2085,7 +2320,7 @@ async fn apply_package_patch_at( return result; } }; - written.push(file_name); + written.push((file_name, AppliedVia::Blob)); } let write = match commit_package(write).await { @@ -2114,7 +2349,7 @@ async fn apply_package_patch_at( // nothing in the common already-synced case. let fixup_files: Vec = written .iter() - .map(|file| (*file).clone()) + .map(|(file, _)| (*file).clone()) .chain( result .files_verified @@ -2151,16 +2386,17 @@ async fn apply_package_patch_at( } } - for file_name in written { + for (file_name, via) in written { // A rewritten `.py` file can't be trusted to invalidate its // bytecode (#819): drop it so the next import compiles the new - // source. - let source = pkg_path.join(normalize_file_path(file_name)); - warnings.extend(remove_stale_bytecode(&source, StaleBytecode::All).await); + // source. One replaced with the bytes it held (its permission + // bits alone changed) is still what its bytecode was compiled from. + if via == AppliedVia::Blob { + let source = pkg_path.join(normalize_file_path(file_name)); + warnings.extend(remove_stale_bytecode(&source, StaleBytecode::All).await); + } result.files_patched.push(file_name.clone()); - result - .applied_via - .insert(file_name.clone(), AppliedVia::Blob); + result.applied_via.insert(file_name.clone(), via); } warnings.extend(finish_package(write).await); // Files `--force` skipped are named beside the ones just written. @@ -2225,6 +2461,10 @@ pub(crate) async fn read_blob_entry(blob_path: &Path) -> std::io::Result read_regular_to_bytes(blob_path).await } +#[cfg(all(test, unix))] +#[path = "apply_file_mode_tests.rs"] +mod file_mode_tests; + #[cfg(test)] mod tests { use super::*; @@ -2244,6 +2484,7 @@ mod tests { current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, }) .collect(), files_patched: Vec::new(), @@ -2416,6 +2657,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaa".to_string(), after_hash: "bbb".to_string(), + mode: None, }; let result = verify_file_patch(dir.path(), "nonexistent.js", &file_info).await; @@ -2436,6 +2678,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: before_hash.clone(), after_hash, + mode: None, }; let result = verify_file_patch(dir.path(), "index.js", &file_info).await; @@ -2456,6 +2699,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: after_hash.clone(), + mode: None, }; let result = verify_file_patch(dir.path(), "index.js", &file_info).await; @@ -2472,6 +2716,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "bbbb".to_string(), + mode: None, }; let result = verify_file_patch(dir.path(), "index.js", &file_info).await; @@ -2495,6 +2740,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: before_hash.clone(), after_hash: "bbbb".to_string(), + mode: None, }; let result = verify_file_patch(dir.path(), "package/lib/server.js", &file_info).await; @@ -2923,6 +3169,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: after_hash.clone(), + mode: None, }, ); @@ -2975,6 +3222,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: after_hash.clone(), + mode: None, }, ); @@ -3022,6 +3270,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(original), after_hash, + mode: None, }, )]); (pkg_dir, blobs_dir, files) @@ -3139,6 +3388,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: "bbbb".to_string(), + mode: None, }, ); @@ -3193,6 +3443,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: after_hash.clone(), + mode: None, }, ); @@ -3244,6 +3495,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash, + mode: None, }, ); @@ -3277,6 +3529,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "bbbb".to_string(), + mode: None, }, ); @@ -3322,6 +3575,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash, + mode: None, }, ); let target = pkg_dir.path().join("index.js"); @@ -3378,6 +3632,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: after_hash.clone(), + mode: None, }, ); @@ -3468,6 +3723,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "bbbb".to_string(), + mode: None, }, ); @@ -3526,6 +3782,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(original.as_bytes()), after_hash, + mode: None, }, ); } @@ -3581,6 +3838,7 @@ mod tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); } @@ -3642,6 +3900,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); (root, pkg_dir, blobs_dir, files, original) @@ -3774,6 +4033,7 @@ mod tests { PatchFileInfo { before_hash: installed_hash.clone(), after_hash: "a".repeat(64), + mode: None, }, ); variant_a.insert( @@ -3781,6 +4041,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), // new file after_hash: "b".repeat(64), + mode: None, }, ); // Variant B: a different distribution (mod.py bytes differ), @@ -3791,6 +4052,7 @@ mod tests { PatchFileInfo { before_hash: other_hash.clone(), after_hash: "c".repeat(64), + mode: None, }, ); variant_b.insert( @@ -3798,6 +4060,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), // new file after_hash: "d".repeat(64), + mode: None, }, ); @@ -3828,6 +4091,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "a".repeat(64), + mode: None, }, ); let variants: Vec<(&str, &HashMap)> = @@ -3859,6 +4123,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: "a".repeat(64), + mode: None, }, )]) }; @@ -3930,6 +4195,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original jar"), after_hash: compute_git_sha256_from_bytes(b"patched jar"), + mode: None, }, ); files.insert( @@ -3937,6 +4203,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"x"), after_hash: compute_git_sha256_from_bytes(b"y"), + mode: None, }, ); let blobs = tempfile::tempdir().unwrap(); @@ -4008,6 +4275,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original a"), after_hash: compute_git_sha256_from_bytes(b"patched a"), + mode: None, }, ); files.insert( @@ -4015,6 +4283,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original b"), after_hash: b_after, + mode: None, }, ); @@ -4073,6 +4342,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: after_hash.clone(), + mode: None, }; let result = verify_file_patch(dir.path(), "new.js", &file_info).await; @@ -4103,6 +4373,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: after_hash.clone(), + mode: None, }, ); @@ -4155,6 +4426,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash, + mode: None, }, ); @@ -4279,6 +4551,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: after_hash.clone(), + mode: None, }, ); let result = apply_package_patch( @@ -4341,6 +4614,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); files.insert( @@ -4348,6 +4622,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: evil_hash, + mode: None, }, ); @@ -4393,6 +4668,7 @@ mod tests { let existing = PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "bbbb".to_string(), + mode: None, }; let result = verify_file_patch(dir.path(), "blocker/index.js", &existing).await; assert_eq!(result.status, VerifyStatus::NotFound); @@ -4401,6 +4677,7 @@ mod tests { let new_file = PatchFileInfo { before_hash: String::new(), after_hash: "bbbb".to_string(), + mode: None, }; let result = verify_file_patch(dir.path(), "blocker/index.js", &new_file).await; assert_eq!(result.status, VerifyStatus::Ready); @@ -4436,6 +4713,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(original), after_hash: "../outside".to_string(), + mode: None, }, ); @@ -4495,6 +4773,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(original), after_hash, + mode: None, }, ); @@ -4637,10 +4916,10 @@ mod tests { let mut write = PackageWrite::new(); let hash = |bytes: &[u8]| compute_git_sha256_from_bytes(bytes); write - .stage_write(dir.path(), "bin.sh", b"new", &hash(b"new")) + .stage_write(dir.path(), "bin.sh", b"new", &hash(b"new"), None) .unwrap(); write - .stage_write(dir.path(), "added.js", b"added", &hash(b"added")) + .stage_write(dir.path(), "added.js", b"added", &hash(b"added"), None) .unwrap(); let mode_of = |op: &FileOp| { let stage = op.staged.as_ref().unwrap().stage(); @@ -4701,13 +4980,13 @@ mod tests { let mut write = PackageWrite::new(); write.stage_delete(&pkg, "lib/gone.js").unwrap(); write - .stage_write(&pkg, "a.js", b"new a", &hash(b"new a")) + .stage_write(&pkg, "a.js", b"new a", &hash(b"new a"), None) .unwrap(); write - .stage_write(&pkg, "new/dir/added.js", b"added", &hash(b"added")) + .stage_write(&pkg, "new/dir/added.js", b"added", &hash(b"added"), None) .unwrap(); write - .stage_write(&pkg, "b.js", b"new b", &hash(b"new b")) + .stage_write(&pkg, "b.js", b"new b", &hash(b"new b"), None) .unwrap(); // The last rename has nothing to rename: its stage is gone. std::fs::remove_file(write.ops[3].staged.as_ref().unwrap().stage()).unwrap(); @@ -4766,6 +5045,7 @@ mod tests { let info = PatchFileInfo { before_hash: String::new(), after_hash: String::new(), + mode: None, }; (key.to_string(), info) }) @@ -4933,6 +5213,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); (root, roots, key, blobs, files, original, patched) @@ -5034,6 +5315,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&upstream), after_hash, + mode: None, }, ); let sources = PatchSources::blobs_only(&blobs); @@ -5094,6 +5376,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&original), after_hash, + mode: None, }, ); let result = apply_package_patch( @@ -5305,6 +5588,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"x = 1\n"), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, ); @@ -5376,6 +5660,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(CRLF_BIN_BEFORE), after_hash: compute_git_sha256_from_bytes(CRLF_BIN_AFTER), + mode: None, }, )]) } diff --git a/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs new file mode 100644 index 0000000000..3428dc60a8 --- /dev/null +++ b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs @@ -0,0 +1,556 @@ +//! A patch entry's `mode` (see [`FileMode`]): a file is patched by its +//! permission bits as well as its content, and patching it clears the +//! group-write and other-write bits the mode does not grant, nothing else. + +use std::collections::HashMap; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::Path; + +use super::*; +use crate::manifest::schema::FileMode; +use crate::patch::rollback::{rollback_package_patch, verify_file_rollback, VerifyRollbackStatus}; +use crate::utils::repo_root::ReadScope; + +const PURL: &str = "pkg:npm/test@1.0.0"; +const FILE: &str = "lib/a.rb"; + +fn hash(bytes: &[u8]) -> String { + compute_git_sha256_from_bytes(bytes) +} + +fn mode_of(path: &Path) -> u32 { + std::fs::metadata(path).unwrap().permissions().mode() & 0o7777 +} + +fn chmod(path: &Path, mode: u32) { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +fn entry(before: &[u8], after: &[u8], mode: Option<&str>) -> PatchFileInfo { + PatchFileInfo { + before_hash: hash(before), + after_hash: hash(after), + mode: mode.map(|m| FileMode::parse(m).unwrap()), + } +} + +/// A package dir holding [`FILE`] with `content` at `mode`, and an empty +/// blobs dir. +fn package(content: &[u8], mode: u32) -> (tempfile::TempDir, tempfile::TempDir) { + let pkg = tempfile::tempdir().unwrap(); + let path = pkg.path().join(FILE); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, content).unwrap(); + chmod(&path, mode); + (pkg, tempfile::tempdir().unwrap()) +} + +fn one(info: PatchFileInfo) -> HashMap { + HashMap::from([(FILE.to_string(), info)]) +} + +async fn apply( + pkg: &Path, + blobs: &Path, + files: &HashMap, + dry_run: bool, +) -> ApplyResult { + apply_package_patch( + ReadScope::Workspace, + PURL, + pkg, + files, + &PatchSources::blobs_only(blobs), + dry_run, + MismatchPolicy::Strict, + ) + .await +} + +const CODE: &[u8] = b"module Octopoller; end\n"; + +/// The reported case: the fix leaves the content as it is, and the file +/// was installed world-writable. It is not patched until the bits go; +/// patching it needs no blob, changes no byte and is reported as a change +/// to the permissions; a second run finds nothing to do. +#[tokio::test] +async fn unchanged_content_under_a_world_writable_mode_is_patched_by_its_bits() { + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let files = one(entry(CODE, CODE, Some("0644"))); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::Ready); + assert!(verify.permissions_only); + assert_eq!(verify.target_hash.as_deref(), Some(hash(CODE).as_str())); + + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(result.files_patched, [FILE]); + assert_eq!(result.applied_via[FILE], AppliedVia::Permissions); + assert_eq!(result.error, None); + assert_eq!(mode_of(&path), 0o644); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::AlreadyPatched); + assert!(!verify.permissions_only); + let again = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(again.success, "{:?}", again.error); + assert!(again.files_patched.is_empty(), "{:?}", again.files_patched); + assert_eq!(mode_of(&path), 0o644); +} + +/// Only write bits are cleared, and only those the mode lacks: an +/// executable keeps every execute bit, and a mode that grants group write +/// keeps a group-writable file as it is. +#[tokio::test] +async fn only_the_write_bits_the_mode_lacks_are_cleared() { + for (held, mode, expected) in [ + (0o777, "0755", 0o755), + (0o666, "0644", 0o644), + (0o664, "0644", 0o644), + (0o646, "0644", 0o644), + (0o666, "0664", 0o664), + (0o757, "0755", 0o755), + ] { + let (pkg, blobs) = package(CODE, held); + let files = one(entry(CODE, CODE, Some(mode))); + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{held:o} under {mode}: {:?}", result.error); + assert_eq!(result.files_patched, [FILE], "{held:o} under {mode}"); + assert_eq!( + mode_of(&pkg.path().join(FILE)), + expected, + "{held:o} under {mode}" + ); + } +} + +/// A file with no excess write bit is patched as it is, whatever else its +/// mode says: read-only, owner-only, group-writable under a mode that +/// grants it, setuid. Nothing is written, so it keeps its inode. +#[tokio::test] +async fn a_file_without_excess_write_bits_is_left_untouched() { + for (held, mode) in [ + (0o644, "0644"), + (0o444, "0644"), + (0o600, "0644"), + (0o400, "0644"), + (0o640, "0644"), + (0o755, "0755"), + (0o500, "0755"), + (0o664, "0664"), + (0o4755, "0755"), + // The mode bounds write bits only: an execute bit it lacks stays. + (0o755, "0644"), + ] { + let (pkg, blobs) = package(CODE, held); + let path = pkg.path().join(FILE); + let inode = std::fs::metadata(&path).unwrap().ino(); + let files = one(entry(CODE, CODE, Some(mode))); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!( + verify.status, + VerifyStatus::AlreadyPatched, + "{held:o} under {mode}" + ); + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{held:o} under {mode}: {:?}", result.error); + assert!(result.files_patched.is_empty(), "{held:o} under {mode}"); + assert_eq!(mode_of(&path), held, "{held:o} under {mode}"); + assert_eq!( + std::fs::metadata(&path).unwrap().ino(), + inode, + "{held:o} under {mode}" + ); + } +} + +/// The bits a mode says nothing about survive the change: setuid stays on +/// a file that loses its other-write bit. +#[tokio::test] +async fn special_bits_survive_the_cleared_write_bits() { + let (pkg, blobs) = package(CODE, 0o4757); + let path = pkg.path().join(FILE); + // Not every filesystem lets an unprivileged owner keep setuid. + if mode_of(&path) != 0o4757 { + return; + } + let files = one(entry(CODE, CODE, Some("0755"))); + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(mode_of(&path), 0o4755); +} + +/// An entry without a mode is patched by its content alone, as before: +/// the patched bytes are patched at any mode, and a content change keeps +/// the mode the file had, bit for bit. +#[tokio::test] +async fn an_entry_without_a_mode_never_looks_at_the_bits() { + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let patched: &[u8] = b"module Octopoller; VERSION = 1; end\n"; + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + let files = one(entry(CODE, patched, None)); + + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(result.applied_via[FILE], AppliedVia::Blob); + assert_eq!(std::fs::read(&path).unwrap(), patched); + assert_eq!(mode_of(&path), 0o666); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::AlreadyPatched); +} + +/// A content change under a mode does both in the one rename: the patched +/// bytes arrive without the excess bits, written from the blob. +#[tokio::test] +async fn a_content_change_with_a_mode_writes_the_blob_without_the_bits() { + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let patched: &[u8] = b"module Octopoller; VERSION = 1; end\n"; + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + let files = one(entry(CODE, patched, Some("0644"))); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::Ready); + assert!(!verify.permissions_only); + + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(result.applied_via[FILE], AppliedVia::Blob); + assert_eq!(std::fs::read(&path).unwrap(), patched); + assert_eq!(mode_of(&path), 0o644); +} + +/// The patched bytes an earlier release wrote, still under the mode the +/// installer gave the file: content done, bits to go. +#[tokio::test] +async fn patched_bytes_left_under_excess_bits_are_finished() { + let patched: &[u8] = b"module Octopoller; VERSION = 1; end\n"; + let (pkg, blobs) = package(patched, 0o666); + let files = one(entry(CODE, patched, Some("0644"))); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::Ready); + assert!(verify.permissions_only); + + // No blob is stored: the file is replaced with the bytes it holds. + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(result.applied_via[FILE], AppliedVia::Permissions); + assert_eq!(mode_of(&pkg.path().join(FILE)), 0o644); +} + +/// The bits are cleared by replacing the directory entry, never by a +/// chmod of the inode: a second link to the file (a package manager's +/// store) keeps its mode and its bytes. +#[tokio::test] +async fn a_hard_linked_copy_is_replaced_not_changed_in_place() { + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let store = tempfile::tempdir_in(pkg.path().parent().unwrap()).unwrap(); + let stored = store.path().join("a.rb"); + std::fs::hard_link(&path, &stored).unwrap(); + let files = one(entry(CODE, CODE, Some("0644"))); + + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(mode_of(&path), 0o644); + assert_eq!(mode_of(&stored), 0o666); + assert_eq!(std::fs::read(&stored).unwrap(), CODE); + assert_ne!( + std::fs::metadata(&path).unwrap().ino(), + std::fs::metadata(&stored).unwrap().ino() + ); +} + +/// A dry run reports the file as one to patch and changes nothing. +#[tokio::test] +async fn a_dry_run_changes_no_bit() { + let (pkg, blobs) = package(CODE, 0o666); + let files = one(entry(CODE, CODE, Some("0644"))); + let result = apply(pkg.path(), blobs.path(), &files, true).await; + assert!(result.success, "{:?}", result.error); + assert!(result.files_patched.is_empty()); + assert_eq!(result.files_verified[0].status, VerifyStatus::Ready); + assert_eq!(mode_of(&pkg.path().join(FILE)), 0o666); +} + +/// A file the patch adds, present with the patched bytes under excess +/// bits, is the patch's own file: not the collision with foreign content +/// that an existing file under a new-file entry otherwise is. +#[tokio::test] +async fn an_added_file_with_the_patched_bytes_is_not_a_collision() { + let (pkg, blobs) = package(CODE, 0o666); + let files = one(PatchFileInfo { + before_hash: String::new(), + after_hash: hash(CODE), + mode: FileMode::parse("0644"), + }); + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + assert_eq!(result.applied_via[FILE], AppliedVia::Permissions); + assert_eq!(mode_of(&pkg.path().join(FILE)), 0o644); +} + +/// A package with several entries stages them all before the first +/// rename: one content change and one permission change land together, +/// and an entry that is done stays out of the report. +#[tokio::test] +async fn content_and_permission_changes_land_in_one_write() { + let (pkg, blobs) = package(CODE, 0o666); + let other = pkg.path().join("lib/b.rb"); + std::fs::write(&other, b"old").unwrap(); + chmod(&other, 0o644); + let done = pkg.path().join("lib/c.rb"); + std::fs::write(&done, CODE).unwrap(); + chmod(&done, 0o644); + std::fs::write(blobs.path().join(hash(b"new")), b"new").unwrap(); + let files = HashMap::from([ + (FILE.to_string(), entry(CODE, CODE, Some("0644"))), + ("lib/b.rb".to_string(), entry(b"old", b"new", None)), + ("lib/c.rb".to_string(), entry(CODE, CODE, Some("0644"))), + ]); + + let result = apply(pkg.path(), blobs.path(), &files, false).await; + assert!(result.success, "{:?}", result.error); + let mut patched = result.files_patched.clone(); + patched.sort(); + assert_eq!(patched, [FILE, "lib/b.rb"]); + assert_eq!(result.applied_via[FILE], AppliedVia::Permissions); + assert_eq!(result.applied_via["lib/b.rb"], AppliedVia::Blob); + assert_eq!(mode_of(&pkg.path().join(FILE)), 0o644); + assert_eq!(std::fs::read(&other).unwrap(), b"new"); +} + +/// A rollback restores content and never gives a write bit back: an entry +/// whose content the patch left alone has nothing to restore, and a +/// restored file keeps the mode the patch left it with. +#[tokio::test] +async fn a_rollback_keeps_the_cleared_bits() { + // Content unchanged: already the original. + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let files = one(entry(CODE, CODE, Some("0644"))); + assert!(apply(pkg.path(), blobs.path(), &files, false).await.success); + let verify = verify_file_rollback(pkg.path(), FILE, &files[FILE], blobs.path()).await; + assert_eq!(verify.status, VerifyRollbackStatus::AlreadyOriginal); + let rolled = rollback_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + blobs.path(), + false, + ) + .await; + assert!(rolled.success, "{:?}", rolled.error); + assert_eq!(mode_of(&path), 0o644); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + + // Content changed: the bytes go back, the bits do not. + let (pkg, blobs) = package(CODE, 0o666); + let path = pkg.path().join(FILE); + let patched: &[u8] = b"patched\n"; + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + std::fs::write(blobs.path().join(hash(CODE)), CODE).unwrap(); + let files = one(entry(CODE, patched, Some("0644"))); + assert!(apply(pkg.path(), blobs.path(), &files, false).await.success); + let rolled = rollback_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + blobs.path(), + false, + ) + .await; + assert!(rolled.success, "{:?}", rolled.error); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + assert_eq!(mode_of(&path), 0o644); +} + +/// An entry whose `mode` is `raw` JSON, a value this release cannot read. +fn unreadable_entry(before: &[u8], after: &[u8], raw: &str) -> PatchFileInfo { + let info: PatchFileInfo = serde_json::from_str(&format!( + r#"{{"beforeHash":"{}","afterHash":"{}","mode":{raw}}}"#, + hash(before), + hash(after) + )) + .unwrap(); + assert!(!info.mode.as_ref().unwrap().is_readable(), "{raw}"); + info +} + +/// A file whose entry has a mode this release cannot read is neither +/// patched nor patchable, whatever it holds and whatever policy is asked +/// for: the patch fails with its own code before anything is written, +/// and that includes the files of the patch whose entries are fine. +#[tokio::test] +async fn a_mode_this_release_cannot_read_fails_its_patch_and_writes_nothing() { + const OTHER: &str = "lib/b.rb"; + let patched: &[u8] = b"module Octopoller; VERSION = 1; end\n"; + for raw in [r#""644""#, r#""0o644""#, "420", r#""u=rw,go=r""#] { + for (held, held_mode, before, after) in [ + // The fix is the bits alone, and the file is world-writable. + (CODE, 0o666, CODE, CODE), + // The same file with nothing to clear. + (CODE, 0o644, CODE, CODE), + // A content change still to make, and one already made. + (CODE, 0o666, CODE, patched), + (patched, 0o644, CODE, patched), + ] { + let (pkg, blobs) = package(held, held_mode); + let path = pkg.path().join(FILE); + let other = pkg.path().join(OTHER); + std::fs::write(&other, CODE).unwrap(); + chmod(&other, 0o666); + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + let files = HashMap::from([ + (FILE.to_string(), unreadable_entry(before, after, raw)), + (OTHER.to_string(), entry(CODE, patched, Some("0644"))), + ]); + let inode = std::fs::metadata(&path).unwrap().ino(); + let case = format!("{raw} over {held_mode:o}"); + + let verify = verify_file_patch(pkg.path(), FILE, &files[FILE]).await; + assert_eq!(verify.status, VerifyStatus::UnreadableMode, "{case}"); + assert!(!verify.permissions_only, "{case}"); + let message = verify.message.unwrap(); + assert!(message.contains(raw), "{case}: {message}"); + + for policy in [ + MismatchPolicy::Strict, + MismatchPolicy::Warn, + MismatchPolicy::Force, + ] { + for dry_run in [true, false] { + let result = apply_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + &PatchSources::blobs_only(blobs.path()), + dry_run, + policy, + ) + .await; + assert!(!result.success, "{case} {policy:?}"); + assert_eq!( + result.failure_cause(), + Some(ApplyFailureCause::Coded(UNREADABLE_FILE_MODE)), + "{case} {policy:?}" + ); + assert!(result.files_patched.is_empty(), "{case} {policy:?}"); + let error = result.error.unwrap(); + assert!(error.contains(FILE) && error.contains(raw), "{error}"); + } + } + assert_eq!(std::fs::read(&path).unwrap(), held, "{case}"); + assert_eq!(mode_of(&path), held_mode, "{case}"); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), inode, "{case}"); + assert_eq!(std::fs::read(&other).unwrap(), CODE, "{case}"); + assert_eq!(mode_of(&other), 0o666, "{case}"); + } + } +} + +/// A mode that cannot be read does not hide what the content says: a +/// file holding neither side of the entry is still a mismatch and a +/// missing one still missing, which is how a release variant that is not +/// the installed one is told from one that is. +#[tokio::test] +async fn a_mode_that_cannot_be_read_leaves_content_mismatches_as_they_are() { + let (pkg, _blobs) = package(b"something else\n", 0o644); + let info = unreadable_entry(CODE, b"patched\n", r#""644""#); + let verify = verify_file_patch(pkg.path(), FILE, &info).await; + assert_eq!(verify.status, VerifyStatus::HashMismatch); + let verify = verify_file_patch(pkg.path(), "lib/missing.rb", &info).await; + assert_eq!(verify.status, VerifyStatus::NotFound); +} + +/// Rollback restores content and never reads the mode, so it works on a +/// patch whose mode this release cannot read. +#[tokio::test] +async fn a_patch_with_a_mode_that_cannot_be_read_still_rolls_back() { + let patched: &[u8] = b"patched\n"; + let (pkg, blobs) = package(patched, 0o644); + let path = pkg.path().join(FILE); + std::fs::write(blobs.path().join(hash(CODE)), CODE).unwrap(); + let files = one(unreadable_entry(CODE, patched, r#""644""#)); + + let verify = verify_file_rollback(pkg.path(), FILE, &files[FILE], blobs.path()).await; + assert_eq!(verify.status, VerifyRollbackStatus::Ready); + let rolled = rollback_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + blobs.path(), + false, + ) + .await; + assert!(rolled.success, "{:?}", rolled.error); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + assert_eq!(mode_of(&path), 0o644); +} + +/// A copy judged by its content alone (a vendored artifact) is judged +/// the same whatever `mode` its entry has, readable or not. +#[tokio::test] +async fn a_content_only_check_never_reads_the_mode_or_the_bits() { + let (pkg, _blobs) = package(CODE, 0o666); + for info in [ + entry(CODE, CODE, Some("0644")), + entry(CODE, CODE, None), + unreadable_entry(CODE, CODE, r#""644""#), + ] { + let verify = verify_file_content(pkg.path(), FILE, &info).await; + assert_eq!( + verify.status, + VerifyStatus::AlreadyPatched, + "{:?}", + info.mode + ); + assert!(!verify.permissions_only); + } + let before = entry(CODE, b"patched\n", Some("0644")); + let verify = verify_file_content(pkg.path(), FILE, &before).await; + assert_eq!(verify.status, VerifyStatus::Ready); + assert!(!verify.permissions_only); +} + +/// Inside a group commit a captured write is given its file's mode when +/// the commit replaces it, and a write that changes no byte is dropped: +/// the bits are cleared when the change is staged. +#[test] +fn a_captured_write_clears_the_bits_when_it_is_staged() { + let root = tempfile::tempdir().unwrap(); + let root_path = root.path().canonicalize().unwrap(); + let pkg = root_path.join("pkg"); + let path = pkg.join(FILE); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, CODE).unwrap(); + chmod(&path, 0o666); + + let commit = crate::utils::group_commit::GroupCommit::begin(&root_path); + assert!(crate::utils::group_commit::is_capturing(&path)); + let mut write = PackageWrite::new(); + write + .stage_write( + &pkg, + FILE, + CODE, + &hash(CODE), + FileMode::parse("0644").as_ref(), + ) + .unwrap(); + assert_eq!(mode_of(&path), 0o644); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + drop(write); + drop(commit); +} diff --git a/crates/socket-patch-core/src/patch/conda_copy.rs b/crates/socket-patch-core/src/patch/conda_copy.rs index 21b5cb917a..ee82d44f7a 100644 --- a/crates/socket-patch-core/src/patch/conda_copy.rs +++ b/crates/socket-patch-core/src/patch/conda_copy.rs @@ -498,6 +498,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: "a".repeat(64), + mode: None, }, )]) } @@ -808,6 +809,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "a".repeat(64), + mode: None, }, )]); let build = conda_build(PURE, &site).await.unwrap(); diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 0d6bfbfbb6..3869d642d2 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -6685,6 +6685,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: after.to_string(), + mode: None, } } @@ -7802,6 +7803,7 @@ mod tests { let adds = PatchFileInfo { before_hash: String::new(), after_hash: "a".repeat(64), + mode: None, }; // C build inputs the record replaces: taken when the copy holds // them (dead code there), skipped when it does not. @@ -7986,6 +7988,7 @@ mod tests { let added = |after: &str| PatchFileInfo { before_hash: String::new(), after_hash: after.repeat(64), + mode: None, }; let record: HashMap = [ ("lib/a.rb".to_string(), info(&"1".repeat(64))), @@ -8155,6 +8158,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "5".repeat(64), + mode: None, }, )] .into(); @@ -8164,6 +8168,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: "8".repeat(64), + mode: None, }, )] .into() @@ -8196,6 +8201,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"int a;"), after_hash: "2".repeat(64), + mode: None, }, )] .into(); @@ -8261,6 +8267,7 @@ mod tests { let added = PatchFileInfo { before_hash: String::new(), after_hash: "5".repeat(64), + mode: None, }; let apply = |purl: &'static str, record: HashMap, rebuild: bool| { let (copy, blobs, cwd) = (copy.clone(), blobs.clone(), tmp.path().to_path_buf()); @@ -8715,6 +8722,7 @@ mod tests { PatchFileInfo { before_hash: before_c, after_hash: "c".repeat(64), + mode: None, }, ), // In the source gem alone: the precompiled copy never had it. @@ -8723,6 +8731,7 @@ mod tests { PatchFileInfo { before_hash: "b".repeat(64), after_hash: "d".repeat(64), + mode: None, }, ), ] @@ -9481,6 +9490,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"int a;"), after_hash: "c".repeat(64), + mode: None, }, )] .into(); @@ -9679,6 +9689,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"int a = 1;\n"), after_hash: compute_git_sha256_from_bytes(after.as_bytes()), + mode: None, }, )] .into(); @@ -9707,6 +9718,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "c".repeat(64), + mode: None, }, )] .into(); diff --git a/crates/socket-patch-core/src/patch/jar_manifest.rs b/crates/socket-patch-core/src/patch/jar_manifest.rs index 77159d6450..e1985e475c 100644 --- a/crates/socket-patch-core/src/patch/jar_manifest.rs +++ b/crates/socket-patch-core/src/patch/jar_manifest.rs @@ -424,6 +424,7 @@ pub(crate) mod fixture { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(BEFORE), after_hash: compute_git_sha256_from_bytes(AFTER), + mode: None, }, )]) } @@ -517,6 +518,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ) }); @@ -527,6 +529,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ) }); @@ -652,6 +655,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(manifest_of(upstream).as_bytes()), after_hash: compute_git_sha256_from_bytes(blob.as_bytes()), + mode: None, }, ); assert_ne!(manifest_of(served), blob); diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index b1107077de..d21ce471ad 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -208,6 +208,7 @@ fn statuses( expected_hash: (status == VerifyStatus::HashMismatch) .then(|| info.before_hash.clone()), target_hash: Some(info.after_hash.clone()), + permissions_only: false, } }) .collect() @@ -261,6 +262,7 @@ pub fn jar_copies(pkg_path: &Path, jar_leaf: &str) -> Vec { PatchFileInfo { before_hash: String::new(), after_hash: String::new(), + mode: None, }, )]); gradle_cache::installed_copies(pkg_path, &probe) @@ -990,7 +992,11 @@ fn rollback_verify(results: &[VerifyResult]) -> Vec { status: match v.status { VerifyStatus::AlreadyPatched => VerifyRollbackStatus::Ready, VerifyStatus::Ready => VerifyRollbackStatus::AlreadyOriginal, - VerifyStatus::HashMismatch => VerifyRollbackStatus::HashMismatch, + // A jar member has no permission bits, so `verify_members` + // never reports `UnreadableMode`. + VerifyStatus::HashMismatch | VerifyStatus::UnreadableMode => { + VerifyRollbackStatus::HashMismatch + } VerifyStatus::NotFound => VerifyRollbackStatus::NotFound, }, message: v.message.clone(), @@ -1209,6 +1215,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, } } @@ -1633,6 +1640,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(b"helper"), + mode: None, }, ); let restore = JarRestore { @@ -2091,6 +2099,7 @@ mod tests { PatchFileInfo { before_hash: zeros_hash.clone(), after_hash: compute_git_sha256_from_bytes(b"patched"), + mode: None, }, )]); let got = verify_member_bytes(&bytes, &ready); @@ -2102,6 +2111,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"pristine"), after_hash: zeros_hash.clone(), + mode: None, }, )]); assert_eq!( diff --git a/crates/socket-patch-core/src/patch/redirect/golang_local.rs b/crates/socket-patch-core/src/patch/redirect/golang_local.rs index cc6e865122..8fa426da95 100644 --- a/crates/socket-patch-core/src/patch/redirect/golang_local.rs +++ b/crates/socket-patch-core/src/patch/redirect/golang_local.rs @@ -1097,6 +1097,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after.clone(), + mode: None, }, ); @@ -2549,6 +2550,7 @@ mod tests { PatchFileInfo { before_hash: "0".repeat(64), after_hash: "1".repeat(64), + mode: None, }, ); @@ -2888,6 +2890,7 @@ mod tests { PatchFileInfo { before_hash: "b".into(), after_hash: "a".into(), + mode: None, }, ); manifest.patches.insert( diff --git a/crates/socket-patch-core/src/patch/redirect/state.rs b/crates/socket-patch-core/src/patch/redirect/state.rs index 98d0b620e6..14d4f924e3 100644 --- a/crates/socket-patch-core/src/patch/redirect/state.rs +++ b/crates/socket-patch-core/src/patch/redirect/state.rs @@ -174,6 +174,7 @@ mod tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); let mut vulns = HashMap::new(); diff --git a/crates/socket-patch-core/src/patch/rollback.rs b/crates/socket-patch-core/src/patch/rollback.rs index d1756e3e6e..b7f249a79a 100644 --- a/crates/socket-patch-core/src/patch/rollback.rs +++ b/crates/socket-patch-core/src/patch/rollback.rs @@ -836,9 +836,12 @@ async fn rollback_package_patch_at( Err(msg) => Err(msg), }; match formed { + // The file keeps the mode it has: a rollback restores + // content, and never gives back a write bit a patch cleared. Ok((content, hash)) => FileChange::Write { content: content.into_owned(), hash, + mode: None, }, Err(msg) => { crate::patch::apply::abort_package(write).await; @@ -971,6 +974,7 @@ mod tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); } @@ -997,6 +1001,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaa".to_string(), after_hash: "bbb".to_string(), + mode: None, }; let result = verify_file_rollback( @@ -1023,6 +1028,7 @@ mod tests { // A well-formed (64-hex) hash that no blob carries. before_hash: "0".repeat(64), after_hash: compute_git_sha256_from_bytes(content), + mode: None, }; let result = @@ -1054,6 +1060,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: before_hash.clone(), after_hash: after_hash.clone(), + mode: None, }; let result = @@ -1083,6 +1090,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: before_hash.clone(), after_hash: "bbbb".to_string(), + mode: None, }; let result = @@ -1111,6 +1119,7 @@ mod tests { let file_info = PatchFileInfo { before_hash, after_hash: "expected_after_hash".to_string(), + mode: None, }; let result = @@ -1298,6 +1307,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); @@ -1362,6 +1372,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash, + mode: None, }, ); @@ -1409,6 +1420,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); @@ -1454,6 +1466,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: "bbbb".to_string(), + mode: None, }, ); @@ -1487,6 +1500,7 @@ mod tests { // A well-formed (64-hex) hash that no blob carries. before_hash: "0".repeat(64), after_hash: "bbbb".to_string(), + mode: None, }, ); @@ -1525,6 +1539,7 @@ mod tests { let file_info = PatchFileInfo { before_hash, after_hash: "some_after_hash".to_string(), + mode: None, }; let result = @@ -1566,6 +1581,7 @@ mod tests { PatchFileInfo { before_hash: a_before, after_hash: "a_after".to_string(), + mode: None, }, ); files.insert( @@ -1573,6 +1589,7 @@ mod tests { PatchFileInfo { before_hash: b_before, after_hash: b_after, + mode: None, }, ); @@ -1611,6 +1628,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaa".to_string(), after_hash: "bbb".to_string(), + mode: None, }; for escape in ["package/../../escape.js", "../escape.js", "/etc/passwd"] { @@ -1652,6 +1670,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(sentinel_content), + mode: None, }, ); @@ -1693,6 +1712,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash, + mode: None, }, ); @@ -1727,6 +1747,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(b"whatever"), + mode: None, }, ); @@ -1774,6 +1795,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash, + mode: None, }, ); @@ -1823,6 +1845,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(body.as_bytes()), + mode: None, }, ); } @@ -2077,6 +2100,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: before_hash.clone(), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }; let result = verify_file_rollback(&pkg_dir, "index.js", &file_info, &blobs_dir).await; assert_ne!( @@ -2121,6 +2145,7 @@ mod tests { PatchFileInfo { before_hash: "../secret.txt".to_string(), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, ); @@ -2174,6 +2199,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(b"added by patch\n"), + mode: None, }, ); @@ -2260,6 +2286,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash, + mode: None, }, ); files.insert( @@ -2267,6 +2294,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(added), + mode: None, }, ); @@ -2349,6 +2377,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(original), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, ), ( @@ -2356,6 +2385,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(added), + mode: None, }, ), ]); @@ -2420,6 +2450,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, ); @@ -2538,6 +2569,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original a"), after_hash: compute_git_sha256_from_bytes(b"patched a"), + mode: None, }, ); files.insert( @@ -2545,6 +2577,7 @@ mod tests { PatchFileInfo { before_hash: b_before, after_hash: compute_git_sha256_from_bytes(b"patched b"), + mode: None, }, ); @@ -2614,6 +2647,7 @@ mod tests { let file_info = PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }; let result = verify_file_rollback(&pkg_dir, "index.js", &file_info, &blobs_dir).await; @@ -2656,6 +2690,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "sub/secret.txt".to_string(), after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }; let verify = verify_file_rollback(&pkg_dir, "index.js", &file_info, &blobs_dir).await; @@ -2778,6 +2813,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }, ); @@ -2836,6 +2872,7 @@ mod tests { let file_info = PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(patched), + mode: None, }; let result = @@ -2867,6 +2904,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(b"x"), + mode: None, }; let result = verify_file_rollback( @@ -2913,6 +2951,7 @@ mod tests { let file_info = PatchFileInfo { before_hash: "aaa".to_string(), after_hash: "bbb".to_string(), + mode: None, }; let result = @@ -2973,6 +3012,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash, + mode: None, }, ); @@ -3038,6 +3078,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash, + mode: None, }, ); @@ -3101,6 +3142,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: hash(b"added"), + mode: None, }, ); for name in ["b.js", "c.js"] { @@ -3121,6 +3163,7 @@ mod tests { PatchFileInfo { before_hash: hash(original.as_bytes()), after_hash: hash(patched.as_bytes()), + mode: None, }, ); } @@ -3182,6 +3225,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash, + mode: None, }, ); @@ -3266,6 +3310,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash, + mode: None, }, ); @@ -3367,6 +3412,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(&patched), + mode: None, }, ); for dry_run in [true, false] { @@ -3429,6 +3475,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(&patched), + mode: None, }, ); for dry_run in [true, false] { @@ -3482,6 +3529,7 @@ mod tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); @@ -3528,6 +3576,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, )]); let res = rollback_package_patch( @@ -3592,6 +3641,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, )]); let res = rollback_package_patch( @@ -3623,6 +3673,7 @@ mod tests { PatchFileInfo { before_hash: before_hash.clone(), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, )]); for with_blob in [true, false] { @@ -3689,6 +3740,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(b"#!/usr/bin/env node\r\nnew();\r\n"), + mode: None, }, )]); let res = rollback_package_patch( @@ -3726,6 +3778,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, )]); let res = rollback_package_patch( @@ -3763,6 +3816,7 @@ mod tests { PatchFileInfo { before_hash, after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, )]); let res = rollback_package_patch( diff --git a/crates/socket-patch-core/src/patch/store_copies.rs b/crates/socket-patch-core/src/patch/store_copies.rs index 8650a8e8cd..a061e0c45d 100644 --- a/crates/socket-patch-core/src/patch/store_copies.rs +++ b/crates/socket-patch-core/src/patch/store_copies.rs @@ -165,6 +165,7 @@ mod regression_tests { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); (root, primary, copies, blobs, files) diff --git a/crates/socket-patch-core/src/utils/purl_key_nuget_vendor_tests.rs b/crates/socket-patch-core/src/utils/purl_key_nuget_vendor_tests.rs index f9d67998df..c103769ff7 100644 --- a/crates/socket-patch-core/src/utils/purl_key_nuget_vendor_tests.rs +++ b/crates/socket-patch-core/src/utils/purl_key_nuget_vendor_tests.rs @@ -97,6 +97,7 @@ async fn fixture(root: &Path) -> (std::path::PathBuf, std::path::PathBuf, PatchR PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: after, + mode: None, }, )]); let record = PatchRecord { diff --git a/crates/socket-patch-core/src/vendor/bun_binary.rs b/crates/socket-patch-core/src/vendor/bun_binary.rs index 83be665429..5580bf2bc7 100644 --- a/crates/socket-patch-core/src/vendor/bun_binary.rs +++ b/crates/socket-patch-core/src/vendor/bun_binary.rs @@ -2737,6 +2737,7 @@ mod rebuild_tests { crate::manifest::schema::PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PACKAGE), after_hash, + mode: None, }, ); let manifest_warnings = |w: &[VendorWarning]| { diff --git a/crates/socket-patch-core/src/vendor/bun_lock.rs b/crates/socket-patch-core/src/vendor/bun_lock.rs index d82f6d4139..74d29acd06 100644 --- a/crates/socket-patch-core/src/vendor/bun_lock.rs +++ b/crates/socket-patch-core/src/vendor/bun_lock.rs @@ -2065,6 +2065,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&before), after_hash, + mode: None, }, ); fx @@ -2132,6 +2133,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -2290,6 +2292,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); @@ -3336,6 +3339,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); diff --git a/crates/socket-patch-core/src/vendor/cargo.rs b/crates/socket-patch-core/src/vendor/cargo.rs index 8a745db4ad..d721d61b4c 100644 --- a/crates/socket-patch-core/src/vendor/cargo.rs +++ b/crates/socket-patch-core/src/vendor/cargo.rs @@ -2285,6 +2285,7 @@ mod tests { PatchFileInfo { before_hash: git_sha(PRISTINE), after_hash: after, + mode: None, }, ); @@ -6275,6 +6276,7 @@ mod tests { PatchFileInfo { before_hash: git_sha(&before), after_hash: git_sha(&after), + mode: None, }, ); let (result, entry, _) = diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 8f1cce2275..5deb859cbc 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -34,6 +34,7 @@ fn already_patched_verify(file: &str) -> VerifyResult { current_hash: None, expected_hash: None, target_hash: None, + permissions_only: false, } } @@ -1057,6 +1058,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(b"patched\n"), + mode: None, }, )]); (jar, files, zip_bytes) @@ -1090,6 +1092,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(content), + mode: None, }, ) }) @@ -1148,6 +1151,7 @@ mod tests { // Python hashlib: sha256(b"blob 67108865\0" + 67108865 zero bytes). after_hash: "453f670092f0481b99614c8a1a5846335799943dd26f5375274e08fa5f12744f" .to_string(), + mode: None, }, )]); assert!(zip_bytes_match_after_hashes(&bytes, &files)); @@ -1183,6 +1187,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(b"patched\n"), + mode: None, }, )]); assert!( @@ -1202,6 +1207,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(b"patched\n"), + mode: None, }, )]); assert!( @@ -1245,6 +1251,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: "0".repeat(64), + mode: None, }, )]); assert!( @@ -1266,6 +1273,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(b"patched\n"), + mode: None, }, )]); assert!( @@ -1292,6 +1300,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: compute_git_sha256_from_bytes(b"patched\n"), + mode: None, }, )]); assert!( @@ -1330,6 +1339,7 @@ mod tests { PatchFileInfo { before_hash: "before".to_string(), after_hash: "after".to_string(), + mode: None, }, )]); diff --git a/crates/socket-patch-core/src/vendor/composer_lock.rs b/crates/socket-patch-core/src/vendor/composer_lock.rs index 46b33ee717..bf9cdc7c30 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -1076,6 +1076,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let mut vulnerabilities = HashMap::new(); @@ -4307,6 +4308,7 @@ mod tests { PatchFileInfo { before_hash: hash.clone(), after_hash: hash, + mode: None, }, ); let lock_before = tokio::fs::read(root.join(COMPOSER_LOCK)).await.unwrap(); diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 339dbf08f9..c4855a78aa 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -4635,6 +4635,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let record = PatchRecord { @@ -6494,6 +6495,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let record = PatchRecord { @@ -7135,6 +7137,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let record = PatchRecord { @@ -12030,6 +12033,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ) }) diff --git a/crates/socket-patch-core/src/vendor/go_native_vendor.rs b/crates/socket-patch-core/src/vendor/go_native_vendor.rs index 28fb23a772..1d411b210a 100644 --- a/crates/socket-patch-core/src/vendor/go_native_vendor.rs +++ b/crates/socket-patch-core/src/vendor/go_native_vendor.rs @@ -957,6 +957,7 @@ mod tests { crate::manifest::schema::PatchFileInfo { before_hash: String::new(), after_hash: after.to_string(), + mode: None, }, ) }) diff --git a/crates/socket-patch-core/src/vendor/golang.rs b/crates/socket-patch-core/src/vendor/golang.rs index cf9b5aee9c..e247947cec 100644 --- a/crates/socket-patch-core/src/vendor/golang.rs +++ b/crates/socket-patch-core/src/vendor/golang.rs @@ -829,6 +829,7 @@ mod tests { PatchFileInfo { before_hash: git_sha(PRISTINE), after_hash: after, + mode: None, }, ); diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index da7a93d28c..be097217b7 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -2939,6 +2939,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: after, + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 0f7a5ebf33..038a1cffb9 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -1142,6 +1142,7 @@ mod harvest_tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original"), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ); ( @@ -1709,6 +1710,7 @@ mod harvest_tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original"), after_hash: compute_git_sha256_from_bytes(OTHER), + mode: None, }, ); let patches = HashMap::from([(k, r)]); @@ -2032,6 +2034,7 @@ mod harvest_tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original"), after_hash: String::new(), + mode: None, }, ); r.files.insert( @@ -2039,6 +2042,7 @@ mod harvest_tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"original"), after_hash: compute_git_sha256_from_bytes(b"expected patched content"), + mode: None, }, ); let patches = HashMap::from([(k, r)]); diff --git a/crates/socket-patch-core/src/vendor/npm_common.rs b/crates/socket-patch-core/src/vendor/npm_common.rs index 0b1b644ef4..6b4d12c6a9 100644 --- a/crates/socket-patch-core/src/vendor/npm_common.rs +++ b/crates/socket-patch-core/src/vendor/npm_common.rs @@ -982,6 +982,7 @@ mod tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: "b".repeat(64), + mode: None, }, ); PatchRecord { @@ -1246,6 +1247,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); (tmp, record) @@ -1484,6 +1486,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash: compute_git_sha256_from_bytes(PATCHED_INDEX), + mode: None, }, ); record @@ -1527,6 +1530,7 @@ mod tests { PatchFileInfo { before_hash: "c".repeat(64), after_hash: "d".repeat(64), + mode: None, }, ); record diff --git a/crates/socket-patch-core/src/vendor/npm_flavor.rs b/crates/socket-patch-core/src/vendor/npm_flavor.rs index f81fe7350b..5c3bca20d9 100644 --- a/crates/socket-patch-core/src/vendor/npm_flavor.rs +++ b/crates/socket-patch-core/src/vendor/npm_flavor.rs @@ -2146,6 +2146,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG), after_hash, + mode: None, }, ); let record = crate::manifest::schema::PatchRecord { diff --git a/crates/socket-patch-core/src/vendor/npm_lock.rs b/crates/socket-patch-core/src/vendor/npm_lock.rs index bb2e82632e..21a43af44a 100644 --- a/crates/socket-patch-core/src/vendor/npm_lock.rs +++ b/crates/socket-patch-core/src/vendor/npm_lock.rs @@ -2144,6 +2144,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -4211,6 +4212,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&before), after_hash, + mode: None, }, ); @@ -4253,6 +4255,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); @@ -4309,6 +4312,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&before), after_hash, + mode: None, }, ); let manifest_warnings = |w: &[VendorWarning]| { @@ -6538,6 +6542,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(&before), after_hash, + mode: None, }, ); fx diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 3cc314f0cb..a5fb4f554a 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -2952,6 +2952,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(PRISTINE), after_hash: after, + mode: None, }, ); let mut vulnerabilities = HashMap::new(); diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 7e0cd84616..0ad4694b5c 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -4945,6 +4945,7 @@ snapshots: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -10557,6 +10558,7 @@ snapshots: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(installed_manifest), after_hash, + mode: None, }, ); @@ -10590,6 +10592,7 @@ snapshots: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs b/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs index abb042c142..cd9e9d7e0c 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs @@ -2316,6 +2316,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, )]), vulnerabilities: HashMap::new(), diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock_legacy.rs b/crates/socket-patch-core/src/vendor/pnpm_lock_legacy.rs index 1762099a1e..6f27431791 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock_legacy.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock_legacy.rs @@ -1471,6 +1471,7 @@ packages: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -3125,6 +3126,7 @@ packages: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_MANIFEST), after_hash, + mode: None, }, ); @@ -3156,6 +3158,7 @@ packages: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); diff --git a/crates/socket-patch-core/src/vendor/prestage.rs b/crates/socket-patch-core/src/vendor/prestage.rs index 78f5d4c98a..2da2025214 100644 --- a/crates/socket-patch-core/src/vendor/prestage.rs +++ b/crates/socket-patch-core/src/vendor/prestage.rs @@ -619,6 +619,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: "0".repeat(64), + mode: None, }, )]); let (_, prestaged) = run(&PrestageRecipe::verify_zip(&files), b"not a zip".to_vec()).await; diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index 9beeb475ba..922089cea3 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -5018,6 +5018,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); let record = PatchRecord { diff --git a/crates/socket-patch-core/src/vendor/reuse.rs b/crates/socket-patch-core/src/vendor/reuse.rs index 776a412af2..a74f883b02 100644 --- a/crates/socket-patch-core/src/vendor/reuse.rs +++ b/crates/socket-patch-core/src/vendor/reuse.rs @@ -366,6 +366,7 @@ mod tests { PatchFileInfo { before_hash: "a".repeat(64), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index eca4508e14..9320ef6289 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -870,6 +870,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"unpatched"), after_hash: compute_git_sha256_from_bytes(b"patched"), + mode: None, }, ); for source in [VendorSource::Service] { diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 50989a413c..6e69d9772c 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -1877,6 +1877,7 @@ mod tests { PatchFileInfo { before_hash: "aa".repeat(32), after_hash: "bb".repeat(32), + mode: None, }, )]), vulnerabilities: HashMap::from([( diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 0e9785611f..137d3abbef 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -36,7 +36,8 @@ use crate::bazel::cargo_bazel::{self, BUILD_FILE}; use crate::hash::git_sha256::compute_git_sha256_from_bytes; use crate::manifest::schema::{PatchFileInfo, PatchRecord}; use crate::patch::apply::{ - is_missing_path, is_safe_relative_subpath, normalize_file_path, verify_file_patch, VerifyStatus, + is_missing_path, is_safe_relative_subpath, normalize_file_path, verify_file_content, + VerifyStatus, }; use crate::patch::file_hash::compute_file_git_sha256; use crate::patch::package::read_archive_to_map; @@ -247,7 +248,7 @@ async fn verify_dir_members( cargo_uuid: Option<&str>, ) -> Result<(), String> { for (file_name, info) in &record.files { - let result = verify_file_patch(dir, file_name, info).await; + let result = verify_file_content(dir, file_name, info).await; match result.status { VerifyStatus::AlreadyPatched => continue, VerifyStatus::Ready | VerifyStatus::HashMismatch @@ -261,7 +262,7 @@ async fn verify_dir_members( { continue } - VerifyStatus::Ready | VerifyStatus::HashMismatch => { + VerifyStatus::Ready | VerifyStatus::HashMismatch | VerifyStatus::UnreadableMode => { return Err("vendor_hash_mismatch".to_string()) } VerifyStatus::NotFound => return Err("file_not_found".to_string()), @@ -472,9 +473,9 @@ async fn verify_vlt_dir( unpinned_vlt_manifest(project_root, dir, file_name, info).await?; continue; } - match verify_file_patch(dir, file_name, info).await.status { + match verify_file_content(dir, file_name, info).await.status { VerifyStatus::AlreadyPatched => {} - VerifyStatus::Ready | VerifyStatus::HashMismatch => { + VerifyStatus::Ready | VerifyStatus::HashMismatch | VerifyStatus::UnreadableMode => { return Err("vendor_hash_mismatch".to_string()) } VerifyStatus::NotFound => return Err("file_not_found".to_string()), @@ -535,7 +536,7 @@ pub(crate) async fn vlt_installed_copy_matches( } continue; } - if verify_file_patch(installed, file_name, info).await.status + if verify_file_content(installed, file_name, info).await.status != VerifyStatus::AlreadyPatched { return false; @@ -580,10 +581,10 @@ async fn unpinned_vlt_manifest( file_name: &str, info: &PatchFileInfo, ) -> Result<(), String> { - match verify_file_patch(dir, file_name, info).await.status { + match verify_file_content(dir, file_name, info).await.status { VerifyStatus::AlreadyPatched => return Ok(()), VerifyStatus::NotFound => return Err("file_not_found".to_string()), - VerifyStatus::Ready | VerifyStatus::HashMismatch => {} + VerifyStatus::Ready | VerifyStatus::HashMismatch | VerifyStatus::UnreadableMode => {} } let Some(blob) = local_after_blob(project_root, &info.after_hash).await else { return Err("vendor_manifest_unverifiable".to_string()); @@ -1281,6 +1282,7 @@ mod tests { PatchFileInfo { before_hash: "b".into(), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); PatchRecord { @@ -1847,6 +1849,7 @@ mod tests { PatchFileInfo { before_hash: "b".into(), after_hash: compute_git_sha256_from_bytes(untagged.as_bytes()), + mode: None, }, ); let mut ent = entry("cargo", UUID, &rel); @@ -2081,6 +2084,30 @@ mod tests { let ent = entry("cargo", UUID, &rel); assert!(verify_vendored_patch_record(root, &ent, &rec).await.is_ok()); + // A committed artifact is judged by its content alone: the bits a + // checkout gives its files (group-writable under umask 002) are + // not the package's, so an entry's `mode` is not read, whether + // this release can read it or not. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions( + dir.join("src/lib.rs"), + std::fs::Permissions::from_mode(0o666), + ) + .unwrap(); + for mode in [r#""0644""#, r#""u=rw,go=r""#] { + let mut with_mode = rec.clone(); + with_mode.files.get_mut("src/lib.rs").unwrap().mode = + Some(serde_json::from_str(mode).unwrap()); + assert_eq!( + verify_vendored_patch_record(root, &ent, &with_mode).await, + Ok(()), + "{mode}" + ); + } + } + tokio::fs::write(dir.join("src/lib.rs"), b"tampered") .await .unwrap(); @@ -2583,6 +2610,7 @@ mod tests { PatchFileInfo { before_hash: "b".into(), after_hash: compute_git_sha256_from_bytes(blob), + mode: None, }, ); let mut ent = entry("npm", UUID, &rel); diff --git a/crates/socket-patch-core/src/vendor/vlt_lock.rs b/crates/socket-patch-core/src/vendor/vlt_lock.rs index 65c1265d2e..72f8295e93 100644 --- a/crates/socket-patch-core/src/vendor/vlt_lock.rs +++ b/crates/socket-patch-core/src/vendor/vlt_lock.rs @@ -2455,6 +2455,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG), after_hash: compute_git_sha256_from_bytes(PATCHED), + mode: None, }, ); PatchRecord { @@ -3688,6 +3689,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(patched_pkg), + mode: None, }, ); let sources = PatchSources::blobs_only(&fx.blobs); @@ -3761,6 +3763,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: compute_git_sha256_from_bytes(patched_pkg), + mode: None, }, ); let sources = PatchSources::blobs_only(&fx.blobs); @@ -3814,6 +3817,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), after_hash: after_hash.clone(), + mode: None, }, ); let sources = PatchSources::blobs_only(&fx.blobs); diff --git a/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs b/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs index ae02662fee..8c5d54ec22 100644 --- a/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs +++ b/crates/socket-patch-core/src/vendor/yarn_berry_lock.rs @@ -2108,6 +2108,7 @@ __metadata: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -3049,6 +3050,7 @@ __metadata: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); @@ -3088,6 +3090,7 @@ __metadata: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); diff --git a/crates/socket-patch-core/src/vendor/yarn_classic_lock.rs b/crates/socket-patch-core/src/vendor/yarn_classic_lock.rs index a842fb9680..862c8cbba6 100644 --- a/crates/socket-patch-core/src/vendor/yarn_classic_lock.rs +++ b/crates/socket-patch-core/src/vendor/yarn_classic_lock.rs @@ -1300,6 +1300,7 @@ left-pad@^1.3.0, left-pad@~1.3.0: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash, + mode: None, }, ); let record = PatchRecord { @@ -1510,6 +1511,7 @@ wow@^1.0.0: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); @@ -1548,6 +1550,7 @@ wow@^1.0.0: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); } @@ -1735,6 +1738,7 @@ wow@^1.0.0: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (result, entry, warnings) = expect_done(fx.vendor(false).await); @@ -1783,6 +1787,7 @@ wow@^1.0.0: PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash, + mode: None, }, ); let (r, e, _) = expect_done(flip_run(&fx, None).await); diff --git a/crates/socket-patch-core/src/vendor/yarn_layering_tests.rs b/crates/socket-patch-core/src/vendor/yarn_layering_tests.rs index e982efac32..d2df06f925 100644 --- a/crates/socket-patch-core/src/vendor/yarn_layering_tests.rs +++ b/crates/socket-patch-core/src/vendor/yarn_layering_tests.rs @@ -153,6 +153,7 @@ fn record_for(after_hash: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIG_INDEX), after_hash: after_hash.to_string(), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-core/src/vex/build.rs b/crates/socket-patch-core/src/vex/build.rs index 4a9b4e1276..3a6957bb09 100644 --- a/crates/socket-patch-core/src/vex/build.rs +++ b/crates/socket-patch-core/src/vex/build.rs @@ -447,6 +447,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "bbbb".to_string(), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-core/src/vex/conformance_tests.rs b/crates/socket-patch-core/src/vex/conformance_tests.rs index b8e6d9552f..50b53987bf 100644 --- a/crates/socket-patch-core/src/vex/conformance_tests.rs +++ b/crates/socket-patch-core/src/vex/conformance_tests.rs @@ -34,6 +34,7 @@ fn record(uuid: &str, vulns: &[(&str, &[&str])]) -> PatchRecord { PatchFileInfo { before_hash: "aa".to_string(), after_hash: "bb".to_string(), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 3bad1c47a2..06cc271acf 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -364,6 +364,7 @@ fn status_verdict(status: VerifyStatus) -> Result<(), String> { VerifyStatus::Ready => Err("not_applied".to_string()), VerifyStatus::HashMismatch => Err("hash_mismatch".to_string()), VerifyStatus::NotFound => Err("file_not_found".to_string()), + VerifyStatus::UnreadableMode => Err(crate::patch::apply::UNREADABLE_FILE_MODE.to_string()), } } @@ -412,12 +413,15 @@ async fn verify_member_copies( #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct InstalledRecordJudgment { /// [`verify_patch_record`] would return `Ok`: the record has files and - /// every one hashes to its `afterHash`. + /// every one hashes to its `afterHash`, without a write bit its entry's + /// `mode` does not grant. pub patched: bool, - /// At least one record file was actually read and hashed to something - /// other than its `afterHash` (`verify_file_patch`'s `Ready` or - /// `HashMismatch` WITH a `current_hash`). Missing, unreadable and - /// unsafe-path files are never evidence. + /// At least one record file was actually read and is not the patched + /// file: it hashed to something other than its `afterHash`, or holds + /// the patched bytes under a write bit its entry's `mode` does not + /// grant (`verify_file_patch`'s `Ready` or `HashMismatch` WITH a + /// `current_hash`). Missing, unreadable and unsafe-path files are never + /// evidence. pub stale_evidence: bool, } @@ -435,13 +439,13 @@ pub async fn judge_installed_record( pkg_path: &Path, record: &PatchRecord, ) -> InstalledRecordJudgment { - let copies: Vec<(PathBuf, Vec<(String, String)>)> = + let copies: Vec<(PathBuf, Vec)> = crate::crawlers::gradle_cache::installed_copies(pkg_path, &record.files) .into_iter() .map(|(dir, files)| { let files = files .into_iter() - .map(|(name, info)| (name, info.after_hash)) + .map(|(name, info)| (name, info.after_hash, info.mode)) .collect(); (dir, files) }) @@ -464,25 +468,51 @@ pub async fn judge_installed_record( .await } -fn judge_installed_files(pkg_path: &Path, files: &[(String, String)]) -> InstalledRecordJudgment { - use crate::patch::apply::{is_safe_relative_subpath, normalize_file_path}; +/// A record file as [`judge_installed_files`] reads it: its key, its +/// `afterHash` and its entry's `mode`. +type JudgedFile = (String, String, Option); + +fn judge_installed_files(pkg_path: &Path, files: &[JudgedFile]) -> InstalledRecordJudgment { + use crate::patch::apply::{is_safe_relative_subpath, mode_excess, normalize_file_path}; use crate::patch::file_hash::compute_file_git_sha256_sync; + // The patched bytes under a write bit the entry's mode does not grant + // are `verify_file_patch`'s `Ready`: the copy is not the patched one. + let excess_bits = |path: &Path, mode: &Option| { + mode.as_ref() + .zip(std::fs::metadata(path).ok()) + .is_some_and(|(mode, meta)| mode_excess(&meta, mode) != 0) + }; let mut all_patched = !files.is_empty(); - for (file_name, after_hash) in files { + for (file_name, after_hash, mode) in files { + // A mode this release cannot read (`verify_file_patch`'s + // `UnreadableMode`): the file cannot be judged, so the copy is not + // the patched one, and nothing about it is evidence. + if mode.as_ref().is_some_and(|mode| !mode.is_readable()) { + all_patched = false; + continue; + } let normalized = normalize_file_path(file_name); // An unsafe key never resolves (verify_file_patch's NotFound). let hashed = is_safe_relative_subpath(normalized) .then(|| compute_file_git_sha256_sync(&pkg_path.join(normalized)).ok()) .flatten(); match hashed { - Some(hash) if &hash == after_hash => {} + Some(hash) if &hash == after_hash && !excess_bits(&pkg_path.join(normalized), mode) => { + } + Some(hash) if &hash == after_hash => { + return InstalledRecordJudgment { + patched: false, + stale_evidence: true, + } + } // npm's LF-shebang form of the patched bin (see `npm_bin`), // which `verify_file_patch` also accepts. Some(_) if crate::patch::npm_bin::source_hash_sync(&pkg_path.join(normalized)) .as_deref() - == Some(after_hash.as_str()) => {} + == Some(after_hash.as_str()) + && !excess_bits(&pkg_path.join(normalized), mode) => {} Some(_) => { return InstalledRecordJudgment { patched: false, @@ -924,6 +954,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: after_hash.to_string(), + mode: None, }, ); PatchRecord { @@ -1144,6 +1175,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: hash_a, + mode: None, }, ); files.insert( @@ -1151,6 +1183,7 @@ mod tests { PatchFileInfo { before_hash: before_b, after_hash: "deadbeef".to_string(), + mode: None, }, ); @@ -1311,6 +1344,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "deadbeef".to_string(), + mode: None, }, ); files.insert( @@ -1318,6 +1352,7 @@ mod tests { PatchFileInfo { before_hash: "cccc".to_string(), after_hash: hash_b, + mode: None, }, ); @@ -1369,6 +1404,7 @@ mod tests { PatchFileInfo { before_hash: String::new(), // new file after_hash: hash, + mode: None, }, ); @@ -1407,6 +1443,7 @@ mod tests { before_hash: String::new(), // new file, not yet created after_hash: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" .to_string(), + mode: None, }, ); @@ -1451,6 +1488,7 @@ mod tests { PatchFileInfo { before_hash: hash.clone(), after_hash: hash, + mode: None, }, ); @@ -1499,6 +1537,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: hash_a, + mode: None, }, ); files.insert( @@ -1506,6 +1545,7 @@ mod tests { PatchFileInfo { before_hash: "bbbb".to_string(), after_hash: hash_b, + mode: None, }, ); @@ -1601,6 +1641,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: hash, // matches the out-of-tree file + mode: None, }, ); @@ -1716,6 +1757,7 @@ mod tests { PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "deadbeef".to_string(), + mode: None, }, ); files.insert( @@ -1723,6 +1765,7 @@ mod tests { PatchFileInfo { before_hash: "bbbb".to_string(), after_hash: "deadbeef".to_string(), + mode: None, }, ); @@ -1982,6 +2025,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let rec = PatchRecord { @@ -2052,6 +2096,7 @@ mod tests { PatchFileInfo { before_hash: before, after_hash: after, + mode: None, }, ); let rec = PatchRecord { @@ -2746,6 +2791,7 @@ mod tests { crate::manifest::schema::PatchFileInfo { before_hash: "b".repeat(64), after_hash: compute_git_sha256_from_bytes(blob), + mode: None, }, ); let mut entry = vendor_entry(purl, &rel); @@ -2852,11 +2898,23 @@ mod tests { } else { upstream.clone() }; + // An entry's mode is part of both verdicts: the patched + // bytes under a write bit it does not grant are stale. + let mode = rng + .chance(40) + .then(|| crate::manifest::schema::FileMode::parse("0644").unwrap()); + #[cfg(unix)] + if rng.chance(40) && std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_file()) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)) + .unwrap(); + } files.insert( name, PatchFileInfo { before_hash, after_hash: patched.clone(), + mode, }, ); } @@ -2886,6 +2944,92 @@ mod tests { ); } + /// The patched bytes under a write bit the entry's `mode` does not + /// grant are not the patched file, for the attestation and for the + /// stale-install probes alike: a copy installed from the upstream + /// archive of a release whose fix is its permissions holds exactly + /// those bytes. + #[cfg(unix)] + #[tokio::test] + async fn patched_bytes_under_excess_write_bits_are_not_applied() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("index.js"); + std::fs::write(&path, b"patched").unwrap(); + let chmod = |mode: u32| { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap() + }; + let hash = compute_git_sha256_from_bytes(b"patched"); + let mut record = record_with_one_file(&hash); + let entry = record.files.get_mut("index.js").unwrap(); + // The content is the fix's and the release's alike. + entry.before_hash = hash.clone(); + entry.mode = crate::manifest::schema::FileMode::parse("0644"); + + chmod(0o666); + assert_eq!( + verify_patch_record(dir.path(), &record).await, + Err("not_applied".to_string()) + ); + assert_eq!( + judge_installed_record(dir.path(), &record).await, + InstalledRecordJudgment { + patched: false, + stale_evidence: true, + } + ); + + chmod(0o644); + assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); + assert_eq!( + judge_installed_record(dir.path(), &record).await, + InstalledRecordJudgment { + patched: true, + stale_evidence: false, + } + ); + + // Without a mode the bits are not part of the patch. + chmod(0o666); + record.files.get_mut("index.js").unwrap().mode = None; + assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); + assert!(judge_installed_record(dir.path(), &record).await.patched); + } + + /// A record with a file mode this release cannot read is never applied + /// and never stale evidence, whatever the file holds: it cannot be + /// judged. Its other records are judged as before. + #[cfg(unix)] + #[tokio::test] + async fn a_record_with_a_mode_that_cannot_be_read_is_never_applied() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("index.js"); + std::fs::write(&path, b"patched").unwrap(); + let hash = compute_git_sha256_from_bytes(b"patched"); + let mut record = record_with_one_file(&hash); + let entry = record.files.get_mut("index.js").unwrap(); + entry.before_hash = hash.clone(); + entry.mode = Some(serde_json::from_str(r#""u=rw,go=r""#).unwrap()); + + for mode in [0o666, 0o644, 0o600] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + assert_eq!( + verify_patch_record(dir.path(), &record).await, + Err("unreadable_file_mode".to_string()), + "{mode:o}" + ); + assert_eq!( + judge_installed_record(dir.path(), &record).await, + InstalledRecordJudgment { + patched: false, + stale_evidence: false, + }, + "{mode:o}" + ); + } + } + // ── Maven / Gradle copy sets ──────────────────────────────────── fn stored_jar(members: &[(&str, &[u8])]) -> Vec { @@ -2915,6 +3059,7 @@ mod tests { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(before), after_hash: compute_git_sha256_from_bytes(after), + mode: None, }, ) }) @@ -3086,6 +3231,7 @@ mod tests { let file = |before: &str, after: &str| PatchFileInfo { before_hash: before.to_string(), after_hash: after.to_string(), + mode: None, }; let record_of = |files: &[(&str, PatchFileInfo)]| { let mut record = record_with_one_file("unused"); diff --git a/crates/socket-patch-core/tests/api_retry_e2e.rs b/crates/socket-patch-core/tests/api_retry_e2e.rs index 97fd09253f..994977e55b 100644 --- a/crates/socket-patch-core/tests/api_retry_e2e.rs +++ b/crates/socket-patch-core/tests/api_retry_e2e.rs @@ -21,6 +21,10 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; const ORG: &str = "org"; const SEED: u64 = 0x5eed_1234; +/// The query every patch request carries: what the client reads in a patch +/// record beyond its file hashes. +const CAPABILITIES_QUERY: &str = "?capabilities=file-modes"; + /// A recording virtual clock: every retry wait lands in the returned log. fn virtual_clock(now_unix_secs: u64) -> (RetryHooks, Arc>>) { let log = Arc::new(Mutex::new(Vec::new())); @@ -180,7 +184,8 @@ async fn a_429_then_200_matches_a_clean_run() { assert_eq!(rendered(&got), rendered(&want)); assert_eq!(requests_to(&throttled, &route).await, 2); - let label = format!("GET {}{route}", throttled.uri()); + // The jitter is keyed by the request as sent, its query included. + let label = format!("GET {}{route}{CAPABILITIES_QUERY}", throttled.uri()); let expected = ApiRetryPolicy::default() .delay(1, None, jitter_sample(SEED, &label, 1)) .expect("no Retry-After"); @@ -227,7 +232,7 @@ async fn retry_after_is_honored_and_floored() { .await .unwrap_or_else(|e| panic!("Retry-After {header:?}: {e}")); let want = want.unwrap_or_else(|| { - let label = format!("GET {}{route}", server.uri()); + let label = format!("GET {}{route}{CAPABILITIES_QUERY}", server.uri()); let floor = ApiRetryPolicy::default() .delay(1, None, jitter_sample(SEED, &label, 1)) .expect("backoff"); diff --git a/crates/socket-patch-core/tests/blob_fetcher_edges_e2e.rs b/crates/socket-patch-core/tests/blob_fetcher_edges_e2e.rs index 83fb0ce385..c82e62a3a5 100644 --- a/crates/socket-patch-core/tests/blob_fetcher_edges_e2e.rs +++ b/crates/socket-patch-core/tests/blob_fetcher_edges_e2e.rs @@ -40,6 +40,7 @@ fn manifest_with_after_hashes(after: &[&str]) -> PatchManifest { PatchFileInfo { before_hash: format!("{:0>64}", format!("be{i}")), after_hash: (*h).to_string(), + mode: None, }, ); } diff --git a/crates/socket-patch-core/tests/crawler_gradle_e2e.rs b/crates/socket-patch-core/tests/crawler_gradle_e2e.rs index 61f85695d8..c91a65328a 100644 --- a/crates/socket-patch-core/tests/crawler_gradle_e2e.rs +++ b/crates/socket-patch-core/tests/crawler_gradle_e2e.rs @@ -258,6 +258,7 @@ fn info(before: &[u8]) -> PatchFileInfo { PatchFileInfo { before_hash: sha1_hex(before), after_hash: "after".into(), + mode: None, } } diff --git a/crates/socket-patch-core/tests/crawler_npm_e2e.rs b/crates/socket-patch-core/tests/crawler_npm_e2e.rs index 3c8438c9c3..b5b6951b6e 100644 --- a/crates/socket-patch-core/tests/crawler_npm_e2e.rs +++ b/crates/socket-patch-core/tests/crawler_npm_e2e.rs @@ -2652,6 +2652,7 @@ async fn apply_and_rollback_reach_every_pnpm_peer_variant_copy() { PatchFileInfo { before_hash: before_hash.clone(), after_hash: after_hash.clone(), + mode: None, }, ); @@ -2779,6 +2780,7 @@ async fn apply_heals_unpatched_pnpm_twin_when_primary_already_patched() { PatchFileInfo { before_hash, after_hash, + mode: None, }, ); let sources = PatchSources { @@ -3731,6 +3733,7 @@ async fn index_js_patch(root: &Path) -> IndexJsPatch { PatchFileInfo { before_hash, after_hash, + mode: None, }, )]); IndexJsPatch { files, blobs } diff --git a/crates/socket-patch-core/tests/rollback_new_file_e2e.rs b/crates/socket-patch-core/tests/rollback_new_file_e2e.rs index 3b87b83004..2ba495c51e 100644 --- a/crates/socket-patch-core/tests/rollback_new_file_e2e.rs +++ b/crates/socket-patch-core/tests/rollback_new_file_e2e.rs @@ -36,6 +36,7 @@ async fn verify_new_file_rollback_ready_when_after_hash_matches() { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: after.clone(), + mode: None, }; let result = verify_file_rollback(pkg, "package/new_file.txt", &file_info, &blobs).await; assert_eq!(result.status, VerifyRollbackStatus::Ready); @@ -67,6 +68,7 @@ async fn verify_new_file_rollback_already_original_when_missing() { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: git_sha256(b"never written"), + mode: None, }; let result = verify_file_rollback(pkg, "package/never_existed.txt", &file_info, &blobs).await; assert_eq!(result.status, VerifyRollbackStatus::AlreadyOriginal); @@ -102,6 +104,7 @@ async fn verify_new_file_rollback_hash_mismatch_when_user_modified() { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: after.clone(), + mode: None, }; let result = verify_file_rollback(pkg, "package/user_modified.txt", &file_info, &blobs).await; assert_eq!(result.status, VerifyRollbackStatus::HashMismatch); @@ -136,6 +139,7 @@ async fn verify_existing_file_rollback_not_found_when_missing() { let file_info = PatchFileInfo { before_hash: git_sha256(b"original"), after_hash: git_sha256(b"patched"), + mode: None, }; let result = verify_file_rollback(pkg, "package/does_not_exist.txt", &file_info, &blobs).await; // Non-empty before_hash → pre-existing-file branch. A missing file here is @@ -171,6 +175,7 @@ async fn verify_existing_file_rollback_missing_blob() { // before-blob, NOT from an after-hash mismatch. A regression that // checked after_hash before the blob would (wrongly) return Ready here. after_hash: current_hash.clone(), + mode: None, }; let result = verify_file_rollback(pkg, "package/patched.txt", &file_info, &blobs).await; assert_eq!(result.status, VerifyRollbackStatus::MissingBlob); @@ -206,6 +211,7 @@ async fn verify_new_file_rollback_unhashable_entry_fails_closed() { let file_info = PatchFileInfo { before_hash: String::new(), after_hash: git_sha256(b"content the patch added"), + mode: None, }; let result = verify_file_rollback(pkg, "package/added.txt", &file_info, &blobs).await; // Same convention as the pre-existing-file branch and this branch's own @@ -239,6 +245,7 @@ async fn verify_new_file_rollback_unhashable_entry_empty_after_hash_not_ready() let file_info = PatchFileInfo { before_hash: String::new(), after_hash: String::new(), + mode: None, }; let result = verify_file_rollback(pkg, "package/added.txt", &file_info, &blobs).await; assert_ne!( diff --git a/crates/socket-patch-core/tests/vlt_locks.rs b/crates/socket-patch-core/tests/vlt_locks.rs index 2a38e50819..dc752081df 100644 --- a/crates/socket-patch-core/tests/vlt_locks.rs +++ b/crates/socket-patch-core/tests/vlt_locks.rs @@ -484,6 +484,7 @@ fn patch_record(uuid: &str) -> PatchRecord { PatchFileInfo { before_hash: compute_git_sha256_from_bytes(ORIGINAL_JS), after_hash: compute_git_sha256_from_bytes(PATCHED_JS), + mode: None, }, ); PatchRecord { diff --git a/crates/socket-patch-node/npm/index.d.ts b/crates/socket-patch-node/npm/index.d.ts index a12cf2db0b..f3d9e865d3 100644 --- a/crates/socket-patch-node/npm/index.d.ts +++ b/crates/socket-patch-node/npm/index.d.ts @@ -29,7 +29,7 @@ export interface BatchSearchResponse { packages: { purl: string; patches: BatchP export interface PatchSearchResult { uuid: string; purl: string; publishedAt: string; description: string; license: string; tier: string; vulnerabilities: Record } export interface SearchResponse { patches: PatchSearchResult[]; canAccessPaidPatches: boolean } export interface PackageVendorResult { status: string; url: string | null; purl: string | null; artifacts: unknown[] | null; registryOverride: unknown | null; npmRegistryUrl?: string | null } // exactly what the v0 API serializes (npmRegistryUrl: npm only, the patch's one-package registry address; omit or null when not served) -export interface PatchResponse { uuid: string; purl: string; publishedAt: string; files: Record; vulnerabilities: Record; description: string; license: string; tier: string } +export interface PatchResponse { uuid: string; purl: string; publishedAt: string; files: Record; vulnerabilities: Record; description: string; license: string; tier: string } export interface PatchProvider { searchPatchesBatch(request: { components: { purl: string }[] }): Promise> diff --git a/npm/socket-patch/src/schema/manifest-schema.test.ts b/npm/socket-patch/src/schema/manifest-schema.test.ts index 12ee440622..dc394aa5a6 100644 --- a/npm/socket-patch/src/schema/manifest-schema.test.ts +++ b/npm/socket-patch/src/schema/manifest-schema.test.ts @@ -146,6 +146,37 @@ describe('PatchManifestSchema', () => { assert.ok(!result.success, 'setup.exclude must be a list') }) + it('should keep a file mode as written, in any spelling', () => { + const record = (mode: unknown) => ({ + uuid: '550e8400-e29b-41d4-a716-446655440000', + exportedAt: '2024-01-01T00:00:00Z', + files: { + // Content unchanged: the permissions are the fix. + 'lib/a.rb': { beforeHash: 'abc123', afterHash: 'abc123', mode }, + }, + vulnerabilities: {}, + description: 'Fix world-writable files', + license: 'MIT', + tier: 'free', + }) + const result = PatchRecordSchema.safeParse(record('0644')) + assert.ok(result.success, 'A file entry with a mode should parse') + assert.equal(result.data.files['lib/a.rb']?.mode, '0644') + // A mode the CLI cannot read fails only its own patch there, never the + // manifest, so it must not fail the record here either. + for (const mode of ['644', '0o644', '0788', '00644', 'rw-r--r--', 420]) { + const other = PatchRecordSchema.safeParse(record(mode)) + assert.ok(other.success, `mode ${mode} must not fail the record`) + assert.equal(other.data.files['lib/a.rb']?.mode, mode) + } + const plain = PatchRecordSchema.safeParse({ + ...record('0644'), + files: { 'lib/a.rb': { beforeHash: 'abc123', afterHash: 'def456' } }, + }) + assert.ok(plain.success) + assert.ok(!('mode' in (plain.data.files['lib/a.rb'] ?? {}))) + }) + it('should reject non-object input', () => { assert.ok(!PatchManifestSchema.safeParse(null).success) assert.ok(!PatchManifestSchema.safeParse('string').success) diff --git a/npm/socket-patch/src/schema/manifest-schema.ts b/npm/socket-patch/src/schema/manifest-schema.ts index 5572fa677f..45972476d3 100644 --- a/npm/socket-patch/src/schema/manifest-schema.ts +++ b/npm/socket-patch/src/schema/manifest-schema.ts @@ -10,6 +10,14 @@ export const PatchRecordSchema = z.object({ z.object({ beforeHash: z.string(), afterHash: z.string(), + // Set when the file's permissions are part of the fix: `0` and three + // octal digits ("0644"). The patched file has no group-write or + // other-write bit the mode lacks, and such an entry may leave the + // content as it is (beforeHash equal to afterHash). Any other value + // is one the CLI cannot read: it is kept as written, and only the + // patch it belongs to is not applied in place. Mirrors `FileMode` in + // crates/socket-patch-core/src/manifest/schema.rs. + mode: z.unknown().optional(), }), ), vulnerabilities: z.record( From 59f3099301d03dd508214e8baa4fa61dc523dab1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 19:39:45 -0500 Subject: [PATCH 2/7] Count a file under an unreadable mode as a content match for a wheel's record The wheel matcher added on main tells a record of another artifact from the installed copy's by content. A file whose entry has a mode this release cannot read holds content the entry describes, so it does not tell the two apart; applying the record reports the mode. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/types.rs | 5 +++-- crates/socket-patch-core/src/patch/pypi_wheel.rs | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index ab9ed52470..bd74fdca5b 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -183,8 +183,9 @@ pub struct PatchFileResponse { /// The file's permissions are part of the fix (see [`FileMode`]). Sent /// only to a client that asked for it /// ([`CAPABILITIES`](crate::api::client::CAPABILITIES)). A spelling - /// this release cannot read fails the whole view: the entry could not - /// be checked, so the patch is not one to record. + /// this release cannot read still parses and is recorded as sent, so + /// it fails only its own patch, when that is applied in place + /// ([`FileMode::is_readable`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub mode: Option, } diff --git a/crates/socket-patch-core/src/patch/pypi_wheel.rs b/crates/socket-patch-core/src/patch/pypi_wheel.rs index f6c217ac1c..8f64050490 100644 --- a/crates/socket-patch-core/src/patch/pypi_wheel.rs +++ b/crates/socket-patch-core/src/patch/pypi_wheel.rs @@ -211,9 +211,11 @@ pub async fn anothers_record<'f>( // A file the record adds that is there with other content: the // verifier calls it writable, and the engine a mismatch. mark_new_file_collision(&mut verify, info); + // `UnreadableMode` is a file whose content matches: it does not + // tell this record from the installed wheel's. if !matches!( verify.status, - VerifyStatus::Ready | VerifyStatus::AlreadyPatched + VerifyStatus::Ready | VerifyStatus::AlreadyPatched | VerifyStatus::UnreadableMode ) { return Some((name, verify.status)); } From fa2403ec038049d61418c2bbc3c601755c90ee02 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 19:44:39 -0500 Subject: [PATCH 3/7] Say how an unreadable file mode is reported, and what a hosted copy does under one Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 1e09658f08..2fcc3b7215 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -188,11 +188,14 @@ every entry of a patch that fixes content only, are handled exactly as before. cannot read. It fails only the patch it belongs to. The manifest (or the API response) still loads, every other patch works as before, and the value is written back exactly as it was read. A file with such an entry cannot be - checked, so its patch is never reported as applied: `apply` fails it with - `errorCode: unreadable_file_mode` before writing any of its files, under - `--force` as well, and `apply --check` and `vex` report the same code. - `rollback`, `remove`, and hosted and vendored use of the patch do not read - the `mode` and work as for any other patch. + checked, so its patch is never reported as applied: `apply` fails it + (`errorCode: apply_failed`, `cause: unreadable_file_mode`) before writing + any of its files, under `--force` as well, and `apply --check` and `vex` + report `unreadable_file_mode` for it. `rollback` and `remove` do not read + the `mode` and work as for any other patch, and so does vendoring it (a + committed artifact is judged by its content). A hosted patch is pinned and + installed as usual, but its installed copy cannot be confirmed, so `vex` + does not attest it. - A release that predates `mode` ignores it and reads an entry with unchanged content as already patched. The patch service therefore sends such entries only to a client that names the `file-modes` capability (see From edfb0ec6d3882d16a56fcf4a90f09140dda07119 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 20:12:46 -0500 Subject: [PATCH 4/7] Read a file mode for in-place copies only, and refuse an unreadable one before any policy Review fixes: - A record with a file mode this release cannot read is refused before any file is verified, in the file engine, the jar swap and the gem apply. A tolerant mismatch policy could otherwise write a file that holds neither side of its entry and report the patch as applied. - Hosted and vendored copies are judged by their content alone again, as on main: a vendored artifact and its installed copies, hosted installs, the stale-install checks, the unwinding of a hosted gem and a compiled conda build. Their bits follow the installer's umask or a git checkout, so reading the mode there reported copies as stale that no reinstall changes. `vex` and `apply --check` read the mode for a copy patched in place. - An entry that fixes a file's permissions alone is no native build input of a gem. - Inside a grouped run a change that must clear bits is refused instead of renaming the file while it is being staged. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 32 ++- crates/socket-patch-cli/src/commands/apply.rs | 10 +- .../src/commands/gem_refresh.rs | 4 +- .../socket-patch-cli/src/commands/vendor.rs | 4 +- .../socket-patch-core/src/manifest/schema.rs | 9 + crates/socket-patch-core/src/patch/apply.rs | 63 +++++- .../src/patch/apply_file_mode_tests.rs | 122 +++++++++- crates/socket-patch-core/src/patch/gem_ext.rs | 53 ++++- crates/socket-patch-core/src/patch/jvm_jar.rs | 11 + crates/socket-patch-core/src/vendor/pypi.rs | 6 +- crates/socket-patch-core/src/vex/verify.rs | 214 +++++++++++------- 11 files changed, 406 insertions(+), 122 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 2fcc3b7215..0ff890cf73 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -173,13 +173,23 @@ every entry of a patch that fixes content only, are handled exactly as before. excess bits, through the same stage and rename as a content change: a file that is hard-linked into a store keeps its other links untouched. A file that already holds the patched bytes is replaced with the bytes it holds; it - is reported in `files` with `appliedVia: "permissions"`, and needs no blob. -- Every command that asks whether an installed copy is patched uses the same - rule (`apply --check`, `vex`, the hosted stale-install check): a file with - the patched bytes and an excess write bit is not applied yet. A committed - vendored artifact is judged by its content alone, as before: this tool - wrote its files with the modes the patched archive gives them, and the bits - git checks out afterwards follow the umask. + is reported in `files` with `appliedVia: "permissions"`, and that write + reads no blob. (The record's blobs are still expected like any other + record's: an `--offline` run without them stops before it applies.) +- The mode is read only for a copy that is patched where it is installed + (agent mode). `apply --check` and `vex` judge such a copy by the same rule + as `apply`: a file with the patched bytes and an excess write bit is not + applied yet. An entry that fixes a file's permissions alone is no build + input of a native gem, so it never starts a rebuild. +- Hosted and vendored copies are judged by their content alone, exactly as + before, whatever `mode` their entries have: a committed vendored artifact, + its installed copies, a hosted install and the stale-install checks. Their + files come from the patched archive, which gives every file `0644` or + `0755`, and the bits an installer or a git checkout leaves on them follow + the umask. One consequence: an install made from the upstream release + before a permissions-only patch was pinned holds the patched content, so + the hosted stale-install check does not see it. Reinstall it (for a gem, + `bundle pristine `). - `rollback` and `remove` restore content only. They never give back a write bit a patch cleared, so a rolled-back file keeps the tightened mode, and an entry whose content the patch did not change has nothing to restore. @@ -191,11 +201,9 @@ every entry of a patch that fixes content only, are handled exactly as before. checked, so its patch is never reported as applied: `apply` fails it (`errorCode: apply_failed`, `cause: unreadable_file_mode`) before writing any of its files, under `--force` as well, and `apply --check` and `vex` - report `unreadable_file_mode` for it. `rollback` and `remove` do not read - the `mode` and work as for any other patch, and so does vendoring it (a - committed artifact is judged by its content). A hosted patch is pinned and - installed as usual, but its installed copy cannot be confirmed, so `vex` - does not attest it. + report `unreadable_file_mode` for it. `rollback`, `remove`, and hosted and + vendored use of the patch do not read the `mode` and work as for any other + patch. - A release that predates `mode` ignores it and reads an entry with unchanged content as already patched. The patch service therefore sends such entries only to a client that names the `file-modes` capability (see diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 17d3573d45..f0cbd30c02 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -8,8 +8,8 @@ use socket_patch_core::crawlers::{ use socket_patch_core::manifest::operations::{manifest_exists, read_manifest}; use socket_patch_core::manifest::schema::{PatchFileInfo, PatchManifest, PatchRecord}; use socket_patch_core::patch::apply::{ - apply_package_patch, gem_copy_holds_earlier_patch, verify_file_patch, ApplyFailureCause, - ApplyResult, MismatchPolicy, PatchSources, VerifyStatus, + apply_package_patch, gem_copy_holds_earlier_patch, verify_file_content, verify_file_patch, + ApplyFailureCause, ApplyResult, MismatchPolicy, PatchSources, VerifyStatus, }; use socket_patch_core::patch::apply_lock::LockGuard; use socket_patch_core::patch::gem_ext; @@ -961,8 +961,12 @@ async fn settle_compiled_conda_copies( for key in &keys { let files = &tree.patches[key].files; let mut holds_patch = !files.is_empty(); + // The copy's content: nothing is written to a compiled + // build, so an entry's `mode` is not read. for (file_name, file_info) in files { - if verify_file_patch(&path, file_name, file_info).await.status + if verify_file_content(&path, file_name, file_info) + .await + .status != VerifyStatus::AlreadyPatched { holds_patch = false; diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index af89f94efe..3bb5c31df1 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1544,13 +1544,13 @@ async fn upstream_installs( /// installed gem `dir`: it hashes to its `beforeHash`, or the patch adds /// it and it is not there. A record that lists no file proves nothing. async fn is_unpatched(dir: &Path, record: &PatchRecord) -> bool { - use socket_patch_core::patch::apply::{verify_file_patch, VerifyStatus}; + use socket_patch_core::patch::apply::{verify_file_content, VerifyStatus}; if record.files.is_empty() { return false; } for (name, info) in &record.files { - let verified = verify_file_patch(dir, name, info).await; + let verified = verify_file_content(dir, name, info).await; // `Ready` also covers a file the patch adds that is there with // other content (apply overwrites it): only its absence proves // the copy never got it. diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 3ae842786b..028c9dcf7f 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -27,7 +27,7 @@ use socket_patch_core::constants::SOCKET_DIR; use socket_patch_core::crawlers::{CrawlerOptions, Ecosystem}; use socket_patch_core::manifest::operations::{manifest_exists, read_manifest, write_manifest}; use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; -use socket_patch_core::patch::apply::{verify_file_patch, PatchSources}; +use socket_patch_core::patch::apply::{verify_file_content, PatchSources}; use socket_patch_core::patch::redirect::upstream::HostedPin; use socket_patch_core::telemetry::{ track_patch_vendor_failed, track_patch_vendored, TelemetryAuth, MODE_VENDORED, @@ -3781,7 +3781,7 @@ impl<'a> CandidateGates<'a> { } if let Some((file, info)) = representative_file(&record.files) { if !variant_matches_installed(Some( - &verify_file_patch(dir, file, info).await.status, + &verify_file_content(dir, file, info).await.status, )) { let sole_candidate = group.candidates.len() == 1; let hosted_pinned = (self.hosted_pinned)(candidate); diff --git a/crates/socket-patch-core/src/manifest/schema.rs b/crates/socket-patch-core/src/manifest/schema.rs index 874ef3e398..627b90d809 100644 --- a/crates/socket-patch-core/src/manifest/schema.rs +++ b/crates/socket-patch-core/src/manifest/schema.rs @@ -133,6 +133,15 @@ pub struct PatchFileInfo { pub mode: Option, } +impl PatchFileInfo { + /// Whether the entry fixes the file's permissions and nothing else: it + /// has a `mode` and leaves the content as it is. Such an entry changes + /// no byte, so it is no build input and no stale-bytecode source. + pub fn is_permissions_only(&self) -> bool { + self.mode.is_some() && !self.after_hash.is_empty() && self.before_hash == self.after_hash + } +} + /// The manifest's hash case policy: a loaded hash is lowercase hex. fn deserialize_hash<'de, D>(deserializer: D) -> Result where diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index bc2afc29b0..9249802356 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -351,6 +351,21 @@ pub(crate) fn mode_excess(meta: &std::fs::Metadata, mode: &FileMode) -> u32 { /// cannot read ([`VerifyStatus::UnreadableMode`]). pub const UNREADABLE_FILE_MODE: &str = "unreadable_file_mode"; +/// The entry of `files` whose `mode` this release cannot read +/// ([`FileMode::is_readable`]), the first by file name when there are +/// several. A record with one is never written in place. +pub(crate) fn unreadable_mode_entry( + files: &HashMap, +) -> Option<(&String, &FileMode)> { + files + .iter() + .filter_map(|(name, info)| { + let mode = info.mode.as_ref().filter(|mode| !mode.is_readable())?; + Some((name, mode)) + }) + .min_by(|(a, _), (b, _)| a.cmp(b)) +} + /// What [`verify_file_patch`] says of a file whose entry has a `mode` this /// release cannot read. pub(crate) fn unreadable_mode_message(mode: &FileMode) -> String { @@ -1143,19 +1158,23 @@ impl PackageWrite { .zip(mode) .and_then(|(meta, mode)| without_excess_write_bits(meta, mode)); if let Some(perms) = &tightened { - attrs.mode = StageMode::Of(perms.clone()); // A captured write (below) is given the mode its file has when // the group commit replaces it, and one that changes no byte is - // never written: the bits are cleared here, under the bytes the - // file holds now. + // never written, so a group commit cannot clear the bits; and + // nothing is written for real while one is open. No in-place + // apply runs inside one: refuse, rather than report bits + // cleared that were not. if crate::utils::group_commit::is_capturing(&dest) { - let held = std::fs::read(&dest)?; - let staged = stage_blocking(&dest, &held, &attrs, StageSync::Now)?; - if let Err(e) = staged.commit() { - staged.discard(); - return Err(e); - } + return Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + format!( + "{}: its permission bits cannot be cleared while the run's writes \ + are grouped", + dest.display() + ), + )); } + attrs.mode = StageMode::Of(perms.clone()); } // Inside an open group commit a commit point under its root is // captured instead of written (see `utils::group_commit`). @@ -1876,8 +1895,10 @@ async fn every_file_already_patched( if files.is_empty() { return false; } + // A question about the copy's content: nothing is written to such a + // build to clear a write bit, so an entry's `mode` is not read. for (file_name, file_info) in files { - if verify_file_patch(pkg_path, file_name, file_info) + if verify_file_content(pkg_path, file_name, file_info) .await .status != VerifyStatus::AlreadyPatched @@ -1925,6 +1946,28 @@ async fn apply_package_patch_at( return result; } + // A record with a file mode this release cannot read is not one it can + // apply: the file could not be told patched afterwards. Refused before + // anything is verified or written, whatever the files hold, so no + // mismatch policy (`--force` included) writes any of its files. + if let Some((file_name, mode)) = unreadable_mode_entry(files) { + let message = unreadable_mode_message(mode); + result.fail( + ApplyFailureCause::Coded(UNREADABLE_FILE_MODE), + format!("Cannot apply patch: {file_name} - {message}"), + ); + result.files_verified.push(VerifyResult { + file: file_name.clone(), + status: VerifyStatus::UnreadableMode, + message: Some(message), + current_hash: None, + expected_hash: None, + target_hash: None, + permissions_only: false, + }); + return result; + } + // A copy conda built is patched only as the PyPI release the patch was // made from (see `conda_copy`): never a compiled build, and never by // overwriting a file that is not the release's. Refused before anything diff --git a/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs index 3428dc60a8..c2ba6d2f0b 100644 --- a/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs +++ b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs @@ -525,10 +525,12 @@ async fn a_content_only_check_never_reads_the_mode_or_the_bits() { } /// Inside a group commit a captured write is given its file's mode when -/// the commit replaces it, and a write that changes no byte is dropped: -/// the bits are cleared when the change is staged. +/// the commit replaces it, and a write that changes no byte is dropped, so +/// the bits cannot be cleared there, and nothing is written for real +/// while one is open. Staging such a change is refused and the file is +/// left as it was; a change with no bit to clear is captured as before. #[test] -fn a_captured_write_clears_the_bits_when_it_is_staged() { +fn a_captured_write_that_must_clear_bits_is_refused() { let root = tempfile::tempdir().unwrap(); let root_path = root.path().canonicalize().unwrap(); let pkg = root_path.join("pkg"); @@ -536,11 +538,12 @@ fn a_captured_write_clears_the_bits_when_it_is_staged() { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, CODE).unwrap(); chmod(&path, 0o666); + let inode = std::fs::metadata(&path).unwrap().ino(); let commit = crate::utils::group_commit::GroupCommit::begin(&root_path); assert!(crate::utils::group_commit::is_capturing(&path)); let mut write = PackageWrite::new(); - write + let refused = write .stage_write( &pkg, FILE, @@ -548,9 +551,114 @@ fn a_captured_write_clears_the_bits_when_it_is_staged() { &hash(CODE), FileMode::parse("0644").as_ref(), ) - .unwrap(); - assert_eq!(mode_of(&path), 0o644); - assert_eq!(std::fs::read(&path).unwrap(), CODE); + .unwrap_err(); + assert_eq!(refused.kind(), std::io::ErrorKind::Unsupported); + assert_eq!(mode_of(&path), 0o666); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), inode); + + // No bit to clear (the mode grants them, or there is no mode): the + // write is captured, and the file on disk is untouched. + for mode in [FileMode::parse("0666"), None] { + write + .stage_write(&pkg, FILE, b"patched\n", &hash(b"patched\n"), mode.as_ref()) + .unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), CODE); + assert_eq!(mode_of(&path), 0o666); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), inode); + } drop(write); drop(commit); } + +/// A file that holds neither side of its entry is written under a +/// tolerant policy, and a missing one is skipped under `--force`. Neither +/// happens for a record with a mode this release cannot read: it is +/// refused before any file is verified, so nothing is written and nothing +/// is reported as applied. +#[tokio::test] +async fn no_policy_writes_a_file_of_a_record_with_a_mode_that_cannot_be_read() { + const OTHER: &str = "lib/b.rb"; + let patched: &[u8] = b"patched\n"; + let edited: &[u8] = b"edited by hand\n"; + for policy in [ + MismatchPolicy::Strict, + MismatchPolicy::SocketContent, + MismatchPolicy::Warn, + MismatchPolicy::Force, + ] { + // `lib/a.rb` matches neither hash; `lib/b.rb` is missing. + let (pkg, blobs) = package(edited, 0o666); + let path = pkg.path().join(FILE); + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + let files = HashMap::from([ + ( + FILE.to_string(), + unreadable_entry(CODE, patched, r#""644""#), + ), + (OTHER.to_string(), entry(CODE, patched, Some("0644"))), + ]); + let result = apply_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + &PatchSources::blobs_only(blobs.path()), + false, + policy, + ) + .await; + assert!(!result.success, "{policy:?}"); + assert_eq!( + result.failure_cause(), + Some(ApplyFailureCause::Coded(UNREADABLE_FILE_MODE)), + "{policy:?}" + ); + assert!(result.files_patched.is_empty(), "{policy:?}"); + assert_eq!(result.files_verified.len(), 1, "{policy:?}"); + assert_eq!(result.files_verified[0].file, FILE); + assert_eq!( + result.files_verified[0].status, + VerifyStatus::UnreadableMode + ); + assert_eq!(std::fs::read(&path).unwrap(), edited, "{policy:?}"); + assert_eq!(mode_of(&path), 0o666, "{policy:?}"); + assert!(!pkg.path().join(OTHER).exists(), "{policy:?}"); + } + + // The same record with a mode this release reads is written under the + // tolerant policies, as any record is. + let (pkg, blobs) = package(edited, 0o666); + std::fs::write(blobs.path().join(hash(patched)), patched).unwrap(); + let files = one(entry(CODE, patched, Some("0644"))); + let result = apply_package_patch( + ReadScope::Workspace, + PURL, + pkg.path(), + &files, + &PatchSources::blobs_only(blobs.path()), + false, + MismatchPolicy::Warn, + ) + .await; + assert!(result.success, "{:?}", result.error); + assert_eq!(std::fs::read(pkg.path().join(FILE)).unwrap(), patched); + assert_eq!(mode_of(&pkg.path().join(FILE)), 0o644); +} + +/// An entry that fixes a file's permissions alone is told from every +/// other entry by its mode and its equal hashes. +#[test] +fn a_permissions_only_entry_has_a_mode_and_unchanged_content() { + assert!(entry(CODE, CODE, Some("0644")).is_permissions_only()); + assert!(unreadable_entry(CODE, CODE, r#""644""#).is_permissions_only()); + // Unchanged content without a mode is the record shape that existed + // before modes: it is not one. + assert!(!entry(CODE, CODE, None).is_permissions_only()); + assert!(!entry(CODE, b"patched\n", Some("0644")).is_permissions_only()); + let added = PatchFileInfo { + before_hash: String::new(), + after_hash: String::new(), + mode: FileMode::parse("0644"), + }; + assert!(!added.is_permissions_only()); +} diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index a62f197b54..f3f05994cb 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1094,8 +1094,12 @@ fn classify(facts: &SpecFacts, files: &HashMap) -> Native .any(|entry| RAKE_SCRIPTS.contains(&leaf_of(entry)))); let precompiled = facts.platform.clone().filter(|_| !decl.declared); let native = decl.declared || precompiled.is_some(); + // An entry that fixes a file's permissions alone changes no byte the + // build reads: it is applied like any plain file. let mut inputs: Vec = files - .keys() + .iter() + .filter(|(_, info)| !info.is_permissions_only()) + .map(|(key, _)| key) .filter(|key| { let path = normalize_file_path(key); if !native { @@ -5856,6 +5860,20 @@ pub async fn apply_gem_package_patch( policy: MismatchPolicy, env: &RubyEnv, ) -> GemApplied { + // A record with a file mode this release cannot read is refused by the + // engine before anything is written: no build is started for it. + if crate::patch::apply::unreadable_mode_entry(files).is_some() { + return plain_apply( + read_scope, + package_key, + pkg_path, + files, + sources, + dry_run, + policy, + ) + .await; + } let gem = InstalledGem::at(pkg_path).await; // The JVM build of a gem has no extension to rebuild: the record is // applied as far as it concerns that build. @@ -6807,6 +6825,39 @@ mod tests { assert!(scope.builds_extensions); } + /// An entry that fixes a file's permissions alone changes no byte the + /// build reads, so it is no build input, wherever the file is. The + /// same file with a content change, or with unchanged content and no + /// mode (the record shape that existed before modes), still is one. + #[test] + fn classify_leaves_out_permissions_only_entries() { + use crate::manifest::schema::FileMode; + let decl = built_gem(&["ext/foo/extconf.rb"]); + let entry = |before: &str, after: &str, mode: Option<&str>| PatchFileInfo { + before_hash: before.repeat(64), + after_hash: after.repeat(64), + mode: mode.map(|m| FileMode::parse(m).unwrap()), + }; + let all: HashMap = HashMap::from([ + ("ext/foo/foo.c".to_string(), entry("a", "a", Some("0644"))), + ( + "ext/foo/extconf.rb".to_string(), + entry("a", "a", Some("0755")), + ), + ("lib/foo.rb".to_string(), entry("a", "a", Some("0644"))), + ]); + let scope = classify(&decl, &all); + assert!(scope.inputs.is_empty(), "{:?}", scope.inputs); + + let mut changed = all.clone(); + changed.insert("ext/foo/foo.c".to_string(), entry("a", "b", Some("0644"))); + assert_eq!(classify(&decl, &changed).inputs, vec!["ext/foo/foo.c"]); + + let mut legacy = all; + legacy.insert("ext/foo/foo.c".to_string(), entry("a", "a", None)); + assert_eq!(classify(&decl, &legacy).inputs, vec!["ext/foo/foo.c"]); + } + #[test] fn classify_without_extensions_keeps_c_but_drops_grammars() { let scope = classify( diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index d21ce471ad..68f3264480 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -507,6 +507,17 @@ pub async fn apply_jar_swap( copies: &[PathBuf], service: Option<&VendorServiceConfig>, ) -> Result, SwapRefusal> { + // As for any record: one with a file mode this release cannot read is + // not applied in place. + if let Some((member, mode)) = crate::patch::apply::unreadable_mode_entry(swap.files) { + return Err(SwapRefusal::new( + crate::patch::apply::UNREADABLE_FILE_MODE, + format!( + "Cannot apply patch: {member} - {}", + crate::patch::apply::unreadable_mode_message(mode) + ), + )); + } let mut refusals = HashMap::new(); let results = swap_copies(swap, copies, service, &mut refusals).await?; Ok(results diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index 922089cea3..8418be8974 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -814,7 +814,7 @@ pub async fn vendor_pypi<'a>( /// another terminal — is not seen by the packages judged after the /// first ask for that site, where re-listing per package would have seen /// it. Only the `(canonicalized name, version)` SET is frozen: which files -/// are stale is still read live, per package, through `verify_file_patch`. +/// are stale is still read live, per package, through `verify_file_content`. #[derive(Default)] pub struct InstalledSiteListings(tokio::sync::Mutex); @@ -993,7 +993,7 @@ async fn stale_install_sites( listings: &InstalledSiteListings, ) -> Vec { use crate::crawlers::python_crawler::PythonCrawler; - use crate::patch::apply::{verify_file_patch, VerifyStatus}; + use crate::patch::apply::{verify_file_content, VerifyStatus}; if record.files.is_empty() { return Vec::new(); } @@ -1023,7 +1023,7 @@ async fn stale_install_sites( continue; } for (file, info) in &record.files { - let result = verify_file_patch(site, file, info).await; + let result = verify_file_content(site, file, info).await; if matches!( result.status, VerifyStatus::Ready | VerifyStatus::HashMismatch diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 52e48de95e..1c6ed9f487 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -20,7 +20,7 @@ use std::path::{Path, PathBuf}; use crate::crawlers::Ecosystem; use crate::manifest::schema::{PatchManifest, PatchRecord}; -use crate::patch::apply::{verify_file_patch, VerifyStatus}; +use crate::patch::apply::{verify_file_content, verify_file_patch, VerifyStatus}; use crate::utils::npm_range::npm_range_admits; use crate::vendor::state::{lookup_entry, VendorEntry}; use crate::vendor::verify::{ @@ -231,7 +231,8 @@ pub async fn applied_patches_with_copies( if Ecosystem::from_purl(purl) == Some(Ecosystem::Maven) { let mut first_failure = None; for copy in paths { - if let Err(reason) = verify_patch_record_for(purl, copy, record).await { + if let Err(reason) = verify_record_for(purl, copy, record, Judge::InPlace).await + { out.unpatched_copies.push((purl.clone(), copy.clone())); first_failure.get_or_insert(reason); } @@ -247,7 +248,7 @@ pub async fn applied_patches_with_copies( Err(reason) => Err(reason), } } else { - verify_every_copy(paths, record).await + verify_every_copy(paths, record, Judge::InPlace).await } } else { Err("package_not_found".to_string()) @@ -375,14 +376,46 @@ pub async fn applied_patches_with_copies( /// A Gradle `files-2.1` version dir is expanded through /// [`installed_copies`](crate::crawlers::gradle_cache::installed_copies): /// every hash directory holding a record file must verify. +/// +/// The copy is judged by its content alone ([`Judge::Content`]): this is +/// the verdict for a copy an installer wrote from the patched archive or +/// this tool extracted from it (hosted, vendored). A copy patched where it +/// is installed is judged by [`verify_patch_record_in_place`]. pub async fn verify_patch_record(pkg_path: &Path, record: &PatchRecord) -> Result<(), String> { - verify_patch_files(pkg_path, &record.files).await + verify_patch_files(pkg_path, &record.files, Judge::Content).await +} + +/// [`verify_patch_record`] for a copy patched where it is installed (agent +/// mode): a file whose entry has a `mode` is patched by its permission +/// bits as well ([`Judge::InPlace`]). +pub async fn verify_patch_record_in_place( + pkg_path: &Path, + record: &PatchRecord, +) -> Result<(), String> { + verify_patch_files(pkg_path, &record.files, Judge::InPlace).await +} + +/// What the files of an installed copy are judged by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Judge { + /// Their content alone + /// ([`verify_file_content`](crate::patch::apply::verify_file_content)): + /// a copy an installer wrote from the patched archive, or this tool + /// extracted from it. Its permission bits are the archive's and the + /// installer's umask, so an entry's `mode` is not read. + Content, + /// Their content, and for an entry with a `mode` their permission + /// bits ([`verify_file_patch`]): a copy patched where it is installed, + /// whose bits are still the ones the unpatched release was installed + /// with until `apply` clears them. + InPlace, } /// [`verify_patch_record`] over a record's `files`. async fn verify_patch_files( pkg_path: &Path, files: &HashMap, + judge: Judge, ) -> Result<(), String> { if files.is_empty() { return Err("no_files".to_string()); @@ -391,7 +424,11 @@ async fn verify_patch_files( let mut keys: Vec<&String> = files.keys().collect(); keys.sort(); for file_name in keys { - let result = verify_file_patch(&dir, file_name, &files[file_name]).await; + let info = &files[file_name]; + let result = match judge { + Judge::Content => verify_file_content(&dir, file_name, info).await, + Judge::InPlace => verify_file_patch(&dir, file_name, info).await, + }; status_verdict(result.status)?; } } @@ -417,13 +454,32 @@ pub async fn verify_patch_record_for( purl: &str, pkg_path: &Path, record: &PatchRecord, +) -> Result<(), String> { + verify_record_for(purl, pkg_path, record, Judge::Content).await +} + +/// [`verify_patch_record_for`] under `judge` (a jar's members have no +/// permission bits, so `judge` is for a leaf-keyed record). +async fn verify_record_for( + purl: &str, + pkg_path: &Path, + record: &PatchRecord, + judge: Judge, ) -> Result<(), String> { use crate::patch::jvm_jar::{self, RecordShape}; match jvm_jar::classify(purl, &record.files) { + // As `apply` refuses it: a record with a mode this release cannot + // read is not applied in place, member-keyed or not. + RecordShape::Members { .. } + if judge == Judge::InPlace + && crate::patch::apply::unreadable_mode_entry(&record.files).is_some() => + { + Err(crate::patch::apply::UNREADABLE_FILE_MODE.to_string()) + } RecordShape::Members { jar_leaf } => { verify_member_copies(pkg_path, &jar_leaf, record).await } - RecordShape::Leaf => verify_patch_record(pkg_path, record).await, + RecordShape::Leaf => verify_patch_files(pkg_path, &record.files, judge).await, } } @@ -507,15 +563,12 @@ async fn multi_release_copies( #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct InstalledRecordJudgment { /// [`verify_patch_record`] would return `Ok`: the record has files and - /// every one hashes to its `afterHash`, without a write bit its entry's - /// `mode` does not grant. + /// every one hashes to its `afterHash`. pub patched: bool, - /// At least one record file was actually read and is not the patched - /// file: it hashed to something other than its `afterHash`, or holds - /// the patched bytes under a write bit its entry's `mode` does not - /// grant (`verify_file_patch`'s `Ready` or `HashMismatch` WITH a - /// `current_hash`). Missing, unreadable and unsafe-path files are never - /// evidence. + /// At least one record file was actually read and hashed to something + /// other than its `afterHash` (`verify_file_content`'s `Ready` or + /// `HashMismatch` WITH a `current_hash`). Missing, unreadable and + /// unsafe-path files are never evidence. pub stale_evidence: bool, } @@ -533,13 +586,13 @@ pub async fn judge_installed_record( pkg_path: &Path, record: &PatchRecord, ) -> InstalledRecordJudgment { - let copies: Vec<(PathBuf, Vec)> = + let copies: Vec<(PathBuf, Vec<(String, String)>)> = crate::crawlers::gradle_cache::installed_copies(pkg_path, &record.files) .into_iter() .map(|(dir, files)| { let files = files .into_iter() - .map(|(name, info)| (name, info.after_hash, info.mode)) + .map(|(name, info)| (name, info.after_hash)) .collect(); (dir, files) }) @@ -562,51 +615,25 @@ pub async fn judge_installed_record( .await } -/// A record file as [`judge_installed_files`] reads it: its key, its -/// `afterHash` and its entry's `mode`. -type JudgedFile = (String, String, Option); - -fn judge_installed_files(pkg_path: &Path, files: &[JudgedFile]) -> InstalledRecordJudgment { - use crate::patch::apply::{is_safe_relative_subpath, mode_excess, normalize_file_path}; +fn judge_installed_files(pkg_path: &Path, files: &[(String, String)]) -> InstalledRecordJudgment { + use crate::patch::apply::{is_safe_relative_subpath, normalize_file_path}; use crate::patch::file_hash::compute_file_git_sha256_sync; - // The patched bytes under a write bit the entry's mode does not grant - // are `verify_file_patch`'s `Ready`: the copy is not the patched one. - let excess_bits = |path: &Path, mode: &Option| { - mode.as_ref() - .zip(std::fs::metadata(path).ok()) - .is_some_and(|(mode, meta)| mode_excess(&meta, mode) != 0) - }; let mut all_patched = !files.is_empty(); - for (file_name, after_hash, mode) in files { - // A mode this release cannot read (`verify_file_patch`'s - // `UnreadableMode`): the file cannot be judged, so the copy is not - // the patched one, and nothing about it is evidence. - if mode.as_ref().is_some_and(|mode| !mode.is_readable()) { - all_patched = false; - continue; - } + for (file_name, after_hash) in files { let normalized = normalize_file_path(file_name); // An unsafe key never resolves (verify_file_patch's NotFound). let hashed = is_safe_relative_subpath(normalized) .then(|| compute_file_git_sha256_sync(&pkg_path.join(normalized)).ok()) .flatten(); match hashed { - Some(hash) if &hash == after_hash && !excess_bits(&pkg_path.join(normalized), mode) => { - } - Some(hash) if &hash == after_hash => { - return InstalledRecordJudgment { - patched: false, - stale_evidence: true, - } - } + Some(hash) if &hash == after_hash => {} // npm's LF-shebang form of the patched bin (see `npm_bin`), // which `verify_file_patch` also accepts. Some(_) if crate::patch::npm_bin::source_hash_sync(&pkg_path.join(normalized)) .as_deref() - == Some(after_hash.as_str()) - && !excess_bits(&pkg_path.join(normalized), mode) => {} + == Some(after_hash.as_str()) => {} Some(_) => { return InstalledRecordJudgment { patched: false, @@ -624,9 +651,13 @@ fn judge_installed_files(pkg_path: &Path, files: &[JudgedFile]) -> InstalledReco /// Every copy must pass [`verify_patch_record`]; the first failure's tag /// wins. The caller guarantees `paths` is non-empty. -async fn verify_every_copy(paths: &[PathBuf], record: &PatchRecord) -> Result<(), String> { +async fn verify_every_copy( + paths: &[PathBuf], + record: &PatchRecord, + judge: Judge, +) -> Result<(), String> { for path in paths { - verify_patch_record(path, record).await?; + verify_patch_files(path, &record.files, judge).await?; } Ok(()) } @@ -672,7 +703,7 @@ async fn verify_every_gem_copy( let gem = InstalledGem::at(path).await; let files = gem.record_files(purl, &record.files).await; if !files.is_empty() { - verify_patch_files(path, &files).await?; + verify_patch_files(path, &files, Judge::InPlace).await?; verdict = GemVerdict::Patched; } gem.verify_native_build(purl, &record.files).await?; @@ -741,7 +772,7 @@ async fn verify_hosted_copies( } None => record, }; - verify_every_copy(&copies.paths, record).await?; + verify_every_copy(&copies.paths, record, Judge::Content).await?; if Ecosystem::from_purl(purl) == Some(Ecosystem::Npm) && touches_npm_manifest(record) { for path in &copies.paths { if unresolved_npm_dependency(path).await.is_some() { @@ -2944,10 +2975,11 @@ mod tests { // ── judge_installed_record ≡ verify_patch_record + evidence scan ── /// The CLI stale-install probes' positive-evidence scan as it was - /// (per-file `verify_file_patch`), the oracle for the one-pass judge. + /// (per-file `verify_file_content`: a copy's content, never its + /// entry's `mode`), the oracle for the one-pass judge. async fn stale_positive_evidence_oracle(pkg_path: &Path, record: &PatchRecord) -> bool { for (file_name, info) in &record.files { - let result = verify_file_patch(pkg_path, file_name, info).await; + let result = verify_file_content(pkg_path, file_name, info).await; if matches!( result.status, VerifyStatus::Ready | VerifyStatus::HashMismatch @@ -2992,8 +3024,8 @@ mod tests { } else { upstream.clone() }; - // An entry's mode is part of both verdicts: the patched - // bytes under a write bit it does not grant are stale. + // An entry's mode and the file's bits are part of neither + // verdict: both judge a copy by its content alone. let mode = rng .chance(40) .then(|| crate::manifest::schema::FileMode::parse("0644").unwrap()); @@ -3039,13 +3071,14 @@ mod tests { } /// The patched bytes under a write bit the entry's `mode` does not - /// grant are not the patched file, for the attestation and for the - /// stale-install probes alike: a copy installed from the upstream - /// archive of a release whose fix is its permissions holds exactly - /// those bytes. + /// grant are not the patched file for a copy patched where it is + /// installed: a copy installed from the upstream archive of a release + /// whose fix is its permissions holds exactly those bytes. A copy + /// judged by its content (hosted, vendored) reads neither the mode nor + /// the bits. #[cfg(unix)] #[tokio::test] - async fn patched_bytes_under_excess_write_bits_are_not_applied() { + async fn patched_bytes_under_excess_write_bits_are_not_applied_in_place() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("index.js"); @@ -3059,43 +3092,45 @@ mod tests { // The content is the fix's and the release's alike. entry.before_hash = hash.clone(); entry.mode = crate::manifest::schema::FileMode::parse("0644"); + let patched = InstalledRecordJudgment { + patched: true, + stale_evidence: false, + }; chmod(0o666); assert_eq!( - verify_patch_record(dir.path(), &record).await, + verify_patch_record_in_place(dir.path(), &record).await, Err("not_applied".to_string()) ); - assert_eq!( - judge_installed_record(dir.path(), &record).await, - InstalledRecordJudgment { - patched: false, - stale_evidence: true, - } - ); + assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); + assert_eq!(judge_installed_record(dir.path(), &record).await, patched); chmod(0o644); - assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); assert_eq!( - judge_installed_record(dir.path(), &record).await, - InstalledRecordJudgment { - patched: true, - stale_evidence: false, - } + verify_patch_record_in_place(dir.path(), &record).await, + Ok(()) ); + assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); + assert_eq!(judge_installed_record(dir.path(), &record).await, patched); - // Without a mode the bits are not part of the patch. + // Without a mode the bits are not part of the patch anywhere. chmod(0o666); record.files.get_mut("index.js").unwrap().mode = None; + assert_eq!( + verify_patch_record_in_place(dir.path(), &record).await, + Ok(()) + ); assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); - assert!(judge_installed_record(dir.path(), &record).await.patched); + assert_eq!(judge_installed_record(dir.path(), &record).await, patched); } /// A record with a file mode this release cannot read is never applied - /// and never stale evidence, whatever the file holds: it cannot be - /// judged. Its other records are judged as before. + /// in place, whatever the file's bits are: the file cannot be judged. + /// A copy judged by its content does not read the mode, so it is + /// judged as for any other record, stale content included. #[cfg(unix)] #[tokio::test] - async fn a_record_with_a_mode_that_cannot_be_read_is_never_applied() { + async fn a_record_with_a_mode_that_cannot_be_read_is_never_applied_in_place() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("index.js"); @@ -3103,25 +3138,40 @@ mod tests { let hash = compute_git_sha256_from_bytes(b"patched"); let mut record = record_with_one_file(&hash); let entry = record.files.get_mut("index.js").unwrap(); - entry.before_hash = hash.clone(); entry.mode = Some(serde_json::from_str(r#""u=rw,go=r""#).unwrap()); for mode in [0o666, 0o644, 0o600] { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); assert_eq!( - verify_patch_record(dir.path(), &record).await, + verify_patch_record_in_place(dir.path(), &record).await, Err("unreadable_file_mode".to_string()), "{mode:o}" ); + assert_eq!(verify_patch_record(dir.path(), &record).await, Ok(())); assert_eq!( judge_installed_record(dir.path(), &record).await, InstalledRecordJudgment { - patched: false, + patched: true, stale_evidence: false, }, "{mode:o}" ); } + + // A copy that still holds other content is stale evidence, as for + // a record without a mode. + std::fs::write(&path, b"upstream").unwrap(); + assert_eq!( + verify_patch_record_in_place(dir.path(), &record).await, + Err("hash_mismatch".to_string()) + ); + assert_eq!( + judge_installed_record(dir.path(), &record).await, + InstalledRecordJudgment { + patched: false, + stale_evidence: true, + } + ); } // ── Maven / Gradle copy sets ──────────────────────────────────── From 4be5b2a972387a6772e98e6d9582d1398266dfab Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 20:45:35 -0500 Subject: [PATCH 5/7] Give the reinstall that a warm hosted gem install needs, not bundle pristine The cached archive of such an install is the upstream one, so `bundle pristine` brings the same files back. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0ff890cf73..d974ec5d2a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -188,8 +188,12 @@ every entry of a patch that fixes content only, are handled exactly as before. `0755`, and the bits an installer or a git checkout leaves on them follow the umask. One consequence: an install made from the upstream release before a permissions-only patch was pinned holds the patched content, so - the hosted stale-install check does not see it. Reinstall it (for a gem, - `bundle pristine `). + the hosted stale-install check does not see it and it keeps its modes + until it is installed again from the patched archive. For a gem that + means removing the installed gem's `specifications` entry and its cached + `.gem` and running `bundle install`, as the "Gem stale-install guard" + section describes for any stale copy; `bundle pristine` reinstalls from + the cached upstream archive and does not help. - `rollback` and `remove` restore content only. They never give back a write bit a patch cleared, so a rolled-back file keeps the tightened mode, and an entry whose content the patch did not change has nothing to restore. From 9da45ed74cf35a575e45770ea0cdced89f2f4dc1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 21:25:57 -0500 Subject: [PATCH 6/7] Keep file verification off the stack, and judge every delivered copy by content CI: the coverage build overflowed a 2 MiB test thread in the in-process gem suite. The mode check had added an async layer and two call sites to the verify and apply paths, which sit under the deepest commands. File verification is now main's content check plus a separate mode step, both handed out as boxed futures, and the permissions-only write is one boxed call. The suite's deepest tests need about 1.4 MiB here, against 1.9 MiB on main. Review of the previous fixes: - A record with an unreadable mode is refused as a whole by `vex` and `apply --check` too, and a Maven record is no longer split across Gradle hash dirs when it has one, so no part of it is written. - A package wired to a hosted patch is judged by content wherever its copies are found (Composer and NuGet have no consumed-copy list), and so are a copy conda built and a local Go patch copy, which are also written without the mode. - A gem copy that lacks the file of a permissions-only entry takes the record without it, instead of failing on a missing build input. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 +- crates/socket-patch-cli/src/commands/apply.rs | 6 +- crates/socket-patch-cli/src/commands/vex.rs | 1 + .../socket-patch-core/src/manifest/schema.rs | 6 +- crates/socket-patch-core/src/patch/apply.rs | 240 +++++++++++++----- .../src/patch/apply_file_mode_tests.rs | 25 ++ crates/socket-patch-core/src/patch/gem_ext.rs | 129 ++++++++-- .../src/patch/redirect/golang_local.rs | 5 + crates/socket-patch-core/src/vex/verify.rs | 136 +++++++++- 9 files changed, 452 insertions(+), 104 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d974ec5d2a..d3429aba06 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -180,13 +180,17 @@ every entry of a patch that fixes content only, are handled exactly as before. (agent mode). `apply --check` and `vex` judge such a copy by the same rule as `apply`: a file with the patched bytes and an excess write bit is not applied yet. An entry that fixes a file's permissions alone is no build - input of a native gem, so it never starts a rebuild. + input of a native gem, so it never starts a rebuild, and a gem copy that + does not hold that entry's file takes the record without it. - Hosted and vendored copies are judged by their content alone, exactly as before, whatever `mode` their entries have: a committed vendored artifact, its installed copies, a hosted install and the stale-install checks. Their files come from the patched archive, which gives every file `0644` or `0755`, and the bits an installer or a git checkout leaves on them follow - the umask. One consequence: an install made from the upstream release + the umask. The same holds for two copies `apply` itself handles: a local + Go patch copy under `.socket/go-patches/`, which this tool writes and the + project commits, and a copy conda built, whose bits are conda's and not + the PyPI release's. Both are written and judged without the `mode`. One consequence: an install made from the upstream release before a permissions-only patch was pinned holds the patched content, so the hosted stale-install check does not see it and it keeps its modes until it is installed again from the patched archive. For a gem that diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index f0cbd30c02..b330f12f70 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -4946,7 +4946,11 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { // build still loads the held jar, so a silent skip would leave // it unpatched behind a clean exit). An Ivy copy expands the // same way over its module's type dirs (`jars/`, `srcs/`, …). - let (targets, absent) = if gradle_cache::expands(copy) { + // A record with a file mode this release cannot read is handed + // over whole, so the engine refuses all of it: split by hash + // dir, the dirs without that entry would be written. + let whole = socket_patch_core::patch::apply::has_unreadable_mode(&patch.files); + let (targets, absent) = if gradle_cache::expands(copy) && !whole { let detailed = gradle_cache::installed_copies_detailed(copy, &patch.files); if detailed.targets.is_empty() { continue; diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index ffd6ae6425..2d0f46b793 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1033,6 +1033,7 @@ async fn generate_vex( entries: plan.vendor_entries.clone(), go_patches, hosted, + hosted_wired: plan.hosted.keys().cloned().collect(), }; let mut outcome = socket_patch_core::vex::applied_patches_with_copies( manifest, diff --git a/crates/socket-patch-core/src/manifest/schema.rs b/crates/socket-patch-core/src/manifest/schema.rs index 627b90d809..92bf31edb0 100644 --- a/crates/socket-patch-core/src/manifest/schema.rs +++ b/crates/socket-patch-core/src/manifest/schema.rs @@ -35,7 +35,9 @@ enum ModeRepr { /// `0` and three octal digits: the permission bits. Bits(u16), /// Any other value, as the manifest or the API response holds it. - Unreadable(serde_json::Value), + /// Boxed: a `Value` is several times the size of the bits, and every + /// file entry would carry the room for one. + Unreadable(Box), } impl FileMode { @@ -107,7 +109,7 @@ impl<'de> Deserialize<'de> for FileMode { Ok(value .as_str() .and_then(Self::parse) - .unwrap_or(Self(ModeRepr::Unreadable(value)))) + .unwrap_or_else(|| Self(ModeRepr::Unreadable(Box::new(value))))) } } diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index 9249802356..cb3ef50412 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -351,6 +351,29 @@ pub(crate) fn mode_excess(meta: &std::fs::Metadata, mode: &FileMode) -> u32 { /// cannot read ([`VerifyStatus::UnreadableMode`]). pub const UNREADABLE_FILE_MODE: &str = "unreadable_file_mode"; +/// `files` with no entry's `mode`: the record as a copy takes it that is +/// judged and written by its content alone (a copy conda built, a local Go +/// patch copy). A record without a `mode` is returned as it is. +pub fn without_modes( + files: &HashMap, +) -> Cow<'_, HashMap> { + if files.values().all(|info| info.mode.is_none()) { + return Cow::Borrowed(files); + } + Cow::Owned( + files + .iter() + .map(|(name, info)| { + let info = PatchFileInfo { + mode: None, + ..info.clone() + }; + (name.clone(), info) + }) + .collect(), + ) +} + /// The entry of `files` whose `mode` this release cannot read /// ([`FileMode::is_readable`]), the first by file name when there are /// several. A record with one is never written in place. @@ -366,6 +389,12 @@ pub(crate) fn unreadable_mode_entry( .min_by(|(a, _), (b, _)| a.cmp(b)) } +/// Whether `files` has an entry whose `mode` this release cannot read: a +/// record that is refused whole, never applied in part. +pub fn has_unreadable_mode(files: &HashMap) -> bool { + unreadable_mode_entry(files).is_some() +} + /// What [`verify_file_patch`] says of a file whose entry has a `mode` this /// release cannot read. pub(crate) fn unreadable_mode_message(mode: &FileMode) -> String { @@ -375,51 +404,89 @@ pub(crate) fn unreadable_mode_message(mode: &FileMode) -> String { ) } +/// A boxed [`VerifyResult`] future: what [`verify_file_patch`] and +/// [`verify_file_content`] return. Boxed by plain functions, so a caller's +/// poll frame holds a pointer and not the verification's own future: the +/// deepest commands run close to a 2 MiB thread stack in a debug build. +pub type VerifyFuture<'a> = futures_util::future::BoxFuture<'a, VerifyResult>; + /// Verify a single file can be patched: its content, and for an entry /// with a `mode` its permission bits (a file holding the patched bytes /// under a write bit the mode does not grant is `Ready`, with /// [`VerifyResult::permissions_only`] set). A file that would be `Ready` /// or `AlreadyPatched` under a `mode` this release cannot read is /// [`VerifyStatus::UnreadableMode`] instead. -pub async fn verify_file_patch( - pkg_path: &Path, - file_name: &str, - file_info: &PatchFileInfo, -) -> VerifyResult { - let mode = file_info.mode.as_ref(); - let mut result = verify_file(pkg_path, file_name, file_info, mode).await; - if let Some(mode) = mode.filter(|mode| !mode.is_readable()) { - if matches!( - result.status, - VerifyStatus::Ready | VerifyStatus::AlreadyPatched - ) { - result.status = VerifyStatus::UnreadableMode; - result.message = Some(unreadable_mode_message(mode)); - result.permissions_only = false; - } +/// +/// An entry without a `mode` is verified by [`verify_file_content`]'s +/// code and nothing else. +pub fn verify_file_patch<'a>( + pkg_path: &'a Path, + file_name: &'a str, + file_info: &'a PatchFileInfo, +) -> VerifyFuture<'a> { + match file_info.mode.as_ref() { + None => Box::pin(verify_content(pkg_path, file_name, file_info)), + Some(mode) => Box::pin(verify_content_and_mode( + pkg_path, file_name, file_info, mode, + )), } - result } /// [`verify_file_patch`] by the file's content alone, whatever `mode` its /// entry has: for a copy this tool wrote itself and git may have checked -/// out since (a vendored artifact), whose permission bits are the -/// extraction's and the checkout's, never the upstream package's. -pub async fn verify_file_content( +/// out since (a vendored artifact), and for a hosted install, whose +/// permission bits are the archive's and the umask's, never the upstream +/// package's. +pub fn verify_file_content<'a>( + pkg_path: &'a Path, + file_name: &'a str, + file_info: &'a PatchFileInfo, +) -> VerifyFuture<'a> { + Box::pin(verify_content(pkg_path, file_name, file_info)) +} + +/// [`verify_content`], then the entry's `mode` over a file whose content +/// is one the entry describes. +async fn verify_content_and_mode( pkg_path: &Path, file_name: &str, file_info: &PatchFileInfo, + mode: &FileMode, ) -> VerifyResult { - verify_file(pkg_path, file_name, file_info, None).await + let mut result = verify_content(pkg_path, file_name, file_info).await; + if !matches!( + result.status, + VerifyStatus::Ready | VerifyStatus::AlreadyPatched + ) { + return result; + } + // Such a file cannot be judged under a mode this release cannot read. + if !mode.is_readable() { + result.status = VerifyStatus::UnreadableMode; + result.message = Some(unreadable_mode_message(mode)); + return result; + } + // An entry with a `mode` is patched by its permission bits too: the + // patched bytes under a write bit the mode does not grant are still to + // patch, and patching them changes the bits alone. + if result.status == VerifyStatus::AlreadyPatched { + let path = pkg_path.join(normalize_file_path(file_name)); + if excess_write_bits(&path, Some(mode)).await != 0 { + result.status = VerifyStatus::Ready; + result.target_hash = Some(file_info.after_hash.clone()); + result.permissions_only = true; + } + } + result } -/// The file's content against the entry's hashes, and its permission bits -/// against `mode` when that is one this release reads. -async fn verify_file( +/// The file's content against the entry's hashes: `Ready`, +/// `AlreadyPatched`, `HashMismatch` or `NotFound`. It never reads the +/// entry's `mode` or the file's permission bits. +async fn verify_content( pkg_path: &Path, file_name: &str, file_info: &PatchFileInfo, - mode: Option<&FileMode>, ) -> VerifyResult { let normalized = normalize_file_path(file_name); // SECURITY: never resolve a key that escapes the package directory. @@ -494,20 +561,6 @@ async fn verify_file( if current_hash == file_info.after_hash || source_hash.as_deref() == Some(file_info.after_hash.as_str()) { - // An entry with a `mode` is patched by its permission bits too: the - // patched bytes under a write bit the mode does not grant are still - // to patch, and patching them changes the bits alone. - if excess_write_bits(&filepath, mode).await != 0 { - return VerifyResult { - file: file_name.to_string(), - status: VerifyStatus::Ready, - message: None, - current_hash: Some(current_hash), - expected_hash: None, - target_hash: Some(file_info.after_hash.clone()), - permissions_only: true, - }; - } return VerifyResult { file: file_name.to_string(), status: VerifyStatus::AlreadyPatched, @@ -1909,6 +1962,57 @@ async fn every_file_already_patched( true } +/// Why [`stage_held_bytes`] staged nothing. The package write is closed +/// either way. +enum HeldBytesError { + /// The file could not be read, or no longer holds the bytes it was + /// verified to hold. + Read(String), + Stage(PackageWriteError), +} + +/// Stage `file_name` with the bytes it holds, under `mode`: the write of a +/// file that is `Ready` for its permission bits alone +/// ([`VerifyResult::permissions_only`]). `verified_hash` is the hash of +/// the bytes verification found there. +/// +/// A plain function that boxes its future: the engine awaits it at one +/// place, so its reads and its stage are no part of the engine's poll +/// frame, which every in-place apply carries. +fn stage_held_bytes<'a>( + write: PackageWrite, + pkg_path: &'a Path, + file_name: &'a str, + mode: Option<&'a FileMode>, + verified_hash: Option<&'a str>, +) -> futures_util::future::BoxFuture<'a, Result<(PackageWrite, Option), HeldBytesError>> { + Box::pin(async move { + let path = pkg_path.join(normalize_file_path(file_name)); + let held = match read_regular_to_bytes(&path).await { + Ok(bytes) => bytes, + Err(e) => { + abort_package(write).await; + return Err(HeldBytesError::Read(e.to_string())); + } + }; + let hash = compute_git_sha256_from_bytes(&held); + if Some(hash.as_str()) != verified_hash { + abort_package(write).await; + return Err(HeldBytesError::Read( + "the file changed while it was being patched".to_string(), + )); + } + let change = FileChange::Write { + content: held, + hash, + mode: mode.cloned(), + }; + stage_change(write, pkg_path, file_name, change) + .await + .map_err(HeldBytesError::Stage) + }) +} + async fn apply_package_patch_at( scope: crate::utils::repo_root::ReadScope, package_key: &str, @@ -1976,8 +2080,10 @@ async fn apply_package_patch_at( // writing another distribution's files into this one, so they act as // the default policy here (content an earlier Socket patch wrote still // gives way to its update). `--strict` stays as strict as it is. + let mut conda_copy = false; let policy = match crate::patch::conda_copy::conda_build(package_key, pkg_path).await { Some(build) => { + conda_copy = true; let refused = crate::patch::conda_copy::refusal_for(&build, package_key, pkg_path, files); // A copy that already holds the patch (an earlier release @@ -2007,6 +2113,16 @@ async fn apply_package_patch_at( } None => policy, }; + // A conda copy's permission bits are conda's, not the PyPI release's + // the record was made from, and a compiled build is never written to: + // such a copy takes the record's content and no `mode`. + let content_only; + let files = if conda_copy { + content_only = without_modes(files); + &*content_only + } else { + files + }; // First, verify all files for (file_name, file_info) in files_in_order(files) { @@ -2271,42 +2387,30 @@ async fn apply_package_patch_at( // included): the stage and rename change its permission bits // alone, and no blob is needed for it. if let Some(verified_hash) = permissions_only.get(file_name.as_str()) { - let held = match read_regular_to_bytes(&pkg_path.join(normalized)).await { - Ok(bytes) => bytes, - Err(e) => { - abort_package(write).await; - result.fail( - ApplyFailureCause::WriteFailed, - format!("Cannot apply patch: {file_name} - {e}"), - ); - return result; - } - }; - let hash = compute_git_sha256_from_bytes(&held); - if Some(hash.as_str()) != *verified_hash { - abort_package(write).await; - result.fail( - ApplyFailureCause::WriteFailed, - format!( - "Cannot apply patch: {file_name} - the file changed while it was being patched" - ), - ); - return result; - } - let change = FileChange::Write { - content: held, - hash, - mode: file_info.mode.clone(), - }; - write = match stage_change(write, pkg_path, file_name, change).await { + let staged = stage_held_bytes( + write, + pkg_path, + file_name, + file_info.mode.as_ref(), + *verified_hash, + ) + .await; + write = match staged { Ok((write, warning)) => { warnings.extend(warning); write } - Err(e) => { + Err(HeldBytesError::Stage(e)) => { write_failed(&mut result, e); return result; } + Err(HeldBytesError::Read(why)) => { + result.fail( + ApplyFailureCause::WriteFailed, + format!("Cannot apply patch: {file_name} - {why}"), + ); + return result; + } }; written.push((file_name, AppliedVia::Permissions)); continue; diff --git a/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs index c2ba6d2f0b..083d2d3c42 100644 --- a/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs +++ b/crates/socket-patch-core/src/patch/apply_file_mode_tests.rs @@ -662,3 +662,28 @@ fn a_permissions_only_entry_has_a_mode_and_unchanged_content() { }; assert!(!added.is_permissions_only()); } + +/// A copy that is judged and written by its content takes the record +/// without its modes; a record that has none is handed over as it is. +#[test] +fn a_content_only_copy_takes_the_record_without_its_modes() { + let plain = one(entry(CODE, b"patched\n", None)); + assert!(matches!( + without_modes(&plain), + std::borrow::Cow::Borrowed(_) + )); + let mut with_modes = one(entry(CODE, CODE, Some("0644"))); + with_modes.insert( + "lib/b.rb".to_string(), + unreadable_entry(CODE, b"patched\n", r#""644""#), + ); + assert!(has_unreadable_mode(&with_modes)); + let stripped = without_modes(&with_modes); + assert!(!has_unreadable_mode(&stripped)); + assert_eq!(stripped.len(), 2); + for (name, info) in stripped.iter() { + assert_eq!(info.mode, None, "{name}"); + assert_eq!(info.before_hash, with_modes[name].before_hash); + assert_eq!(info.after_hash, with_modes[name].after_hash); + } +} diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index f3f05994cb..0026ae438f 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1202,15 +1202,61 @@ impl InstalledGem { files: &'f HashMap, ) -> std::borrow::Cow<'f, HashMap> { use std::borrow::Cow; - match self.jvm() { + let taken = match self.jvm() { Some((copy, platform)) if is_ruby_platform_record(key) => { Cow::Owned(jvm_record(©.gem_dir, platform, key, files).await.files) } _ => Cow::Borrowed(files), + }; + match &self.copy { + Some(copy) => without_absent_permissions_only(©.gem_dir, taken).await, + None => taken, } } } +/// `files` without the entries that fix a file's permissions alone +/// ([`PatchFileInfo::is_permissions_only`]) and whose file the copy at +/// `gem_dir` does not hold: there is no file to clear a bit of. An +/// installed copy lacks files its source gem packs (a precompiled gem +/// never shipped `ext/**`, a build deletes its `ports/**`); for an entry +/// that changes content that is what [`files_as_installed`] is for. +/// +/// A record without such an entry, which is every record without a +/// `mode`, is returned as it is and nothing on disk is looked at. A plain +/// function that boxes the lookup, so a caller's poll frame holds a +/// pointer. +fn without_absent_permissions_only<'f>( + gem_dir: &Path, + files: std::borrow::Cow<'f, HashMap>, +) -> futures_util::future::BoxFuture<'f, std::borrow::Cow<'f, HashMap>> { + if !files.values().any(PatchFileInfo::is_permissions_only) { + return Box::pin(std::future::ready(files)); + } + let gem_dir = gem_dir.to_path_buf(); + Box::pin(async move { + let mut absent = Vec::new(); + for (key, info) in files.iter() { + let path = normalize_file_path(key); + if info.is_permissions_only() + && is_safe_relative_subpath(path) + && matches!( + tokio::fs::symlink_metadata(gem_dir.join(path)).await, + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ) + { + absent.push(key.clone()); + } + } + if absent.is_empty() { + return files; + } + let mut taken = files.into_owned(); + taken.retain(|key, _| !absent.contains(key)); + std::borrow::Cow::Owned(taken) + }) +} + /// [`InstalledGem::record_files`] for the gem copy at `pkg_path`. pub async fn installed_files<'f>( pkg_path: &Path, @@ -5348,21 +5394,24 @@ pub async fn discriminating_files<'f>( return Cow::Borrowed(files); } let gem = InstalledGem::at(pkg_path).await; + // The record as the copy takes it: for an MRI copy, `files` less the + // permissions-only entries of files it does not hold. + let taken = gem.record_files(key, files).await; if gem.jvm().is_some() { - return gem.record_files(key, files).await; + return taken; } - let scope = gem.scope(files); + let scope = gem.scope(&taken); let Some(copy) = gem.copy.filter(|_| !scope.inputs.is_empty()) else { - return Cow::Borrowed(files); + return taken; }; if !scope.builds_extensions && scope.precompiled.is_none() { - return Cow::Borrowed(files); + return taken; } - let (_, absent) = files_as_installed(©, &scope, files).await; + let (_, absent) = files_as_installed(©, &scope, &taken).await; if absent.is_empty() { - return Cow::Borrowed(files); + return taken; } - let mut telling = files.clone(); + let mut telling = taken.into_owned(); telling.retain(|key, _| !absent.iter().any(|path| path == normalize_file_path(key))); Cow::Owned(telling) } @@ -5860,24 +5909,25 @@ pub async fn apply_gem_package_patch( policy: MismatchPolicy, env: &RubyEnv, ) -> GemApplied { - // A record with a file mode this release cannot read is refused by the - // engine before anything is written: no build is started for it. - if crate::patch::apply::unreadable_mode_entry(files).is_some() { - return plain_apply( - read_scope, - package_key, - pkg_path, - files, - sources, - dry_run, - policy, - ) - .await; - } let gem = InstalledGem::at(pkg_path).await; + // A permissions-only entry of a file this copy does not hold has no bit + // to clear: the copy takes the record without it. + let taken = match &gem.copy { + Some(copy) => { + without_absent_permissions_only(©.gem_dir, std::borrow::Cow::Borrowed(files)).await + } + None => std::borrow::Cow::Borrowed(files), + }; + let files = &*taken; + // A record with a file mode this release cannot read goes to the file + // engine, which refuses it before anything is written: no build is + // started for it, and no part of it is applied to a JVM build. (Through + // the one `plain_apply` call below: a second call site would put that + // future in this function's poll frame a second time.) + let unreadable_mode = crate::patch::apply::unreadable_mode_entry(files).is_some(); // The JVM build of a gem has no extension to rebuild: the record is // applied as far as it concerns that build. - if let Some((copy, platform)) = gem.jvm() { + if let Some((copy, platform)) = gem.jvm().filter(|_| !unreadable_mode) { let jvm = JvmApply { read_scope, package_key, @@ -5894,7 +5944,7 @@ pub async fn apply_gem_package_patch( } let scope = gem.scope(files); let copy = gem.copy; - if scope.inputs.is_empty() { + if unreadable_mode || scope.inputs.is_empty() { return plain_apply( read_scope, package_key, @@ -8220,6 +8270,37 @@ mod tests { assert!(matches!(whole, std::borrow::Cow::Borrowed(_))); assert_eq!(*whole, record); assert_eq!(*installed_files(tmp.path(), purl, &record).await, record); + + // Except an entry that fixes a file's permissions alone, of a file + // the copy does not hold: there is no bit to clear, so the copy + // takes the record without it (a precompiled gem never shipped + // its `ext/` sources). The same entry of a file it holds stays, + // and so does an unchanged-content entry without a mode, which is + // the record shape that existed before modes. + use crate::manifest::schema::FileMode; + let entry = |mode: Option<&str>| PatchFileInfo { + before_hash: "a".repeat(64), + after_hash: "a".repeat(64), + mode: mode.map(|m| FileMode::parse(m).unwrap()), + }; + std::fs::create_dir_all(mri.gem_dir.join("lib")).unwrap(); + std::fs::write(mri.gem_dir.join("lib/held.rb"), b"x").unwrap(); + let with_modes: HashMap = HashMap::from([ + ("ext/a/absent.c".to_string(), entry(Some("0644"))), + ("lib/held.rb".to_string(), entry(Some("0644"))), + ("lib/absent_without_mode.rb".to_string(), entry(None)), + ]); + let taken = installed_files(&mri.gem_dir, purl, &with_modes).await; + assert_eq!( + sorted_keys(&taken), + ["lib/absent_without_mode.rb", "lib/held.rb"] + ); + let telling = discriminating_files(&mri.gem_dir, purl, &with_modes).await; + assert!(!telling.contains_key("ext/a/absent.c")); + assert_eq!( + sorted_keys(&rollback_files(&mri.gem_dir, purl, &with_modes).await), + ["lib/absent_without_mode.rb", "lib/held.rb"] + ); } /// With a record for the copy's own platform in the manifest, that diff --git a/crates/socket-patch-core/src/patch/redirect/golang_local.rs b/crates/socket-patch-core/src/patch/redirect/golang_local.rs index 8fa426da95..3f45e33418 100644 --- a/crates/socket-patch-core/src/patch/redirect/golang_local.rs +++ b/crates/socket-patch-core/src/patch/redirect/golang_local.rs @@ -300,6 +300,11 @@ pub async fn apply_go_redirect<'a>( dry_run: bool, policy: MismatchPolicy, ) -> ApplyResult { + // The copy is this tool's own, made from the module and committed: it + // is judged by its content ([`redirect_in_sync`], `vex`), so it is + // written by its content too, whatever `mode` an entry has. + let content_only = crate::patch::apply::without_modes(files); + let files = &*content_only; let pristine_src = pristine_src.into(); // SECURITY: refuse coordinates that would escape the copy base. // A `..`/separator-laden `module`/`version` (a tampered manifest PURL) would diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 1c6ed9f487..3e50d378b0 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -105,6 +105,12 @@ pub struct VendorContext { /// the caller per package manager. When present for a PURL it REPLACES /// the crawler's `package_paths` entry — see [`HostedCopies`]. pub hosted: HashMap, + /// Every PURL the project wires to a hosted patch, including the ones + /// `hosted` has no consumed copies for (the caller resolves those for + /// some ecosystems only). An installer wrote their installed copies + /// from the patched archive, so they are judged by content + /// ([`Judge::Content`]) wherever they are found. + pub hosted_wired: std::collections::HashSet, } /// The installed copies a hosted-wired PURL's build consumes — the CLI @@ -228,18 +234,30 @@ pub async fn applied_patches_with_copies( } else if let Some(copies) = vendor.and_then(|ctx| ctx.hosted.get(purl)) { verify_hosted_copies(purl, copies, record).await } else if let Some(paths) = package_copies.get(purl).filter(|p| !p.is_empty()) { - if Ecosystem::from_purl(purl) == Some(Ecosystem::Maven) { + // The installed tree. A copy there was patched where it is + // installed unless the project wires the package to a hosted + // patch, whose installer wrote it from the patched archive. + let judge = if vendor.is_some_and(|ctx| ctx.hosted_wired.contains(purl)) { + Judge::Content + } else { + Judge::InPlace + }; + // As `apply` refuses it whole: a record with a file mode this + // release cannot read is not applied in place, whatever its + // files hold. + if judge == Judge::InPlace && crate::patch::apply::has_unreadable_mode(&record.files) { + Err(crate::patch::apply::UNREADABLE_FILE_MODE.to_string()) + } else if Ecosystem::from_purl(purl) == Some(Ecosystem::Maven) { let mut first_failure = None; for copy in paths { - if let Err(reason) = verify_record_for(purl, copy, record, Judge::InPlace).await - { + if let Err(reason) = verify_record_for(purl, copy, record, judge).await { out.unpatched_copies.push((purl.clone(), copy.clone())); first_failure.get_or_insert(reason); } } first_failure.map_or(Ok(()), Err) } else if Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) { - match verify_every_gem_copy(purl, paths, record).await { + match verify_every_gem_copy(purl, paths, record, judge).await { Ok(GemVerdict::CodeNotPresent) => { out.code_not_present.push(purl.clone()); Ok(()) @@ -248,7 +266,7 @@ pub async fn applied_patches_with_copies( Err(reason) => Err(reason), } } else { - verify_every_copy(paths, record, Judge::InPlace).await + verify_installed_copies(purl, paths, record, judge).await } } else { Err("package_not_found".to_string()) @@ -649,6 +667,32 @@ fn judge_installed_files(pkg_path: &Path, files: &[(String, String)]) -> Install } } +/// [`verify_every_copy`] for the copies of `purl` in the installed tree. A +/// copy conda built is judged by its content whatever `judge` says: its +/// permission bits are conda's, and `apply` writes it no `mode` +/// ([`conda_build`](crate::patch::conda_copy::conda_build)). +async fn verify_installed_copies( + purl: &str, + paths: &[PathBuf], + record: &PatchRecord, + judge: Judge, +) -> Result<(), String> { + for path in paths { + let judge = match judge { + Judge::InPlace + if crate::patch::conda_copy::conda_build(purl, path) + .await + .is_some() => + { + Judge::Content + } + judge => judge, + }; + verify_patch_files(path, &record.files, judge).await?; + } + Ok(()) +} + /// Every copy must pass [`verify_patch_record`]; the first failure's tag /// wins. The caller guarantees `paths` is non-empty. async fn verify_every_copy( @@ -693,6 +737,7 @@ async fn verify_every_gem_copy( purl: &str, paths: &[PathBuf], record: &PatchRecord, + judge: Judge, ) -> Result { use crate::patch::gem_ext::InstalledGem; if record.files.is_empty() { @@ -703,7 +748,7 @@ async fn verify_every_gem_copy( let gem = InstalledGem::at(path).await; let files = gem.record_files(purl, &record.files).await; if !files.is_empty() { - verify_patch_files(path, &files, Judge::InPlace).await?; + verify_patch_files(path, &files, judge).await?; verdict = GemVerdict::Patched; } gem.verify_native_build(purl, &record.files).await?; @@ -723,8 +768,9 @@ pub async fn gem_copies_patched_in_place( record: &PatchRecord, ) -> bool { !paths.is_empty() + && !crate::patch::apply::has_unreadable_mode(&record.files) && matches!( - verify_every_gem_copy(purl, paths, record).await, + verify_every_gem_copy(purl, paths, record, Judge::InPlace).await, Ok(GemVerdict::Patched) ) } @@ -2015,6 +2061,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let paths: HashMap = HashMap::new(); // no installed tree @@ -2052,6 +2099,7 @@ mod tests { entries: HashMap::from([(purl.to_string(), vendor_entry(purl, &rel))]), go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let version = root .path() @@ -2108,6 +2156,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let out = @@ -2172,6 +2221,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let mut paths = HashMap::new(); paths.insert(purl.to_string(), installed); @@ -2243,6 +2293,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let copies = HashMap::from([(purl.to_string(), installed)]); @@ -2291,6 +2342,7 @@ mod tests { entries: HashMap::from([(purl.to_string(), vendor_entry(purl, &rel))]), go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let copies = HashMap::from([(purl.to_string(), installed.clone())]); @@ -2338,6 +2390,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let mut paths = HashMap::new(); paths.insert(purl.to_string(), cache); @@ -2391,6 +2444,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let mut paths = HashMap::new(); paths.insert(purl.to_string(), installed); @@ -2443,6 +2497,7 @@ mod tests { entries, go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let mut paths = HashMap::new(); paths.insert(purl.to_string(), installed); @@ -2486,6 +2541,7 @@ mod tests { entries: HashMap::new(), go_patches, hosted: HashMap::new(), + hosted_wired: Default::default(), }; // No installed tree (module cache absent) — the redirect copy is @@ -2939,6 +2995,7 @@ mod tests { entries: HashMap::from([(purl.to_string(), entry)]), go_patches: HashMap::new(), hosted: HashMap::new(), + hosted_wired: Default::default(), }; let link = root.join("node_modules/a"); tokio::fs::create_dir_all(root.join("node_modules")) @@ -3174,6 +3231,71 @@ mod tests { ); } + /// The installed tree of a record with a file mode this release cannot + /// read is refused as a whole, as `apply` refuses it: the reason is + /// the mode, whatever its other files hold. A package the project + /// wires to a hosted patch is judged by its content there, mode or + /// not: an installer wrote that copy from the patched archive. + #[cfg(unix)] + #[tokio::test] + async fn the_installed_tree_reads_a_mode_only_for_a_copy_patched_in_place() { + use std::os::unix::fs::PermissionsExt; + let purl = "pkg:composer/acme/x@1.0.0"; + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("index.js"), b"patched").unwrap(); + std::fs::write(dir.path().join("other.js"), b"upstream").unwrap(); + for name in ["index.js", "other.js"] { + std::fs::set_permissions( + dir.path().join(name), + std::fs::Permissions::from_mode(0o664), + ) + .unwrap(); + } + let hash = compute_git_sha256_from_bytes(b"patched"); + let copies = HashMap::from([(purl.to_string(), vec![dir.path().to_path_buf()])]); + let manifest_of = |record: &PatchRecord| { + let mut manifest = PatchManifest::new(); + manifest.patches.insert(purl.to_string(), record.clone()); + manifest + }; + let hosted = VendorContext { + hosted_wired: [purl.to_string()].into(), + ..VendorContext::default() + }; + + // One file under a readable mode, group-writable. + let mut readable = record_with_one_file(&hash); + readable.files.get_mut("index.js").unwrap().mode = + crate::manifest::schema::FileMode::parse("0644"); + let out = applied_patches_with_copies(&manifest_of(&readable), &copies, None).await; + assert_eq!(out.failed[0].reason, "not_applied"); + let out = + applied_patches_with_copies(&manifest_of(&readable), &copies, Some(&hosted)).await; + assert_eq!(out.applied, [purl]); + + // A stale file that sorts first, and a mode that cannot be read on + // the patched one: the mode is the reason in place. + let mut unreadable = record_with_one_file(&hash); + unreadable.files.insert( + "a-first.js".to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"upstream"), + after_hash: compute_git_sha256_from_bytes(b"fixed"), + mode: None, + }, + ); + std::fs::write(dir.path().join("a-first.js"), b"upstream").unwrap(); + unreadable.files.get_mut("index.js").unwrap().mode = + Some(serde_json::from_str(r#""u=rw,go=r""#).unwrap()); + let out = applied_patches_with_copies(&manifest_of(&unreadable), &copies, None).await; + assert!(out.applied.is_empty()); + assert_eq!(out.failed[0].reason, "unreadable_file_mode"); + // Hosted: content alone, so the stale file is what fails it. + let out = + applied_patches_with_copies(&manifest_of(&unreadable), &copies, Some(&hosted)).await; + assert_eq!(out.failed[0].reason, "not_applied"); + } + // ── Maven / Gradle copy sets ──────────────────────────────────── fn stored_jar(members: &[(&str, &[u8])]) -> Vec { From 623941da3535ad76d1913f3b9e76a46fb7b8b98c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 22:19:44 -0500 Subject: [PATCH 7/7] Test that a conda build is never written to for a file mode A compiled conda build that holds a permissions-only record's content is reported as patched and left as it is, loose bits included; a record that changes content is still refused. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-core/src/patch/conda_copy.rs | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/crates/socket-patch-core/src/patch/conda_copy.rs b/crates/socket-patch-core/src/patch/conda_copy.rs index 1a50148c0b..d347708366 100644 --- a/crates/socket-patch-core/src/patch/conda_copy.rs +++ b/crates/socket-patch-core/src/patch/conda_copy.rs @@ -574,6 +574,90 @@ mod tests { } } + /// Nothing is written to a copy conda built to clear a write bit: its + /// permission bits are conda's, so it takes a record without its + /// modes. A compiled build whose files hold the record's content is + /// reported as patched and left exactly as it is, group- and + /// world-writable files included, and one that does not hold it is + /// refused as before. + #[cfg(unix)] + #[tokio::test] + async fn a_conda_build_is_never_written_to_for_a_file_mode() { + use crate::manifest::schema::FileMode; + use crate::patch::apply::{apply_package_patch, MismatchPolicy, PatchSources}; + use crate::utils::repo_root::ReadScope; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let tmp = tempfile::tempdir().unwrap(); + let site = conda_site(tmp.path()); + dist_info(&site, "pillow", "12.3.0", Some("conda"), Some(false)); + let blobs = tempfile::tempdir().unwrap(); + let file = site.join("PIL").join("Image.py"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, b"image").unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o666)).unwrap(); + let inode = std::fs::metadata(&file).unwrap().ino(); + let held = crate::hash::git_sha256::compute_git_sha256_from_bytes(b"image"); + let entry = |before: &str, after: &str| { + HashMap::from([( + "PIL/Image.py".to_string(), + PatchFileInfo { + before_hash: before.to_string(), + after_hash: after.to_string(), + mode: FileMode::parse("0644"), + }, + )]) + }; + let untouched = || { + assert_eq!(std::fs::read(&file).unwrap(), b"image"); + assert_eq!( + std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, + 0o666 + ); + assert_eq!(std::fs::metadata(&file).unwrap().ino(), inode); + }; + + // The fix is the permissions alone: the content is the record's. + let permissions_only = entry(&held, &held); + let result = apply_package_patch( + ReadScope::Workspace, + PLATFORM, + &site, + &permissions_only, + &PatchSources::blobs_only(blobs.path()), + false, + MismatchPolicy::Strict, + ) + .await; + assert!(result.success, "{:?}", result.error); + assert!( + result.files_patched.is_empty(), + "{:?}", + result.files_patched + ); + untouched(); + + // A content change is still refused for a compiled build. + let changes_content = entry(&held, &"a".repeat(64)); + let result = apply_package_patch( + ReadScope::Workspace, + PLATFORM, + &site, + &changes_content, + &PatchSources::blobs_only(blobs.path()), + false, + MismatchPolicy::Strict, + ) + .await; + assert!(!result.success); + assert!( + result.error.as_deref().unwrap_or("").contains(REFUSAL_CODE), + "{:?}", + result.error + ); + untouched(); + } + /// A pure-Python conda build is supported. A platform wheel's record /// is still not its distribution, and the refusal names the wheel. #[tokio::test]