diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 10b3aecec..c8560e6de 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -552,7 +552,7 @@ A patch mirror is a caching proxy the operator runs in front of the patch server * **Operator configuration only.** The base is read from the flag or the environment, never from `socket.yml` or any other repository file (the socket.yml trust boundary below): it names the host every later install fetches from and the host whose references `vex` attests. It must be an `http(s)` URL with a host and no userinfo, query or fragment, in the characters a grant URL may hold; trailing slashes are dropped. Anything else is a usage error (exit 2, `Error: --patch-mirror-url (or SOCKET_PATCH_MIRROR_URL) is not a usable patch mirror base URL: `), checked before the project is read. The message never repeats the value. `apply` is the exception: it does not use the mirror and runs unattended from install hooks, so there a base it cannot use is no mirror and no error. * **What hosted mode writes.** `scan` / `get --mode hosted` move each granted reference onto the mirror before anything else reads it: the artifact URL, and the registry index URL of a gem or Maven-layout reference, keep their path (grant token and patch uuid included) and take the base in place of scheme and authority. The integrity pins are unchanged, and a re-run is idempotent. A Go reference is not moved: its pin is the module path `patch.socket.dev/gopatch/`, which names no host to fetch from (go finds it through `GOPROXY`, see *Installing through the mirror*). A Cargo or NuGet reference is not written at all: `skipped` / `redirect_mirror_unsupported` (their registry index is rendered by the patch server with its own absolute download URLs, which a mirror cannot rewrite; the detail names `--mode vendored`). A reference with no path to serve, or whose mirrored URL the grant gate refuses, is `skipped` / `redirect_mirror_url_refused`. * **Installing through the mirror.** The build installs from the pins alone, so it needs read access to the repository, and each package manager is handed the repository's credentials its own way: npm and pnpm send what `.npmrc` holds for the host (`///:_auth=…`); pip, uv, PDM and Pipenv what a netrc file holds for it; Bundler what `bundle config ` holds; vlt the token its keychain holds for the base or a URL above it (`vlt token add --registry=`). yarn classic sends none for a URL pin outside its registry's path, and yarn berry and Bun none for a URL pin at all, so they need a repository that allows anonymous reads. Go fetches a Socket module over the GOPROXY protocol from the patch server's root, which the mirror serves at its base: list the base first in `GOPROXY` (`GOPROXY=,https://proxy.golang.org`), and go fetches every Socket module through the mirror and moves past its 404 for every other module. The run writes nothing for this. go sends credentials (netrc, `GOAUTH`) only over `https`, so a plain-`http` mirror must allow anonymous reads. A generic remote repository is enough for Go; Artifactory OSS has no Go API (`/api/go/` answers 404 even for a repository of type Go). -* **A project already pinned on the patch server.** npm, pnpm, yarn classic, vlt, `requirements.txt`, uv and Pipenv locks are re-pinned onto the mirror by the same run. A Go pin is never moved (see *What hosted mode writes*). The yarn berry, Bun, Bundler, Poetry and PDM rewriters own an earlier pin only on the host they are writing, so they leave a direct pin as it is: the patch is `skipped` (`redirect_unconfirmed`) and a `redirect_mirror_pin_not_moved` warning names the file, the host and the remedy (`rollback `, then the same command again). +* **A project already pinned on the patch server.** npm, pnpm, yarn classic, vlt, `requirements.txt`, uv and Pipenv locks are re-pinned onto the mirror by the same run. A Go pin is never moved (see *What hosted mode writes*). The yarn berry, Bun, Bundler, Poetry and PDM rewriters own an earlier pin only on the host they are writing, so they leave a direct pin as it is: the patch is `skipped` (`redirect_unconfirmed`) and a `redirect_mirror_pin_not_moved` warning names the file, the host and the remedy (`rollback `, then the same command again). A binary `bun.lockb` is read as well: `rollback` refuses a pin in it, so the remedy named there is the lock as it was before the pin (from version control), then the same command again. For Bun the warning takes the place of `redirect_bun_non_registry_entry_skipped`: an entry that pins this patch on a patch server of the run is the patched copy, not a user's tarball. It is also given when the run pins another copy of the package on the mirror, since the lock still fetches the earlier one from the patch server; that patch is then `applied`, and the run's own `--vex` does not take the package for patched without checking the installed copy. A URL in the same shape on a host the run does not know for a patch server stays a user's tarball (`redirect_bun_non_registry_entry_skipped`). * **pnpm takes `trustLockfile`, never the registry route.** The registry address a grant carries (`npmRegistryUrl`, see "pnpm registry route") is not moved onto the mirror: the document the patch server answers there names the tarball on the patch server itself, which a mirror cannot rewrite, so pnpm would refuse a mirrored tarball against it. A mirrored tarball is no file of that address, which reads as no address, and a mirror run pins a pnpm project exactly as a patch service without registries does (`trustLockfile: true`, with nothing said of registries). A project an earlier run routed is taken off the route by the run that moves its pins onto the mirror: the registries (on the patch server, which the run still knows for one: the configured server, else the one the grants' registry addresses name), the overrides, the locks' records and the registry keys go as in *Leaving the route*, each entry reported as usual, and the `redirect_pnpm_trust_lockfile` warning says "the patch mirror serves no registry for `@`, …". `repair` and `scan --prune` clean up a route's unused entries the same with or without the setting; a registry of the CLI's name shape declared under the mirror's base or elsewhere on its host is on no patch server and is the user's. * **The run's own downloads** (a wheel's metadata, a tarball's `package.json`, a gem for the stale-install refresh) read the patch server, not the mirror, which may want credentials the run does not have. * **The mirror is checked before anything is pinned.** One `HEAD` for each mirrored reference the project's files do not already hold (a re-run that pins nothing new sends none), in candidate order, after the unconfigured-host guard and before the rewrite. The request carries no Socket credential, carries `SOCKET_PATCH_MIRROR_AUTHORIZATION` as its `Authorization` header when that is set, and follows no redirect. 2xx: that pin proceeds. 401 / 403 / 407, or a 3xx: nothing more is asked, every pin the mirror has not already refused proceeds, and one `redirect_mirror_unverified` warning says they were not checked. A transport failure, or no answer within the per-attempt timeout: nothing more is asked, and that reference and every one not yet asked about are `skipped` / `redirect_mirror_unavailable`. Any other answer: that reference is `skipped` / `redirect_mirror_unavailable`. Nothing is written for a skipped reference, and a warning names its package; when the mirror served none of the references it was asked about there is one warning instead, about the mirror. Exit 0 either way, files byte-identical for the skipped references, no `.npmrc` setting when nothing was pinned. No retry. A dry run checks too. @@ -2628,7 +2628,7 @@ command's integration tests check its output. | `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". | | `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. | | `redirect_mirror_unverified` | `warnings[]` (warning, one per run) | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror answered 401 / 403 / 407 or a redirect to the run's check, so the references were written without confirming the mirror serves them. `SOCKET_PATCH_MIRROR_AUTHORIZATION` lets the next run check. | -| `redirect_mirror_pin_not_moved` | `warnings[]` (warning) | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: a yarn berry, Bun, Bundler, Poetry or PDM file pins the patch directly on the patch server, and that pin cannot be moved onto the mirror in place. It is left as it is (the patch is `skipped` / `redirect_unconfirmed`); `rollback ` and a re-run pin it through the mirror. | +| `redirect_mirror_pin_not_moved` | `warnings[]` (warning) | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: a yarn berry, Bun, Bundler, Poetry or PDM file pins the patch directly on the patch server, and that pin cannot be moved onto the mirror in place. It is left as it is (the patch is `skipped` / `redirect_unconfirmed`); `rollback ` and a re-run pin it through the mirror. For a pin in a binary `bun.lockb`, which `rollback` refuses, the detail says to restore the lock as it was before the pin instead. For Bun the warning is also given beside an `applied` event, when the run pinned another copy of the package on the mirror and left the earlier pin. | | `redirect_pin_on_unconfigured_host` | `skipped` (hosted event) + `warnings[]` | scan/get `--mode hosted`: a project file already pins the patch through a URL in the hosted shape on a host this run was not given as a patch mirror or patch server. The pin is left as it is; set `--patch-mirror-url` to that mirror's base, or `--patch-server-url` when the host is another patch server. | | `redirect_grant_malformed` / `redirect_grant_insecure_url` | `skipped` (hosted event) + `warnings[]` | scan/get `--mode hosted` and the in-memory engine: the patch API's reference for the package has a field that is not in the shape the project's files take verbatim (`redirect_grant_malformed`; the detail names the field), or names a plain-`http` artifact or registry index URL on an origin that is neither `--patch-server-url` nor a loopback address (`redirect_grant_insecure_url`; the detail names the host). Refused before anything is planned: nothing is written for the package and it stays unpatched. Exit code unchanged. See the grant gate under "Scan modes (v5.0)". | | `redirect_copy_unpatched` | `warnings[]` (warning) | scan/get `--mode hosted` (pnpm, yarn): the pin was written, but its own lock also installs an unpatched copy of the same `name@version`, which no rewrite reaches: a pnpm `file:` directory or tarball dependency (#935), or a yarn `file:` tarball / directory, URL tarball or berry `portal:` / `link:` dependency declared under another name (`lp2@file:…`, #939, #1236; not repeated for a copy a yarn classic skip warning already names), or a yarn classic copy installed from a parent's `bundleDependencies` (#758). The detail names the lock entry (for a bundled copy, the parent's entry and the copy's directory). Neither the run's own `--vex` nor a later `vex` attests the package (`vex` warns `patched_ref_unattributable`), but discovery still manages the pin, so `rollback` / `remove` undo it. | @@ -2695,7 +2695,7 @@ command's integration tests check its output. | `redirect_bun_patched_dependency_dropped` | rollback/remove `warnings[]` (+ human stderr) | a wet hosted unwind took out of `bun.lock` / `bun.lockb` the hosted URL a project's own `bun patch` is keyed by (`name@`, the key Bun 1.4 writes for a `bun patch` made after the rewire, #1019): from then on `bun install` stops applying that patch, without failing. Only keys the lock resolved to before the unwind and no longer does warn, so a stale key, or one whose resolution the unwind restores, stays silent. The rollback still goes ahead; the detail names the key and says to re-create the patch (`bun patch `, `bun patch --commit`) or remove the entry. Vendored reverts warn the same way as `vendor_bun_patched_dependency_dropped`. Exit 0. | | `redirect_bun_default_trust_lost` / `vendor_bun_default_trust_lost` | `warnings[]` / vendor `warnings[]` (warning) | scan/get `--mode hosted` and vendored mode (bun, `bun.lock` and `bun.lockb`): the rewired package is on Bun's built-in default trusted list (better-sqlite3, esbuild, sharp, …) and the project declares no `trustedDependencies` in its root `package.json` (the copy Bun mirrors in `bun.lock` counts only when `package.json` cannot be read: Bun takes the list from the manifest). Bun 1.3.5 and later apply that list only to packages resolved from the npm registry, so on a hosted URL or a local tarball the package's install scripts are skipped with exit 0 (#371). Emitted only for a package an EARLIER run already pinned or vendored (releases up to 5.1 rewired such a package and warned; a registry copy is no longer taken off the registry, see the next row): the pin stays, and the detail tells the user to add the package to `trustedDependencies` (which replaces Bun's default list, so other default-trusted dependencies whose scripts matter must be listed too). Repeated on every run while the pin stays and no list is declared. Exit 0. | | `redirect_bun_default_trust_skipped` / `vendor_bun_default_trust_refused` | `warnings[]` (warning) / `failed` | scan/get `--mode hosted` and vendored mode (bun, `bun.lock` and `bun.lockb`): the granted package is on Bun's default trusted list, the root `package.json` declares no `trustedDependencies`, and the lock resolves every copy of it from the registry (none is pinned or vendored yet). Rewiring it would make Bun 1.3.5+ skip its install scripts on every install with exit 0 — measured on Bun 1.4.4 with `sqlite3@5.1.4`: `bun install` prints `Blocked 1 postinstall`, the native binding is missing and `require('sqlite3')` throws — so the package is left on the registry, UNPATCHED, and a working install is not traded for a patch. Bun reads `trustedDependencies` from `package.json` alone (a copy written only into `bun.lock` leaves the script blocked on a frozen install and is deleted by a plain one; measured on 1.3.14 and 1.4.4), so no lockfile edit can keep the script running. Hosted: per-dep warning, other packages are still rewired, the in-run VEX never assumes the uuid applied, and no other lock confirms it; exit 0. Vendored: refused before any write or download in the pre-download preflight and in the engine whenever the run would write a NEW local tuple and no copy is vendored yet (a hosted → vendored takeover of such a package is refused the same way and its hosted wiring is put back). Not affected: a project whose `package.json` declares `trustedDependencies` (any list; the `bun.lock` mirror counts only when `package.json` cannot be read), a package off the default list, a pin an earlier run wrote (previous row) together with any further copy of the same package the lock gains later (Bun trusts by name, so the first pin already took the default trust; both modes then wire the new copy too), and agent mode. The detail names the remedy: add the package to `trustedDependencies` in `package.json` (listing any other default-trusted dependency whose scripts matter), run `bun install`, and run socket-patch again; or use `--mode agent`. | -| `redirect_bun_non_registry_entry_skipped` / `vendor_non_registry_entry_skipped` | `warnings[]` / vendor warnings (warning) | scan/get `--mode hosted` and vendored mode (bun, `bun.lock` and `bun.lockb`): the lock also installs the granted `name@version` from a user URL or `file:` tarball (its `-.tgz` leaf names that version). Bun installs it from that spec, so the copy stays unpatched beside any rewired registry copy; it is left untouched, the in-run VEX does not assume the patch, and `vex` attests nothing for that `name@version` (#497). With no registry copy left, vendoring refuses with `vendor_lock_entry_not_rewritable`. A same-name URL / `file:` tarball whose leaf names no version, or a git, folder or `link:` copy, has no version in the lock: these codes do not fire for it, but `vex` attests no ref of that package from that lock (`patched_ref_unattributable`), since the copy may be the wired version. | +| `redirect_bun_non_registry_entry_skipped` / `vendor_non_registry_entry_skipped` | `warnings[]` / vendor warnings (warning) | scan/get `--mode hosted` and vendored mode (bun, `bun.lock` and `bun.lockb`): the lock also installs the granted `name@version` from a user URL or `file:` tarball (its `-.tgz` leaf names that version). Bun installs it from that spec, so the copy stays unpatched beside any rewired registry copy; it is left untouched, the in-run VEX does not assume the patch, and `vex` attests nothing for that `name@version` (#497). In a run with `--patch-mirror-url`, the hosted code is not given for an entry that pins the granted patch itself on a patch server of the run (an earlier hosted pin): `redirect_mirror_pin_not_moved` is given for it instead. With no registry copy left, vendoring refuses with `vendor_lock_entry_not_rewritable`. A same-name URL / `file:` tarball whose leaf names no version, or a git, folder or `link:` copy, has no version in the lock: these codes do not fire for it, but `vex` attests no ref of that package from that lock (`patched_ref_unattributable`), since the copy may be the wired version. | | `redirect_npm_patched_dependency_skipped` | `warnings[]` (warning) | scan/get `--mode hosted` (`package-lock.json` / `npm-shrinkwrap.json`): the project patches the granted `name@version` itself with npm ≥ 12.1's native `npm patch` (a root `package.json` `patchedDependencies` key for `name@version` or the bare name, or a `packages` entry carrying npm's `patched` record, which npm writes in a lockfileVersion 4 lock). npm applies the user's diff on top of whatever tarball the lock names and fails the install `EPATCHFAILED` when it no longer applies, so a hosted pin would break every later `npm ci` / `npm install` (or install bytes VEX can never attest); the dep is left on its registry entry in every present npm lock instead (#711). Per-dep; the detail names the key or lock entry and the remedy (fold the Socket fix into the user's patch, or drop the `patchedDependencies` entry and re-run); when an earlier hosted run already pinned the entry, the detail says so and names `socket-patch rollback ` to restore the registry entry instead of claiming it is unchanged; the in-run VEX never assumes the uuid applied, and no sibling lock confirms it. Vendored mode refuses the lockfileVersion 4 lock `vendor_lockfile_version_unsupported`, its detail naming `npm patch` / `patchedDependencies` and `npm install --lockfile-version 3` (npm keeps a v4 lock at v4 on a plain `npm install`); a v4 lock with no native patch left (no `patchedDependencies` key, no non-null `patched` record) gets a detail naming only that downgrade (#1576). Exit 0. | | `nested_project_skipped` | `warnings[]` (warning) | scan `--mode hosted` / `--mode vendored` (npm family): the crawl found a patched package only in the `node_modules` of a nested, independent npm project below the scan root (a directory with its own npm-family lock that is not a workspace member whose package manager ignores that lock), the root's lockfiles do not list it, and the root's own install holds no copy. A hosted or vendored run rewires only the root's lockfiles, so the package is left out of the run (no `packages[]` row, no event, no VEX statement) instead of failing `vendor_lock_entry_not_found` or skipping `redirect_unconfirmed`. One warning per nested project; the detail names the purls, the project directory and the PATH to pass (`socket-patch scan --mode `). Exit and status unchanged (#1534). | | `patched_projects_below` | `warnings[]` (warning) | `vex`, `apply`, `repair`, `remove` and `rollback `, on the envelope of a run that found no patch at `--cwd` (`manifest_not_found`, vex's `no_patches`, apply's `noManifest`) or, for `rollback `, none the target matches (`patch_not_found`, or `vendor_state_unreadable` when the vendor ledger could not be searched for an identifier): project directories below `--cwd` hold patches. The detail names them and the command for each (`... --cwd `); see "What a bare scan patched at and below `--cwd`" under Scan modes for which directories each command names. Exit code, status and `error` are unchanged. | diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 40a94ae94..4fba99689 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -126,12 +126,26 @@ pub(crate) const MIRROR_PIN_NOT_MOVED: &str = "redirect_mirror_pin_not_moved"; /// writing, so they leave a direct pin alone as a source the user chose. /// Without this the run would report such a patch with only the /// rewriter's own, unrelated-looking reason. +/// +/// The Bun rewriters name such a pin themselves +/// ([`BunPatchShapedPin`](socket_patch_core::patch::redirect::BunPatchShapedPin)), +/// which is how one inside a binary `bun.lockb` is seen at all. They take +/// it for a user's tarball, since they know no host but the mirror; for a +/// pin on a patch server of this run that warning is retracted from +/// `rewrite` here, because the copy is the patched one, and this warning is +/// given in its place, also when another copy of the package was pinned +/// on the mirror: the lock still fetches this one from the patch server. +/// `rollback` refuses a `bun.lockb` pin, so the remedy there is the lock +/// as it was before the pin. fn mirror_pins_not_moved( mirror_sources: &socket_patch_core::hosted::engine::MirrorSources, candidates: &[socket_patch_core::hosted::engine::Candidate], confirmed: &[(String, String)], files: &std::collections::BTreeMap, + rewrite: &mut socket_patch_core::patch::redirect::RewriteResult, ) -> Vec { + use socket_patch_core::vex::discover::hosted_host_in_text; + // By origin: an earlier pin of the patch may carry another grant token // in its path. let served: Vec = mirror_sources @@ -141,35 +155,53 @@ fn mirror_pins_not_moved( .into_iter() .collect(); let mirrored: std::collections::BTreeSet<&str> = mirror_sources.mirrored_urls().collect(); - candidates + let mut retracted = Vec::new(); + let warnings = candidates .iter() .filter(|c| mirrored.contains(c.dep.artifact_url.as_str())) - .filter(|c| !confirmed.iter().any(|(_, uuid)| uuid == &c.dep.patch_uuid)) .filter_map(|c| { - let (file, host) = files.iter().find_map(|(path, text)| { - socket_patch_core::vex::discover::hosted_host_in_text( - text, - &c.dep.patch_uuid, - &served, + let uuid = c.dep.patch_uuid.as_str(); + let bun = rewrite + .bun_patch_shaped_pins + .iter() + .filter(|pin| pin.patch_uuid == uuid) + .filter_map(|pin| Some((pin, hosted_host_in_text(&pin.url, uuid, &served)?))) + .collect::>(); + retracted.extend(bun.iter().map(|(pin, _)| pin.warning.clone())); + let (file, host) = match bun.into_iter().next() { + Some((pin, host)) => (pin.file.as_str(), host), + None if confirmed.iter().any(|(_, done)| done == uuid) => return None, + None => files.iter().find_map(|(path, text)| { + hosted_host_in_text(text, uuid, &served).map(|host| (path.as_str(), host)) + })?, + }; + let remedy = if file == "bun.lockb" { + "restore bun.lockb to its content before the pin (from version control: \ + `socket-patch rollback` cannot restore a pin in a binary lock) and then run \ + this command again" + .to_string() + } else { + format!( + "run `socket-patch rollback {}` and then this command again", + // As `rollback` selects a hosted pin: no qualifiers. + crate::ui::shell_word(socket_patch_core::utils::purl::strip_purl_qualifiers( + &c.purl + )) ) - .map(|host| (path, host)) - })?; + }; Some(socket_patch_core::hosted::engine::warning( MIRROR_PIN_NOT_MOVED, format!( "{}: {file} pins it directly on {host}, and a pin in that file cannot be \ - moved onto the patch mirror {} in place, so it was left as it is; run \ - `socket-patch rollback {}` and then this command again", + moved onto the patch mirror {} in place, so it was left as it is; {remedy}", c.purl, mirror_sources.base(), - // As `rollback` selects a hosted pin: no qualifiers. - crate::ui::shell_word(socket_patch_core::utils::purl::strip_purl_qualifiers( - &c.purl - )) ), )) }) - .collect() + .collect(); + rewrite.warnings.retain(|w| !retracted.contains(w)); + warnings } /// Ask the patch mirror about every mirrored pin this run would newly @@ -2184,6 +2216,7 @@ async fn run_redirect_selected_untracked( &candidates, &done.confirmed, &done.files, + &mut done.rewrite, )); let takeover::Finished { warnings: takeover_pre_warnings, diff --git a/crates/socket-patch-cli/tests/patch_mirror.rs b/crates/socket-patch-cli/tests/patch_mirror.rs index 5d80035d2..f84be9c9c 100644 --- a/crates/socket-patch-cli/tests/patch_mirror.rs +++ b/crates/socket-patch-cli/tests/patch_mirror.rs @@ -44,28 +44,38 @@ const MIRROR_PREFIX: &str = "/artifactory/socket-patch"; struct Pkg { name: &'static str, uuid: &'static str, + version: &'static str, } const FIRST: Pkg = Pkg { name: "mirror-fixture", uuid: "11111111-1111-4111-8111-111111111111", + version: VERSION, }; const SECOND: Pkg = Pkg { name: "other-fixture", uuid: "33333333-3333-4333-8333-333333333333", + version: VERSION, +}; +/// The registry package the Bun fixture locks +/// (`socket-patch-core/tests/fixtures/bun-lockb/1.4.2`). +const BUN: Pkg = Pkg { + name: "is-number", + uuid: "44444444-4444-4444-8444-444444444444", + version: "7.0.0", }; impl Pkg { fn purl(&self) -> String { - format!("pkg:npm/{}@{VERSION}", self.name) + format!("pkg:npm/{}@{}", self.name, self.version) } /// The path the patch server serves the patched tarball at, and so the /// path under the mirror's base. fn served_path(&self) -> String { format!( - "/patch/npm/{0}/{VERSION}/{TOKEN}/{1}/{0}-{VERSION}.tgz", - self.name, self.uuid + "/patch/npm/{0}/{2}/{TOKEN}/{1}/{0}-{2}.tgz", + self.name, self.uuid, self.version ) } @@ -78,7 +88,7 @@ impl Pkg { for (name, body) in [ ( "package/package.json", - format!(r#"{{"name":"{}","version":"{VERSION}"}}"#, self.name), + format!(r#"{{"name":"{}","version":"{}"}}"#, self.name, self.version), ), ( "package/index.js", @@ -446,6 +456,205 @@ async fn a_run_pins_the_mirror_and_a_run_without_it_leaves_the_pin_alone() { assert_eq!(lock(tmp.path()), pinned, "the mirrored pin is untouched"); } +/// A Bun project that locks [`BUN`] from the registry, in a text `bun.lock` +/// or a binary `bun.lockb`. +fn write_bun_project(root: &Path, lock: &str) { + std::fs::write( + root.join("package.json"), + include_bytes!("../../socket-patch-core/tests/fixtures/bun-lockb/1.4.2/package.json"), + ) + .unwrap(); + if lock == "bun.lockb" { + std::fs::write( + root.join(lock), + include_bytes!("../../socket-patch-core/tests/fixtures/bun-lockb/1.4.2/bun.lockb"), + ) + .unwrap(); + return; + } + std::fs::write( + root.join(lock), + format!( + "{{\n \"lockfileVersion\": 1,\n \"packages\": {{\n \ + \"{0}\": [\"{0}@{1}\", \"\", {{}}, \"sha512-UPSTREAMupstream==\"],\n \ + }}\n}}\n", + BUN.name, BUN.version + ), + ) + .unwrap(); +} + +/// #2279: a Bun project an earlier run pinned directly on the patch server, +/// in a run given a mirror. Neither Bun rewriter moves that pin in place, +/// so it is left as it is and the run says which file holds it, on which +/// host, and how to get it onto the mirror; for `bun.lockb`, whose pin +/// `rollback` refuses, not by way of `rollback`. The pinned copy is the +/// patched one: nothing calls it a user's tarball or unpatched. +#[tokio::test] +#[serial] +async fn a_bun_pin_on_the_patch_server_is_named_and_not_called_unpatched() { + for lock in ["bun.lock", "bun.lockb"] { + let api = MockServer::start().await; + mock_socket(&api, &[BUN]).await; + let mirror = MockServer::start().await; + mirror_answers(&mirror, BUN, 200).await; + let base = mirror_base(&mirror); + let tmp = tempfile::tempdir().unwrap(); + write_bun_project(tmp.path(), lock); + let holds = |needle: &str| { + let bytes = std::fs::read(tmp.path().join(lock)).unwrap(); + bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) + }; + + let direct = hosted_scan(tmp.path(), &api, &[], &[]); + assert_eq!( + event(&direct.json(), BUN), + applied(), + "{lock}: {}", + direct.stdout + ); + let served = format!("{}{}", api.uri(), BUN.served_path()); + assert!( + holds(&served), + "{lock}: the first run pins the patch server" + ); + let pinned = std::fs::read(tmp.path().join(lock)).unwrap(); + + let moved = hosted_scan(tmp.path(), &api, &["--patch-mirror-url", &base], &[]); + let env = moved.json(); + assert_eq!( + event(&env, BUN), + skipped("redirect_unconfirmed"), + "{lock}: {env:#}" + ); + let codes = warning_codes(&env); + assert!( + codes.contains(&"redirect_mirror_pin_not_moved".to_string()), + "{lock}: {env:#}" + ); + assert!( + !codes.contains(&"redirect_bun_non_registry_entry_skipped".to_string()) + && !moved.stdout.contains("UNPATCHED"), + "{lock}: the earlier pin is the patched copy, not a user's tarball: {env:#}" + ); + let host = api.uri().trim_start_matches("http://").to_string(); + let not_moved = env["warnings"] + .as_array() + .and_then(|warnings| { + warnings + .iter() + .find(|w| w["code"] == "redirect_mirror_pin_not_moved") + }) + .map(|w| w.to_string()) + .unwrap_or_default(); + assert!( + not_moved.contains(lock) && not_moved.contains(&host) && not_moved.contains(&base), + "{lock}: the warning names the file, the host and the mirror: {not_moved}" + ); + // `rollback` restores a bun.lock pin and refuses a bun.lockb one. + assert_eq!( + not_moved.contains(&format!("run `socket-patch rollback {}`", BUN.purl())), + lock == "bun.lock", + "{lock}: {not_moved}" + ); + if lock == "bun.lockb" { + assert!(not_moved.contains("version control"), "{not_moved}"); + } + assert_eq!( + std::fs::read(tmp.path().join(lock)).unwrap(), + pinned, + "{lock}: the pin is left as it is" + ); + } +} + +/// #2279: the earlier pin is named even when the run pins another copy of +/// the package on the mirror: the lock still fetches the first copy from +/// the patch server, which a build that reaches only the mirror cannot. +#[tokio::test] +#[serial] +async fn a_bun_pin_left_beside_a_copy_moved_to_the_mirror_is_named() { + let api = MockServer::start().await; + mock_socket(&api, &[BUN]).await; + let mirror = MockServer::start().await; + mirror_answers(&mirror, BUN, 200).await; + let tmp = tempfile::tempdir().unwrap(); + write_bun_project(tmp.path(), "bun.lock"); + hosted_scan(tmp.path(), &api, &[], &[]); + // A later install adds a nested copy from the registry. + let lock = tmp.path().join("bun.lock"); + let pinned = std::fs::read_to_string(&lock).unwrap(); + let nested = format!( + " \"is-odd/{0}\": [\"{0}@{1}\", \"\", {{}}, \"sha512-UPSTREAMupstream==\"],\n }}\n}}\n", + BUN.name, BUN.version + ); + let grown = pinned.replacen(" }\n}\n", &nested, 1); + assert_ne!(grown, pinned, "{pinned}"); + std::fs::write(&lock, &grown).unwrap(); + + let moved = hosted_scan( + tmp.path(), + &api, + &["--patch-mirror-url", &mirror_base(&mirror)], + &[], + ); + let env = moved.json(); + let after = std::fs::read_to_string(&lock).unwrap(); + assert!( + after.contains(&mirrored_url(&mirror, BUN)), + "the registry copy is pinned on the mirror: {after}" + ); + assert!( + after.contains(&format!("{}{}", api.uri(), BUN.served_path())), + "the earlier pin is left as it is: {after}" + ); + let codes = warning_codes(&env); + assert!( + codes.contains(&"redirect_mirror_pin_not_moved".to_string()) + && !codes.contains(&"redirect_bun_non_registry_entry_skipped".to_string()), + "{env:#}" + ); +} + +/// The earlier pin is taken for the patched copy only on a patch server of +/// this run. The same `bun.lockb` in a run whose patch server is another +/// host holds a URL nobody vouches for: it stays a user's tarball, reported +/// unpatched, and no mirror warning speaks of it. +#[tokio::test] +#[serial] +async fn a_bun_pin_on_a_host_the_run_does_not_know_stays_a_user_tarball() { + let earlier = MockServer::start().await; + mock_socket(&earlier, &[BUN]).await; + let tmp = tempfile::tempdir().unwrap(); + write_bun_project(tmp.path(), "bun.lockb"); + hosted_scan(tmp.path(), &earlier, &[], &[]); + let pinned = std::fs::read(tmp.path().join("bun.lockb")).unwrap(); + + let api = MockServer::start().await; + mock_socket(&api, &[BUN]).await; + let mirror = MockServer::start().await; + mirror_answers(&mirror, BUN, 200).await; + let moved = hosted_scan( + tmp.path(), + &api, + &["--patch-mirror-url", &mirror_base(&mirror)], + &[], + ); + let env = moved.json(); + let codes = warning_codes(&env); + assert!( + codes.contains(&"redirect_bun_non_registry_entry_skipped".to_string()) + && !codes.contains(&"redirect_mirror_pin_not_moved".to_string()), + "{env:#}" + ); + assert_ne!(event(&env, BUN), applied(), "{env:#}"); + assert_eq!( + std::fs::read(tmp.path().join("bun.lockb")).unwrap(), + pinned, + "nothing is written" + ); +} + /// What the run needs for itself it downloads from the patch server, not /// from the mirror, which may want credentials the run does not have. A /// yarn classic pin reads the served tarball (its sha1 goes into the diff --git a/crates/socket-patch-core/src/patch/redirect/bun_binary.rs b/crates/socket-patch-core/src/patch/redirect/bun_binary.rs index 5a432f816..ce920bca4 100644 --- a/crates/socket-patch-core/src/patch/redirect/bun_binary.rs +++ b/crates/socket-patch-core/src/patch/redirect/bun_binary.rs @@ -49,6 +49,8 @@ pub fn rewrite_bun_binary(content: &[u8], overrides: &[DepOverride], result: &mu Err(_) => unreachable!("validated lock"), }; let mut skipped: Vec = Vec::new(); + // The user-tarball records, for [`super::BunPatchShapedPin`]. + let mut shaped: Vec<(String, RewriteWarning)> = Vec::new(); let attempt = (|| { let mut edits = Vec::new(); let packages = candidate.packages()?; @@ -74,7 +76,7 @@ pub fn rewrite_bun_binary(content: &[u8], overrides: &[DepOverride], result: &mu && !matching.iter().any(|m| m.id == p.id) && user_tarball_version(&name, &p.resolution) == Some(dep.version.as_str()) }) { - skipped.push(RewriteWarning { + let warning = RewriteWarning { code: "redirect_bun_non_registry_entry_skipped".into(), detail: format!( "bun.lockb package #{} installs {name}@{} from a URL or local tarball, \ @@ -83,7 +85,9 @@ pub fn rewrite_bun_binary(content: &[u8], overrides: &[DepOverride], result: &mu release to patch it", p.id, dep.version, ), - }); + }; + shaped.push((p.resolution.clone(), warning.clone())); + skipped.push(warning); } if matching.is_empty() && !skipped.is_empty() { return Ok((Vec::new(), false)); @@ -136,6 +140,9 @@ pub fn rewrite_bun_binary(content: &[u8], overrides: &[DepOverride], result: &mu if !skipped.is_empty() { result.bundled_skipped_uuids.insert(dep.patch_uuid.clone()); } + for (url, warning) in &shaped { + super::BunPatchShapedPin::record("bun.lockb", url, dep, warning, result); + } result.warnings.append(&mut skipped); match attempt { Ok((_, false)) => {} @@ -288,6 +295,77 @@ mod tests { } } + /// #2279: the rewriter knows no host but the one it writes, so a record + /// an earlier run pinned on another host for the SAME patch (the patch + /// server, in a run that moves pins onto a patch mirror) is left as any + /// user tarball is, with the same warning. It is also recorded with + /// that warning, so that a caller that knows the run's patch servers + /// can say what is true of it. A pin of another patch in the same + /// shape is not recorded. + #[test] + fn a_pin_of_the_same_patch_on_another_host_is_recorded() { + let uuid = "11111111-1111-4111-8111-111111111111"; + let on = |base: &str, uuid: &str| DepOverride { + patch_uuid: uuid.into(), + artifact_url: format!( + "{base}/patch/npm/minimist/1.2.2/22222222-2222-4222-8222-222222222222/{uuid}/\ + minimist-1.2.2.tgz" + ), + ..dep("1.2.2") + }; + let direct = on("https://patch.socket.dev", uuid); + let mut first = RewriteResult::default(); + rewrite_bun_binary(FIXTURE, std::slice::from_ref(&direct), &mut first); + assert!(first.confirmed_bun_binary_uuids.contains(uuid)); + assert!(first.bun_patch_shaped_pins.is_empty()); + let pinned = first.binary_files["bun.lockb"].clone(); + + let mirror = "https://repo.example/artifactory/socket-patch"; + for (patch, recorded) in [ + (uuid, true), + ("99999999-9999-4999-8999-999999999999", false), + ] { + let mut moved = RewriteResult::default(); + rewrite_bun_binary(&pinned, &[on(mirror, patch)], &mut moved); + assert!(moved.edits.is_empty(), "{patch}: {:?}", moved.edits); + assert!(moved.binary_files.is_empty(), "{patch}"); + assert!(moved.confirmed_bun_binary_uuids.is_empty(), "{patch}"); + let codes: Vec<_> = moved.warnings.iter().map(|w| w.code.as_str()).collect(); + assert_eq!( + codes, + ["redirect_bun_non_registry_entry_skipped"], + "{patch}: {:?}", + moved.warnings + ); + assert!(moved.bundled_skipped_uuids.contains(patch), "{patch}"); + let pins: Vec<_> = moved + .bun_patch_shaped_pins + .iter() + .map(|pin| { + ( + pin.patch_uuid.as_str(), + pin.file.as_str(), + pin.url.as_str(), + &pin.warning, + ) + }) + .collect(); + if recorded { + assert_eq!( + pins, + [( + uuid, + "bun.lockb", + direct.artifact_url.as_str(), + &moved.warnings[0] + )] + ); + } else { + assert!(pins.is_empty(), "{patch}: {pins:?}"); + } + } + } + #[test] fn malformed_metahash_cannot_confirm_an_existing_binary_redirect() { let mut result = RewriteResult::default(); diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index ef0a182c6..898ef1276 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -439,6 +439,11 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub bundled_skipped_uuids: std::collections::BTreeSet, + /// The Bun lock entries reported as user tarballs that are in the + /// patch server's path shape for the patch being pinned + /// ([`BunPatchShapedPin`]). Skipped while empty, as above. + #[cfg_attr(test, serde(skip_serializing_if = "Vec::is_empty"))] + pub bun_patch_shaped_pins: Vec, /// Patch uuid → the yarn.lock keys of the `npm:` alias entries of its /// package the rewriter left untouched (`redirect_yarn_classic_alias_skipped`, /// `redirect_yarn_berry_alias_skipped`): that copy keeps installing the @@ -975,6 +980,7 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { refused_vlt_uuids, vlt_foreign_uuids, bundled_skipped_uuids, + mut bun_patch_shaped_pins, alias_skipped_entries, vlt_drives: _, gradle_uuids, @@ -1032,6 +1038,9 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { .confirmed_maven_reactor_uuids .extend(confirmed_maven_reactor_uuids); result.bundled_skipped_uuids.extend(bundled_skipped_uuids); + result + .bun_patch_shaped_pins + .append(&mut bun_patch_shaped_pins); for (uuid, keys) in alias_skipped_entries { result .alias_skipped_entries @@ -6619,7 +6628,7 @@ fn rewrite_bun_lock( if is_user_tarball_spec(spec, &fname, &dep.version) && spec != url_spec { user_tarball_skipped = true; result.bundled_skipped_uuids.insert(dep.patch_uuid.clone()); - result.warnings.push(RewriteWarning { + let warning = RewriteWarning { code: "redirect_bun_non_registry_entry_skipped".into(), detail: format!( "bun.lock entry `{}` installs {fname}@{} from a URL or local \ @@ -6628,7 +6637,14 @@ fn rewrite_bun_lock( registry release to patch it", entry.key, dep.version ), - }); + }; + let url = spec + .strip_prefix(fname.as_str()) + .and_then(|rest| rest.strip_prefix('@')); + if let Some(url) = url { + BunPatchShapedPin::record("bun.lock", url, dep, &warning, result); + } + result.warnings.push(warning); } continue; } @@ -6763,6 +6779,50 @@ pub(crate) fn is_prior_hosted_bun_spec(spec: &str, fname: &str, current_url: &st } } +/// A Bun lock entry a rewriter left as a user's tarball +/// (`redirect_bun_non_registry_entry_skipped`) although its URL is in the +/// patch server's path shape and names the uuid of the patch being pinned. +/// +/// A Bun rewriter takes over an earlier pin only on the host it is writing +/// ([`is_prior_hosted_bun_spec`]), so a run that writes a patch mirror +/// meets the pin an earlier run wrote on the patch server as a URL it does +/// not own (#2279). The rewriter knows no host but the one it writes, so +/// it cannot tell that pin from a look-alike on a host nobody vouches for: +/// it treats both as it treats any user tarball, and records the entry +/// here. A caller that knows the run's patch servers may retract +/// [`Self::warning`] for a URL on one of them and say what is true of it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BunPatchShapedPin { + pub patch_uuid: String, + /// `bun.lock` or `bun.lockb`. + pub file: String, + /// The URL the entry installs from. + pub url: String, + /// The user-tarball warning the rewriter raised for the entry. + pub warning: RewriteWarning, +} + +impl BunPatchShapedPin { + /// Record the entry of `file` that installs from `url`, when `url` is + /// in the patch server's path shape for `dep`'s own patch. + pub(crate) fn record( + file: &str, + url: &str, + dep: &DepOverride, + warning: &RewriteWarning, + result: &mut RewriteResult, + ) { + if crate::origin::hosted_shape_uuid(url).as_deref() == Some(dep.patch_uuid.as_str()) { + result.bun_patch_shaped_pins.push(Self { + patch_uuid: dep.patch_uuid.clone(), + file: file.to_string(), + url: url.to_string(), + warning: warning.clone(), + }); + } + } +} + // ── uv.lock ────────────────────────────────────────────────────────────────── fn python_lock_blocks(text: &str) -> Vec<&str> { let mut starts = vec![0]; @@ -18776,6 +18836,78 @@ mod tests { } } + /// #2279: the rewriter knows no host but the one it writes, so the pin + /// an earlier run wrote for the SAME patch on another host (the patch + /// server, in a run that moves pins onto a patch mirror) is left as any + /// user tarball is, with the same warning. It is also recorded with + /// that warning, so that a caller that knows the run's patch servers + /// can say what is true of it. A pin of another patch in the same + /// shape, or a plain user tarball, is not recorded. + #[test] + fn bun_lock_pin_of_the_same_patch_on_another_host_is_recorded() { + let sha512 = format!("sha512-{}==", "A".repeat(86)); + let token = "22222222-2222-4222-8222-222222222222"; + let uuid = "11111111-1111-4111-8111-111111111111"; + let served = |uuid: &str| { + format!( + "https://patch.socket.dev/patch/npm/is-number/6.0.0/{token}/{uuid}/\ + is-number-6.0.0.tgz" + ) + }; + let ovr = npm_override( + "is-number", + "6.0.0", + &served(uuid).replace( + "https://patch.socket.dev", + "https://repo.example/artifactory/socket-patch", + ), + &sha512, + ); + assert_eq!(ovr.patch_uuid, uuid); + let entry = + |url: &str| format!("\"is-number\": [\"is-number@{url}\", {{}}, \"{sha512}\"],"); + let run = |lock: &str| { + let mut files = BTreeMap::new(); + files.insert("bun.lock".to_string(), bun_lock_file(lock, 2)); + let mut r = RewriteResult::default(); + rewrite_bun_lock(&files, std::slice::from_ref(&ovr), &mut r); + r + }; + + let r = run(&entry(&served(uuid))); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + warning_codes(&r), + vec!["redirect_bun_non_registry_entry_skipped"], + "{:?}", + r.warnings + ); + assert!(r.bundled_skipped_uuids.contains(uuid)); + assert_eq!( + r.bun_patch_shaped_pins, + vec![BunPatchShapedPin { + patch_uuid: uuid.into(), + file: "bun.lock".into(), + url: served(uuid), + warning: r.warnings[0].clone(), + }] + ); + + for other in [ + served("99999999-9999-4999-8999-999999999999"), + "https://registry.npmjs.org/is-number/-/is-number-6.0.0.tgz".to_string(), + ] { + let r = run(&entry(&other)); + assert_eq!( + warning_codes(&r), + vec!["redirect_bun_non_registry_entry_skipped"], + "{other}: {:?}", + r.warnings + ); + assert!(r.bun_patch_shaped_pins.is_empty(), "{other}"); + } + } + /// #580: the bundled check runs only for entries whose spec matches the /// patch. A bundled copy of ANOTHER package (or another version) beside /// the target never warns or keeps the patch out of VEX, while a bundled