diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..76cf99dcd 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -515,7 +515,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive. Only copies of the builds the restored lock names are judged, each under its own leaf (the ruby-platform gem alone when the lock cannot be read): a platform build the restored lock names (`nokogiri (1.18.10-arm64-darwin)`) is judged and refreshed against that build's own upstream sha256 (its `CHECKSUMS` entry, else the compact index's `-` line) and from `/gems/--.gem`; so is its archive in bundler's cache dir. A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install`, said with its cost: another project that still pins the hosted patch of that gem version then loads the upstream code, which `socket-patch scan` reports there. A path in the warning's `rm -f` command is shell-quoted when it needs to be. A project path outside the project directory that the unwind left alone is named without `--gem-refresh-shared`, for the same reason. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk; a remote `SOCKET_RUBYGEMS_URL` names is the registry, not another remote). The registry is never asked about a gem the lock resolves from another remote: an archive of such a gem in Bundler's cache dir, under a lock with no `CHECKSUMS` entry for it, is named by `upstream_gem_stale_cache` as one that could not be checked. An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive. Only copies of the builds the restored lock names are judged, each under its own leaf (the ruby-platform gem alone when the lock cannot be read): a platform build the restored lock names (`nokogiri (1.18.10-arm64-darwin)`) is judged and refreshed against that build's own upstream sha256 (its `CHECKSUMS` entry, else the compact index's `-` line) and from `/gems/--.gem`; so is its archive in bundler's cache dir. A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. So is a copy whose gem home does hold an archive, when nothing gives the upstream sha256 to check that archive against (a lock without `CHECKSUMS` that resolves the gem from another remote, or `--offline` or a registry error): the archive says nothing, so the pinned patch records judge the copy's files, a copy proven patched is reported as left on the patched build, and one no record could judge is reported as one that could not be checked ("nothing gives the sha256 of its upstream gem and …"). An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install`, said with its cost: another project that still pins the hosted patch of that gem version then loads the upstream code, which `socket-patch scan` reports there. A path in the warning's `rm -f` command is shell-quoted when it needs to be. A project path outside the project directory that the unwind left alone is named without `--gem-refresh-shared`, for the same reason. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. @@ -2054,7 +2054,7 @@ v5.0 replaces v4's per-purl reverts and whole-ledger reverse replay (`revert_rem * **cargo** — `Cargo.lock` back on crates.io (source + the sparse index's checksum, `SOCKET_CRATES_INDEX`). When the lock already holds a crates.io block for the same `name@version` (a later dependent locked its own copy, #679), the Socket block merges into it instead: it is dropped (with a v1 lock's `[metadata]` line), and dependents' references take the spelling cargo writes, so no duplicate block is left that cargo cannot parse (#863), and no index lookup is needed; every `Cargo.toml` declaration loses its `registry = "socket-patch-"` pin (the shorthand the rewriter produced collapses back); every `[registries.socket-patch-]` block no manifest or lock still references leaves the project cargo config — including a superseded patch generation's block an earlier re-pin left behind (#864). A declaration it cannot unpin refuses. * **golang** — the hosted `replace` (in the root `go.mod`, an in-root workspace member's `go.mod`, or `go.work`) and the socket module's sum lines (its `go.sum`, `go.work.sum`, and for a `go.work` pin each in-root member's `go.sum`) go; the upstream module's two go.sum lines come back: for a `go.mod` pin into the `go.sum` beside it; for a `go.work` pin, which leaves the members' pair in place, only when no sum file holds them, into each sum file that held the socket pair, else `go.work.sum`. A `go.work.sum` left empty is removed; hashed from the module proxy (`SOCKET_GOPROXY`, else `GOPROXY` / `GONOPROXY` / `GOPRIVATE` as go reads them) and cross-checked against the checksum database (`SOCKET_GOSUMDB_URL`, else `sum.golang.org` unless `GOSUMDB=off` / `GONOSUMDB` / `GOPRIVATE` say go would not ask it). A `replace` the user had before the hosted run is not recorded anywhere, so the restore lands on the plain upstream module. * **pypi** — `Pipfile.lock`, `requirements.txt` (+ in-root `-r` includes), Hatch PEP 508 direct references (`pyproject.toml` / `hatch.toml`), `poetry.lock`, `pdm.lock`, `uv.lock`, PEP 723 script locks and PEP 751 `pylock*.toml` (+ the paired `pyproject.toml` / script metadata): hashes re-derived from PyPI's JSON API (`SOCKET_PYPI_JSON_API`). A restored `requirements.txt` line gets `--hash` options only when the file is in pip's hash-checking mode. The mode is read off the file's other requirement lines (an `-e` / `--editable` line means unhashed). When every requirement is a hosted pin, it is read off the hosted line itself (`--hash` vs a `#sha256=` url fragment) (#410). Refused: a `static_urls` `pdm.lock` whose project installs from an index other than PyPI (a `[[tool.pdm.source]]` in the sibling `pyproject.toml`, a project `pypi.url` (`.pdm.toml`, then `pdm.toml`), or, with neither, another package's file URL in the lock off PyPI's file host), since restoring PyPI's file URLs would make `pdm sync` bypass that index (#413); a `pdm.lock` without `cross_platform`, or a uv / script / pylock lock, whose release has a wheel that is not pure Python 3 (which files the lock keeps is not re-derivable); a uv lock whose options filter files (`exclude-newer`, `no-binary`, `no-build`, or an `exclude-newer-package` cutoff for the restored package; one of `false` exempts it from the global cutoff here and in pylocks, as in uv) (#1604); a pylock from `uv pip compile` whose header command line (`--no-build`, `--only-binary`, `--no-binary`, `--exclude-newer`, `--exclude-newer-package`) or uv settings (the nearest `uv.toml`, else a pyproject's `[tool.uv]` / `[tool.uv.pip]`, then the user's and the system's `uv.toml` unless `UV_NO_CONFIG` is set, merged as uv does with `[pip]` over the top level; none under `--no-config`, and any `--config-file` refuses; `UV_CONFIG_FILE` or `UV_EXCLUDE_NEWER` set in the restoring environment also refuses, since the header does not record uv's environment) filter the restored package's files, or whose header records no `uv pip compile` command line (`--no-header`, `UV_CUSTOM_COMPILE_COMMAND`), since uv 0.9.16 records only the files those filters let through (#1613); a uv lock whose other registry packages name several registries, or one other than PyPI's simple index; a uv 0.2 `[[distribution]]` lock with no other registry package; a pylock whose other registry packages show neither an `index` nor (as `uv pip compile` writes them) only PyPI files with none, which restores the entry without an `index` too. A `[[package]]` uv lock (uv 0.2.35 and later, script locks included) in which every registry package is hosted — a project with one dependency — has no other entry to show its registry or the artifact fields uv records, so the entry is rebuilt on PyPI's default index with the fields uv writes at the lock's `revision` (`url`, `hash`, `size` with no `revision` and at revision 1; those and `upload-time` at revisions 2 and 3), which is byte for byte what `uv lock` wrote except on uv 0.6.15–0.6.17, whose `upload_time` spelling comes back as the `upload-time` they also read; the run warns `upstream_uv_entry_rebuilt`. That rebuild is refused when the lock's `revision` is newer than 3, or when uv is configured with a package index, since the entry's registry is then not known to be PyPI: `index`, `index-url`, `extra-index-url`, `find-links` or `no-index` in the paired `pyproject.toml` / script `[tool.uv]`, in the nearest `uv.toml` (else pyproject `[tool.uv]`) or the user's or system `uv.toml`, or `UV_INDEX` / `UV_DEFAULT_INDEX` / `UV_INDEX_URL` / `UV_EXTRA_INDEX_URL` / `UV_FIND_LINKS` / `UV_NO_INDEX` set in the restoring environment. Restored artifact fields keep the spelling the lock's other entries show, including the `upload_time` that uv 0.6.15–0.6.17 write. A uv 0.2 `[[distribution]]` lock (uv 0.1.45–0.2.34) is restored like a `[[package]]` one, in the grammar the hosted rewrite wrote the entry in, which is the entry's own: its source keeps its spelling (a string `"direct+…"` back to `"registry+…"`, uv ≤ 0.2.17, or an inline table), its artifacts their grammar (`[distribution.sdist]` / `[[distribution.wheel]]` sub-tables, uv ≤ 0.2.5, or inline), and dependents' references, inline or `[[distribution.dependencies]]` tables, are pointed back. Refused there: an entry with an sdist and inline `dependencies` when no other registry entry of the lock carries both (uv 0.2.18–0.2.22 and 0.2.23–0.2.34 order them differently; hosted mode refuses to wire such an entry, `redirect_uv_lock_unsupported`); and, for the inline-artifact grammar, an `exclude-newer` cutoff the lock does not record: the project's settings (`uv.toml`, else the pyproject's `[tool.uv]`), the user's or system `uv.toml`, or `UV_EXCLUDE_NEWER` (uv 0.2.12–0.2.27 apply these without recording them; hosted mode refuses to wire a lock whose project sets one). A cutoff uv 0.2.28–0.2.33 recorded at the lock's top level refuses like an `[options]` one. A cutoff passed to uv 0.2.6–0.2.27 only on the command line leaves no trace and cannot be detected. A restored pylock entry's `upload-time`s are whole seconds, as uv writes them, unless the lock's other entries show fractions. Its artifacts come back in the TOML spelling the other entries use: uv's inline `wheels = [{ … }]`, or the standard tables `pip lock` writes (`[[packages.wheels]]` with a `[packages.wheels.hashes]` sub-table, `[packages.sdist]`). A `pip lock` file (`created-by = "pip"`) records only the artifact pip selected, so the entry is restored with only the release's wheel (its sdist when it has none), and a release with several wheels is refused. A transitive `override-dependencies` entry hosted mode added is removed (`upstream_uv_override_removed`). Hosted mode keeps no ledger, so it marks the entry it adds with a `# socket-patch hosted: …` comment line above it and removes only a marked entry; a user's own `==` override (which the hosted rewrite reuses rather than adding a second one) is kept, and the lock's `[manifest] overrides` record of it gets its specifier back. - * **gem** — `Gemfile.lock` / `gems.locked` + `Gemfile` / `gems.rb`: the spec moves back into the upstream `GEM` section (or the Socket remote leaves a merged section), the Socket source comes off the manifest, the `CHECKSUMS` entry is re-pinned from the rubygems.org compact index (`SOCKET_RUBYGEMS_URL`) and the `DEPENDENCIES` pin loses its `!`. A gem hosted as platform builds has every entry of its Socket section moved back to where Bundler sorts it (by full name: `nokogiri (1.18.10)` before `nokogiri (1.18.10-arm64-darwin)`), and each `CHECKSUMS` entry re-pinned to its own build's upstream sha256, the index's `-` line (one `info/` request per gem). **The unwind is exact**: the `, source: ""` option hosted mode appended to the declaration is removed (nothing else of the declaration was ever changed), and the line it added for a transitive gem (marked `# added by socket-patch (transitive dependency)`) is removed with the blank line before it and the gem's `DEPENDENCIES` entry, so the pair is the pre-scan pair byte for byte, for every declaration form and with LF or CRLF files. A pin socket-patch 5.0 / 5.1 wrote as a `source "" do … end` block is undone too (also when a superseding hosted re-scan on a lock with no `CHECKSUMS` section has moved that block to the newer patch of the same name and version while the lock still pins the older one; several such blocks are refused), but that rewrite did not keep the declaration it replaced: the gem comes back as the exact pin `gem "", ""[, ]`, and the run reports `upstream_gem_declaration_pinned` once per manifest, naming each declaration restored that way, so a version range can be put back by hand. For such a block the `DEPENDENCIES` pin keeps its `!` when the declaration comes back inside the user's own `source "…" do` block (Bundler writes the `!` for any dependency declared in one, rubygems.org included). A block 5.0 / 5.1 appended for a transitive gem with a blank line before it is removed with that line and the `DEPENDENCIES` entry; one with no blank line before it can't be told apart from an in-place rewrite, so it comes back as the exact pin. Refused: an ambiguous upstream section, an upstream remote other than rubygems.org. The manifest pair can't make a committed bundler cache upstream: a `-.gem` (or a platform build's `--.gem`) left in Bundler's cache dir that isn't the upstream archive is named by `upstream_gem_stale_cache`, never deleted. + * **gem** — `Gemfile.lock` / `gems.locked` + `Gemfile` / `gems.rb`: the spec moves back into the upstream `GEM` section (or the Socket remote leaves a merged section), the Socket source comes off the manifest, the `CHECKSUMS` entry is re-pinned from the rubygems.org compact index (`SOCKET_RUBYGEMS_URL`) and the `DEPENDENCIES` pin loses its `!`. A gem hosted as platform builds has every entry of its Socket section moved back to where Bundler sorts it (by full name: `nokogiri (1.18.10)` before `nokogiri (1.18.10-arm64-darwin)`), and each `CHECKSUMS` entry re-pinned to its own build's upstream sha256, the index's `-` line (one `info/` request per gem). **The unwind is exact**: the `, source: ""` option hosted mode appended to the declaration is removed (nothing else of the declaration was ever changed), and the line it added for a transitive gem (marked `# added by socket-patch (transitive dependency)`) is removed with the blank line before it and the gem's `DEPENDENCIES` entry, so the pair is the pre-scan pair byte for byte, for every declaration form and with LF or CRLF files. A pin socket-patch 5.0 / 5.1 wrote as a `source "" do … end` block is undone too (also when a superseding hosted re-scan on a lock with no `CHECKSUMS` section has moved that block to the newer patch of the same name and version while the lock still pins the older one; several such blocks are refused), but that rewrite did not keep the declaration it replaced: the gem comes back as the exact pin `gem "", ""[, ]`, and the run reports `upstream_gem_declaration_pinned` once per manifest, naming each declaration restored that way, so a version range can be put back by hand. For such a block the `DEPENDENCIES` pin keeps its `!` when the declaration comes back inside the user's own `source "…" do` block (Bundler writes the `!` for any dependency declared in one, rubygems.org included). A block 5.0 / 5.1 appended for a transitive gem with a blank line before it is removed with that line and the `DEPENDENCIES` entry; one with no blank line before it can't be told apart from an in-place rewrite, so it comes back as the exact pin. Refused: an ambiguous upstream section; a `CHECKSUMS` entry to re-pin for a gem whose upstream remote is neither rubygems.org nor the server `SOCKET_RUBYGEMS_URL` names (a `source` line naming a private gem server). That refusal names the setting (unless the remote is plain `http` to another host, which the setting refuses): with `SOCKET_RUBYGEMS_URL=` the entry is re-pinned from the server's own compact index and the pair is restored as for rubygems.org. The manifest pair can't make a committed bundler cache upstream: a `-.gem` (or a platform build's `--.gem`) left in Bundler's cache dir that isn't the upstream archive is named by `upstream_gem_stale_cache`, never deleted. * **composer** — `composer.lock`: `dist` and the deleted `source` block from packagist's composer v2 metadata (`SOCKET_PACKAGIST_URL`). Refused unless the entry is packagist-sourced and packagist still serves the lock's `dist.reference` for the version. * **maven** — `pom.xml` (the `-socket.` version suffix, the added `` / `` entry) and the `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` lines hosted mode writes: **no network**, so it restores under `--offline` too. `.mvn` files holding anything else keep the resolver lines (`maven_trusted_checksums_left`). In a config that stays, the six settings hosted mode wrote are respelled for the Maven the project declares, as a hosted scan respells them, so the line an earlier release wrote does not go on stopping Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project; when that takes the pin's enforcement on Maven 4 away, `maven_trusted_checksums_maven3_only` says so. * **nuget** — `nuget.config` loses the `socket-patch-` source and its exact-id mapping; every lock entry of the id at the pinned version, in every lock the root config governs (member projects' and `packages..lock.json` included), gets nuget.org's `contentHash` back (`SOCKET_NUGET_URL`). Refused when the restored config would not resolve the id from nuget.org alone. A config hosted mode created from scratch is kept (`nuget_default_config_left`). @@ -2310,7 +2310,7 @@ Env-only knobs used for hosted upstream restoration and JVM metadata verificatio | `SOCKET_CRATES_INDEX` | `https://index.crates.io` | v5.0 upstream restore: the crates.io sparse index whose `checksum` a restored `Cargo.lock` entry gets back. | | `SOCKET_GOSUMDB_URL` | `https://sum.golang.org` | v5.0 upstream restore: the checksum database the restored go.sum lines are checked against. Without it, `GOSUMDB=off` or a module matching `GONOSUMDB` (default `GOPRIVATE`) skips the database and the hashes come from the module proxy's bytes alone (`SOCKET_GOPROXY` above). | | `SOCKET_PYPI_JSON_API` | `https://pypi.org/pypi` | PyPI's JSON API (`///json`): the release files whose sha256 the upstream restore writes back into every Python lock format. | -| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from. Agent mode: the registry the source gem of a native-extension gem (`/gems/`), and a gem its build lacks, are downloaded from and their checksums read from (`/info/`); a lock `remote:` equal to it counts as the registry. Must be an `https` URL, or plain `http` to a loopback host (`localhost`, `127.0.0.1`, `[::1]`): gems fetched from it are installed and built, and their checksums pinned, so any other value is refused before a request is made, with a message that says to use an https URL, and a redirect that leaves `https` is not followed. A request to a loopback host is never sent through a proxy. The outcome of a refused value is that of a registry that cannot be reached, said out loud: a pin whose `CHECKSUMS` entry must be re-pinned is not restored, an installed copy is not refreshed and is reported as unchecked (`upstream_gem_stale_install`), a source gem is not downloaded. Credentials in the URL are sent to the registry and never printed. | +| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from, for a gem the lock resolves from rubygems.org or from the server this names (a private gem server a `source` line names: `rollback` / `remove` re-pin a `CHECKSUMS` entry of its gems only with this set to it; a lock without `CHECKSUMS` is restored without it). Agent mode: the registry the source gem of a native-extension gem (`/gems/`), and a gem its build lacks, are downloaded from and their checksums read from (`/info/`); a lock `remote:` equal to it counts as the registry. Must be an `https` URL, or plain `http` to a loopback host (`localhost`, `127.0.0.1`, `[::1]`): gems fetched from it are installed and built, and their checksums pinned, so any other value is refused before a request is made, with a message that says to use an https URL, and a redirect that leaves `https` is not followed. A request to a loopback host is never sent through a proxy. The outcome of a refused value is that of a registry that cannot be reached, said out loud: a pin whose `CHECKSUMS` entry must be re-pinned is not restored, an installed copy is not refreshed and is reported as unchecked (`upstream_gem_stale_install`), a source gem is not downloaded. Credentials in the URL are sent to the registry and never printed. | | `SOCKET_PACKAGIST_URL` | `https://repo.packagist.org` | v5.0 upstream restore: packagist's composer v2 metadata (`/p2//.json`) a restored `composer.lock` `dist` / `source` comes from. | | `SOCKET_NUGET_URL` | `https://api.nuget.org` | v5.0 upstream restore: the nuget.org API host whose catalog `packageHash` a restored `packages.lock.json` `contentHash` comes from. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 2aa74e510..301486010 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1108,8 +1108,11 @@ enum NoRecord { NotServed, } -/// What judges the installed copies a hosted unwind's archive check cannot -/// (#2092): those whose gem home keeps no readable `/cache/.gem`. +/// What judges the installed copies a hosted unwind's archive check cannot: +/// those whose gem home keeps no readable `/cache/.gem` (#2092), +/// and those of a build nothing gives the upstream sha256 of, so that its +/// archive says nothing (#2230: a gem from another remote, or `--offline` +/// or a registry error, under a lock without `CHECKSUMS`). /// Nothing else tells such a copy from the patched build the hosted scan /// may have replaced it with, and no later `bundle install` replaces it. /// Each is judged on its own files, by the record of a patch its gem was @@ -1157,8 +1160,11 @@ impl PinJudge<'_> { } /// The installed copies of `builds` (`(purl, leaf)`, the builds the - /// restored lock names for the pinned gems) with no readable archive in - /// their gem home: those that hold a pinned patch (stale), and those nothing + /// restored lock names for the pinned gems) that no archive judges: + /// one with no readable archive in its gem home, and one of a build + /// that is not in `by_archive` (the leaves the archive check has an + /// upstream sha256 for, or reports itself). Of those: the copies that + /// hold a pinned patch (stale), and those nothing /// could judge, each with why (the reason completes "could not be /// checked against the upstream gem (…)"). A copy is neither when a /// record judged it and found files that are not its patch's, and no @@ -1167,6 +1173,7 @@ impl PinJudge<'_> { async fn probe( &mut self, builds: &[(String, String)], + by_archive: &BTreeSet, ) -> (Vec, Vec<(StaleGem, String)>) { use socket_patch_core::vendor::file_sha256_hex; use socket_patch_core::vex::verify::judge_installed_record; @@ -1174,10 +1181,17 @@ impl PinJudge<'_> { let (mut stale, mut unjudged) = (Vec::new(), Vec::new()); for copy in installed_builds(self.common, builds).await { // The same test as `stale_after_restore`'s: an archive it can - // hash is its to judge the copy by. - if file_sha256_hex(©.archive).await.is_some() { + // hash is its to judge the copy by, when it has the upstream + // sha256 to hold that archive against. + let archived = file_sha256_hex(©.archive).await.is_some(); + if archived && by_archive.contains(©.leaf) { continue; } + let unjudged_by_archive = if archived { + "nothing gives the sha256 of its upstream gem" + } else { + "its gem home has no archive of it" + }; // Why the copy is not known to be free of a pinned patch: a pin // with no record, or a record whose files could not be read. let (mut patched, mut open) = (false, None); @@ -1216,7 +1230,7 @@ impl PinJudge<'_> { match (patched, open) { (true, _) => stale.push(gem), (false, Some(why)) => { - unjudged.push((gem, format!("its gem home has no archive of it and {why}"))) + unjudged.push((gem, format!("{unjudged_by_archive} and {why}"))) } (false, None) => {} } @@ -1484,11 +1498,13 @@ async fn refresh_restored( if shas.is_empty() && unverified.is_empty() && judged.is_empty() && pinned.is_empty() { return RestoreRefresh::default(); } - // A hosted unwind's copies with no archive to judge them by: stale - // when they hold a pinned patch, reported when no record says (#2092). + // A hosted unwind's copies that no archive judges (none in the gem + // home, #2092; or no upstream sha256 to hold it against, #2230): stale + // when they hold a pinned patch, reported when no record says. let pinned_builds = build_leaves(&named, |purl| pinned.iter().any(|p| p == purl)); + let by_archive: BTreeSet = shas.keys().chain(unverified.keys()).cloned().collect(); let (pin_stale, no_record) = match &mut pin_judge { - Some(judge) => judge.probe(&pinned_builds).await, + Some(judge) => judge.probe(&pinned_builds, &by_archive).await, None => Default::default(), }; let pin_stale_any = !pin_stale.is_empty(); @@ -1543,7 +1559,7 @@ async fn refresh_restored( let mut still = stale_after_restore(common, &named, &shas, &judged, scope).await; // (A copy no record judged is not one the pass could change.) if let Some(judge) = pin_judge.as_mut().filter(|_| pin_stale_any) { - still.extend(judge.probe(&pinned_builds).await.0); + still.extend(judge.probe(&pinned_builds, &by_archive).await.0); } still } else { @@ -2055,7 +2071,11 @@ mod tests { vec!["uuid-a".to_string(), "uuid-b".to_string()], )]); // `--offline`: only the records seeded below are there to judge by. - let probe = |tmp: &tempfile::TempDir, fetched: Vec<(&str, Option)>| { + // `sha_known`: whether the archive check has the upstream sha256 of + // the build (a `CHECKSUMS` entry, or the registry's answer). + let probe_as = |tmp: &tempfile::TempDir, + fetched: Vec<(&str, Option)>, + sha_known: bool| { let fetched = fetched .into_iter() .map(|(uuid, record)| (uuid, record.ok_or(NoRecord::NotServed))); @@ -2078,11 +2098,16 @@ mod tests { unreachable: false, }; let builds = [(PURL.to_string(), "rack-1.0.0".to_string())]; - let (stale, unjudged) = judge.probe(&builds).await; + let by_archive: BTreeSet = sha_known + .then(|| "rack-1.0.0".to_string()) + .into_iter() + .collect(); + let (stale, unjudged) = judge.probe(&builds, &by_archive).await; assert!(api.get().is_none(), "an offline probe builds no client"); (stale.len(), unjudged) } }; + let probe = |tmp: &tempfile::TempDir, fetched| probe_as(tmp, fetched, true); let (a, b) = (record("uuid-a", "patch a\n"), record("uuid-b", "patch b\n")); let both = || vec![("uuid-a", Some(a.clone())), ("uuid-b", Some(b.clone()))]; @@ -2138,6 +2163,26 @@ mod tests { let tmp = project("patch b\n", true); let (stale, unjudged) = probe(&tmp, both()).await; assert_eq!((stale, unjudged.len()), (0, 0)); + + // #2230: unless nothing gives the upstream sha256 to hold that + // archive against (a gem from a private mirror under a lock with + // no `CHECKSUMS`). The copy is then judged on its files like one + // with no archive: the patched build is stale, ... + let (stale, unjudged) = probe_as(&tmp, both(), false).await; + assert_eq!((stale, unjudged.len()), (1, 0)); + // ... the upstream build is not, ... + let tmp = project("upstream\n", true); + let (stale, unjudged) = probe_as(&tmp, both(), false).await; + assert_eq!((stale, unjudged.len()), (0, 0)); + // ... and one no record judges is reported, with a reason that + // does not say the archive is missing. + let (stale, unjudged) = probe_as(&tmp, vec![("uuid-b", Some(b.clone()))], false).await; + assert_eq!((stale, unjudged.len()), (0, 1)); + assert_eq!( + unjudged[0].1, + "nothing gives the sha256 of its upstream gem and `--offline` is set, so its patch \ + record was not fetched" + ); } /// A project-local copy the refresh could not fix says why and names diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index e429489d7..93f020012 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5546,6 +5546,131 @@ async fn gem_hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { } } +/// #2230 against a real Bundler: the project's `Gemfile` names a private +/// gem server as its source, so the lock (with `CHECKSUMS`) resolves the gem +/// from that remote, not rubygems.org. The unwind refuses to guess the +/// upstream sha256 and names `SOCKET_RUBYGEMS_URL`; with the setting naming +/// that server it reads the checksum from the server's compact index, hands +/// the pre-scan pair back byte for byte and puts the upstream gem back, so +/// `bundle install` and `bundle pristine` both pass on the restored lock. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (CHECKSUMS lock: >= 2.6); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_unwind_restores_a_gem_from_a_private_gem_server() { + let Some(fx) = redirect_scanned_project( + "mirror-unwind", + Spelling::Gemfile, + true, + true, + None, + Driver::ScanVex, + ) + .await + else { + return; + }; + let api = fx._server.uri(); + let upstream = format!("{api}/upstream"); + assert!( + String::from_utf8_lossy(&fx.pristine_lock).contains(&format!("remote: {upstream}/")), + "premise: the lock resolves the gem from the gem server" + ); + for command in ["rollback", "remove"] { + let dir = stage_fresh_checkout(&fx, &format!("mirror-{command}")); + let install = bundle(&dir, &["install"]); + assert!( + install.status.success(), + "{command}: hosted install:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb"); + assert_eq!( + std::fs::read(&installed).unwrap(), + fx.patched, + "{command}: the patched gem is installed (test premise)" + ); + let pair = || { + ( + std::fs::read(dir.join(fx.gemfile_name)).unwrap(), + std::fs::read(dir.join(fx.lock_name)).unwrap(), + ) + }; + let hosted = pair(); + + let cwd = dir.to_str().expect("utf8 tmp path"); + let mut argv = vec![command, PURL, "--json", "--cwd", cwd]; + if command == "remove" { + argv.push("--yes"); + } + argv.extend([ + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]); + // The registry setting names another server: refused, nothing + // changed, and the refusal names the setting that works. + let elsewhere = format!("{api}/elsewhere"); + let (code, stdout, stderr) = + run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &elsewhere)]); + assert_ne!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + format!("{stdout}{stderr}").contains(&format!("`SOCKET_RUBYGEMS_URL={upstream}`")), + "{command}: the refusal names the setting:\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + pair() == hosted, + "{command}: a refused unwind changes nothing" + ); + + let (code, stdout, stderr) = + run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); + let env: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| { + panic!("{command}: not JSON: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}") + }); + assert_eq!(code, 0, "{command}: {env}\nstderr:\n{stderr}"); + let (gemfile, lock) = pair(); + assert_eq!( + String::from_utf8_lossy(&gemfile), + String::from_utf8_lossy(&fx.pristine_gemfile), + "{command}: the Gemfile is the pre-scan one" + ); + assert_eq!( + String::from_utf8_lossy(&lock), + String::from_utf8_lossy(&fx.pristine_lock), + "{command}: the lock is the pre-scan one" + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: the installed gem is the upstream one again: {env}" + ); + assert!( + !env.to_string().contains("upstream_gem_stale_install"), + "{command}: {env}" + ); + // The restored project installs and reinstalls as it is. + for args in [&["install"][..], &["pristine"][..]] { + let run = bundle(&dir, args); + assert!( + run.status.success(), + "{command}: bundle {args:?} after the unwind:\n{}\n{}", + String::from_utf8_lossy(&run.stdout), + String::from_utf8_lossy(&run.stderr) + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: bundle {args:?} keeps the upstream bytes" + ); + } + } +} + /// A warm project: the pre-redirect pair installed from the mock upstream /// into the project's `vendor/bundle`, as on a developer machine or a CI /// job with a restored bundle cache. diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 51f6f58c3..5f1b07277 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3821,6 +3821,221 @@ async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { ); } +/// A project whose `Gemfile` names a private gem mirror as its source +/// (`source ""`), so the lock resolves the gem from that remote, +/// with the gem installed from it. `checksum` is the sha256 the lock's +/// `CHECKSUMS` section pins for the gem (Bundler 2.6 and later); `None` +/// writes a lock without the section. Returns the installed gem dir. +fn mirror_project(proj: &Path, mirror: &str, checksum: Option<&str>) -> PathBuf { + std::fs::create_dir_all(proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"{mirror}\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + let checksums = checksum + .map(|sha| format!("CHECKSUMS\n {DEP} ({DEP_VERSION}) sha256={sha}\n\n")) + .unwrap_or_default(); + std::fs::write( + proj.join("Gemfile.lock"), + format!( + "GEM\n remote: {mirror}/\n specs:\n {DEP} ({DEP_VERSION})\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})\n\n\ + {checksums}BUNDLED WITH\n 2.6.9\n" + ), + ) + .unwrap(); + install_real_gem(&project_home(proj), UPSTREAM_LIB) +} + +/// #2230: a hosted gem the lock resolves from a private mirror, under a +/// lock without `CHECKSUMS`. The unwind restores the pair, and nothing +/// gives the upstream gem's sha256, so the patched archive in the gem home +/// says nothing about the installed copy. The copy is judged by the pin's +/// patch record like one with no archive: the patched build the scan put +/// there is named with the files to remove (`bundle install` and `bundle +/// pristine` keep it otherwise), and offline it is named as a copy that +/// could not be checked. Neither is passed over in silence. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_patched_install_from_a_mirror_without_checksums() { + const MIRROR: &str = "https://gems.example.test"; + for (offline, needles) in [ + (false, ["its patched install at", "run `bundle install`"]), + ( + true, + [ + "could not be checked against the upstream gem", + "nothing gives the sha256 of its upstream gem and `--offline` is set, so its \ + patch record was not fetched", + ], + ), + ] { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let gem_dir = mirror_project(&proj, MIRROR, None); + // The project commits its bundler cache. + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{DEP}-{DEP_VERSION}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, real_gem(UPSTREAM_LIB)).unwrap(); + let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); + let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + let uri = server.uri(); + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); + let home = project_home(&proj); + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(pair("Gemfile"), gemfile, "offline={offline}"); + assert_eq!(pair("Gemfile.lock"), lock, "offline={offline}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let left = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); + for needle in needles.into_iter().chain([PURL, gem_dir.to_str().unwrap()]) { + assert!( + left[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + left[0] + ); + } + // The archive in Bundler's cache dir is named too, as one nothing + // could check: the registry is not asked about another remote's gem. + let cached = details_with_code(&env, "upstream_gem_stale_cache"); + assert_eq!(cached.len(), 1, "offline={offline}: {env}"); + assert!( + cached[0].contains(committed.to_str().unwrap()) + && cached[0].contains("could not be checked against the upstream sha256"), + "offline={offline}: {}", + cached[0] + ); + let asked_registry = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!( + !asked_registry, + "offline={offline}: rubygems.org is not asked about another remote's gem" + ); + } +} + +/// The record judges, it does not assume (#2230): an installed copy from a +/// private mirror that is still the upstream gem (the scan was told not to +/// refresh it) gets no warning after the unwind. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_leaves_an_upstream_install_from_a_mirror_alone() { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let gem_dir = mirror_project(&proj, "https://gems.example.test", None); + let uri = server.uri(); + let flags = ["--json", "--no-gem-install-refresh"]; + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &flags), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "premise"); + + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert!( + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{env}" + ); +} + +/// #2230: on a lock with `CHECKSUMS`, a hosted gem from a private mirror +/// can be unwound. The restore reads the gem's upstream sha256 from the +/// mirror's own compact index when `SOCKET_RUBYGEMS_URL` names that +/// server: the pair is the pre-scan pair byte for byte and the installed +/// copy is the upstream gem again. Without the setting the unwind refuses, +/// changes nothing and names the setting. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_restores_a_mirror_gem_when_the_registry_setting_names_the_mirror() { + for command in HOSTED_UNWINDS { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + // The mirror: the mock's `/upstream` tree. + serve_upstream_gem(&server, &upstream).await; + let uri = server.uri(); + let mirror = format!("{uri}/upstream"); + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let gem_dir = mirror_project(&proj, &mirror, Some(&sha256_of(&upstream))); + let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); + let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); + let (hosted_gemfile, hosted_lock) = (pair("Gemfile"), pair("Gemfile.lock")); + assert!(hosted_lock.contains("/patch-registry/"), "{hosted_lock}"); + + // rubygems.org (here: another stand-in) is not the lock's remote. + let mut args = command.to_vec(); + args.push("--json"); + let elsewhere = format!("{uri}/elsewhere"); + let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &elsewhere); + assert_ne!(code, 0, "{command:?}: {stdout}\n{stderr}"); + let said = format!("{stdout}\n{stderr}"); + for needle in [ + "is not rubygems.org", + &format!("`SOCKET_RUBYGEMS_URL={mirror}`"), + "git checkout -- Gemfile Gemfile.lock", + ] { + assert!( + said.contains(needle), + "{command:?}: missing {needle:?}: {said}" + ); + } + assert_eq!(pair("Gemfile"), hosted_gemfile, "{command:?}: refused"); + assert_eq!(pair("Gemfile.lock"), hosted_lock, "{command:?}: refused"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{command:?}: refused"); + + // The setting names the mirror: the remedy the refusal gave. + let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &mirror); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); + assert_eq!(pair("Gemfile"), gemfile, "{command:?}"); + assert_eq!(pair("Gemfile.lock"), lock, "{command:?}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{command:?}: the upstream gem is back: {env}" + ); + assert!( + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{command:?}: nothing is left on the patched build: {env}" + ); + } +} + /// The vendored half of the patch API for the fixture's patch: the grant /// names the patched `.gem` and the stub gemspec a path source loads, each /// with its sha512, beside the hosted registry override. Priority 1, so it diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs index bf20908f7..4579cfcfb 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -42,7 +42,9 @@ //! In every state a `CHECKSUMS` entry is re-pinned to the upstream sha256 //! from the rubygems.org compact index (`info/`, what bundler itself //! records; other upstream remotes are refused: their index may need -//! credentials and is not the default registry) — each platform build's +//! credentials and is not the default registry, unless `SOCKET_RUBYGEMS_URL` +//! names that very server, which then stands in for rubygems.org, #2230) +//! — each platform build's //! entry to that build's own sha256, the index's `-` //! line — and the `DEPENDENCIES` //! source pin (`name (…)!`) loses its `!` — unless the declaration sits @@ -1058,8 +1060,10 @@ fn lock_checksum(lock: &str, name: &str, token: &str) -> Option { /// fails every install against the restored upstream checksum (#1260). /// The upstream sha is the restored lock's `CHECKSUMS` entry, else the /// rubygems.org compact index (already fetched when the restore re-pinned -/// `CHECKSUMS`). Read-only, like scan's guard: the file is named, never -/// deleted. +/// `CHECKSUMS`) for a gem the lock resolves from rubygems.org +/// ([`rubygems_locked`]); the archive of a gem from another gem server +/// with no `CHECKSUMS` entry is named as one that could not be checked. +/// Read-only, like scan's guard: the file is named, never deleted. async fn stale_cache_warning( root: &std::path::Path, purl: &str, @@ -1076,6 +1080,14 @@ async fn stale_cache_warning( let got = crate::vendor::file_sha256_hex(&archive).await; let upstream = match lock.and_then(|l| lock_checksum(l, name, token)) { Some(sha) => Ok(sha), + // The registry is asked only about a gem that is its own: one the + // lock resolves from another gem server is not named to it, and + // its answer for a gem of that name would be another gem's (#2230). + None if lock.is_some_and(|l| !rubygems_locked(l, name, token)) => Err( + "the lock pins no CHECKSUMS sha256 for it and resolves it from a gem server \ + other than the gem registry" + .to_string(), + ), None => client.rubygems_sha256(name, token).await, }; let fix = "delete it, then run `bundle cache` to cache the upstream gem in its place \ @@ -1408,10 +1420,26 @@ async fn restore_one( LockEdit::Done(next) => next, LockEdit::NeedsSha { remote, tokens } => { let remote = remote.ok_or("its upstream GEM remote is ambiguous")?; - if !same_remote(&remote, RUBYGEMS_REMOTE) { + // rubygems.org, or the server `SOCKET_RUBYGEMS_URL` + // names in its place (a private mirror, #2230): the + // sha256 below is read from that one. + if !super::is_rubygems_remote(&remote) { + let server = crate::utils::redact::strip_url_userinfo(&remote); + let server = server.trim_end_matches('/'); + // The setting is refused for a server reached over + // plain http ([`super::rubygems_secure_base`]): it + // is no way out for that one. + let setting = match crate::utils::http::insecure_transport(server) { + Some(_) => String::new(), + None => format!( + " unless a re-run with `SOCKET_RUBYGEMS_URL={server}` names \ + that server as the gem registry (with its credentials in the \ + URL if it needs them)" + ), + }; return Err(format!( - "its upstream GEM remote {remote} is not rubygems.org, so its CHECKSUMS \ - sha256 cannot be re-derived" + "its upstream GEM remote {server} is not rubygems.org, so its CHECKSUMS \ + sha256 cannot be re-derived{setting}" )); } // One `info/` document lists every build. diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index 9bdc28d05..7feddd7e6 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -959,6 +959,39 @@ async fn gem_transitive_append_round_trips_unless_unprovable() { ); } +/// #2230: a project whose `source` names a private gem mirror locks its +/// gems under that remote. `SOCKET_RUBYGEMS_URL` set to the same server is +/// the registry's stand-in for the restore too, so the `CHECKSUMS` entry +/// is re-pinned from that server's compact index and the pair is the +/// pre-scan pair byte for byte. The lock names the server without the +/// credentials the setting may carry. +#[tokio::test] +#[serial] +async fn gem_mirror_named_by_socket_rubygems_url_round_trips() { + let gemfile = "source \"https://rubygems.org\"\n\ngem \"rails\", \"7.0.0\"\ngem \"puma\"\n"; + let case = synthetic( + "mirror-upstream", + &[("Gemfile", gemfile), ("Gemfile.lock", GEM_LOCK)], + gem_override("rails", "7.0.0"), + ); + let server = gem_mock(&case).await; + let mirror = server.uri(); + let mut case = case; + case.edit_both("Gemfile", |t| t.replace("https://rubygems.org", &mirror)); + case.edit_both("Gemfile.lock", |t| { + t.replace("https://rubygems.org/", &format!("{mirror}/")) + }); + for base in [ + mirror.clone(), + format!("{mirror}/"), + mirror.replace("http://", "http://user:token@"), + ] { + let _env = EnvGuard::set("SOCKET_RUBYGEMS_URL", &base); + let (after, statuses) = run_case(&case).await; + assert_round_trip(&case, &after, &statuses); + } +} + #[tokio::test] #[serial] async fn gem_refusals_leave_everything_hosted() { @@ -994,6 +1027,32 @@ async fn gem_refusals_leave_everything_hosted() { "Gemfile Gemfile.lock", "not rubygems.org", ); + // The refusal names the setting that reads such a server (#2230). + match &statuses[0].1 { + PinStatus::Refused(why) => assert!( + why.contains("SOCKET_RUBYGEMS_URL=https://gems.example.com"), + "{why}" + ), + other => panic!("expected a refusal, got {other:?}"), + } + // A server reached over plain http is one the setting refuses: the + // refusal does not name it as the way out. + let mut plain = foreign.clone_with("foreign-upstream-http"); + plain.edit_both("Gemfile.lock", |t| { + t.replace("https://gems.example.com/", "http://gems.example.com/") + }); + let (after, statuses) = gem_run(&plain).await; + assert_refused( + &plain, + &after, + &statuses, + "Gemfile Gemfile.lock", + "http://gems.example.com is not rubygems.org", + ); + match &statuses[0].1 { + PinStatus::Refused(why) => assert!(!why.contains("SOCKET_RUBYGEMS_URL"), "{why}"), + other => panic!("expected a refusal, got {other:?}"), + } // Two upstream sections, neither singled out. let mut ambiguous = case.clone_with("ambiguous-upstream"); ambiguous.edit_both("Gemfile.lock", |t| { diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..981034b3a 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3941,6 +3941,28 @@ that deletes it, `gem cleanup`): with no archive to compare, the installed files against the patch itself, in both directions. If the patch can't be looked up during a `rollback` or `remove`, the copy is left alone and the run warns (`upstream_gem_stale_install`), naming the files to remove before `bundle install`. + +A project whose `Gemfile` names a private gem server as its source (`source +"https://gems.example.com"`) locks its gems under that server, not rubygems.org. `rollback` and +`remove` do not ask a server they were not told about, so for such a gem: + +- On a lock with a `CHECKSUMS` section they need the upstream gem's sha256 to restore the lock, and + refuse until `SOCKET_RUBYGEMS_URL` names that server (its credentials go in the URL, and are + never printed): + + ```sh + SOCKET_RUBYGEMS_URL=https://gems.example.com socket-patch rollback pkg:gem/rack@3.1.8 + ``` + + The checksum is then read from the server's compact index (`info/`), the `Gemfile` and + lock come back byte for byte, and the installed copy is replaced with the upstream gem + downloaded from that server. +- On a lock without `CHECKSUMS` (Bundler 2.5 and older) the pair is restored without the setting. + Nothing then gives the upstream gem's sha256, so the installed copy is checked against the patch + itself: a copy that still holds the patched build is left as it is and named by + `upstream_gem_stale_install`, with the files to remove before `bundle install` (Bundler keeps + the copy otherwise). With the setting, the copy is replaced as above. + Vendoring a gem that was hosted (`vendor`, `scan --mode vendored`) leaves the installed copies as they are: Bundler loads the vendored copy from then on. When that vendored gem is later unwound (`rollback`, `remove`, `vendor --revert`), Bundler loads the installed copy again, so the unwind