diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 112eff958..74e5e02d1 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -456,11 +456,11 @@ 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 (ruby-platform gems only: the lock's checksum names that archive). 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. 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. +*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 (ruby-platform gems only: the lock's checksum names that archive). 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. *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. -*A vendored unwind after a hosted scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. @@ -926,7 +926,16 @@ one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep i network. Otherwise, and not under `--offline`, it is downloaded from the default registry, `https://rubygems.org` or the registry `SOCKET_RUBYGEMS_URL` names (a mirror), as `/gems/`, and used only when its sha256 is the one that registry's compact index -(`/info/`) records. Nothing in the project's lock chooses the URL or the hash: not +(`/info/`) records. The index vouches for the archive only when nobody on the +network path can rewrite both, and the archive's build scripts are about to run, so the registry +is asked over `https` only. Plain `http` is accepted for a loopback host (`localhost`, +`127.0.0.1`, `[::1]`: a local mirror; not a name under `.localhost`), and a request to one is +sent straight to it, never through `HTTP_PROXY` / `ALL_PROXY` (an `https` request keeps the +system proxy). A `SOCKET_RUBYGEMS_URL` that is neither is refused before any request with a +message that says to use an https URL, and a redirect that leaves `https`, or leads to an `http` +host that is not this machine, is not followed (ten redirects at most); the gem then has no +archive but a cached one, as offline. Credentials in the URL (`https://user:token@mirror`) are +sent and never printed. Nothing in the project's lock chooses the URL or the hash: not a `remote:`, not `CHECKSUMS`. The lock at the project root is read to withhold the download: a gem name that `Gemfile.lock` / `gems.locked` resolves from another source at any version (a `GEM` section with a remote that is not the registry, a private gem server or Socket's patch registry @@ -1034,10 +1043,10 @@ whose marker matches is `already_patched`; sources an earlier release patched wi with a `native_extension_rebuilt` warning. `rollback` (and `remove`) puts the backed-up build back with the sources, bytes and file mode; without a backup it rebuilds a gem RubyGems built from the restored sources, and fails a precompiled gem with `native_extension_restore_failed` (`gem -pristine ` reinstalls it). An in-place rebuild backs up and restores RubyGems' extension -directory and its `lib/` copies only: a library a gem builds into its own tree stays as last -built. Only the gem's own extension dir under its home, and files under the gem directory, are -ever replaced, whatever path the backup or marker names. +pristine ` reinstalls it). An in-place rebuild backs up and restores what it replaced in +the gem's own tree as well, and removes what it added there. Only the gem's own extension dir +under its home, and files under the gem directory, are ever replaced, whatever path the backup or +marker names. A build runs in a process group of its own: an interrupted `apply` (Ctrl-C, SIGTERM, SIGHUP) kills that group and waits for it before it releases the lock, so no compiler is left running. A build @@ -1960,7 +1969,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. | +| `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_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. | @@ -2242,7 +2251,7 @@ command's integration tests check its output. | `redirect_gem_stale_install` | `warnings[]` (warning) | scan / get `--mode hosted` (gem): a stale UNPATCHED materialization (installed gem, or committed archive in bundler's cache dir — `vendor/cache` unless `cache_path` moves it) that `bundle install` will reuse instead of fetching the redirected patch, and that the run did not refresh: it is in a shared gem home, or the refresh could not be done (the detail says why) or is turned off. The detail carries the remedy. A human run prints one warning for all of them. Full rules and flavors: the "Gem stale-install guard" section. | | `redirect_gem_install_refreshed` | `warnings[]` (note) | scan / get `--mode hosted` (gem): a stale materialization the run replaced with the sha256-verified patched gem (the detail names the purl and the path). A human run prints a progress line instead. See the "Gem stale-install guard" section. | | `redirect_gem_install_would_refresh` | `warnings[]` (note) | scan / get `--mode hosted --dry-run` (gem): a stale materialization a wet run would replace. Nothing was written or downloaded. | -| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. The detail carries the remedy; a human run prints one warning for all of them. | +| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. Also: the copy could not be checked against the upstream gem, because the registry that would say what that is was refused (plain-http `SOCKET_RUBYGEMS_URL`); it still holds the patched build if it was installed before the unwind. The detail carries the reason and the remedy; a human run prints one warning for all of them. | | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 2bbaa3f5c..3a46fe529 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -176,6 +176,10 @@ pub(crate) enum Why { Disabled, /// The refresh was tried, or could not be. Failed(String), + /// Nothing says which build the copy holds: the sha256 of the wanted + /// gem could not be had, for this reason. It is not known to be stale, + /// and not known not to be. + Unverified(String), } /// What one refresh pass did. @@ -399,7 +403,7 @@ fn after_hint(hint: &str, action: &str) -> String { fn reason(why: Option<&Why>) -> String { match why { - Some(Why::Failed(reason)) => format!(" ({reason})"), + Some(Why::Failed(reason) | Why::Unverified(reason)) => format!(" ({reason})"), Some(Why::Disabled) => " (`--no-gem-install-refresh` is set)".to_string(), _ => String::new(), } @@ -442,6 +446,20 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh }; } match &gem.installed { + Some((dir, _)) if matches!(why, Some(Why::Unverified(_))) => format!( + "{purl} {switched}, but its install at {} could not be checked against the \ + {wanted} gem{}. If it was installed before the switch it still holds the {stale} \ + build, and {reuse}. {}", + dir.display(), + reason(why), + after_hint( + "", + &format!( + "remove {} and run `bundle install`", + display_list(&files_to_remove(gem)) + ) + ), + ), Some((dir, false)) if !matches!(why, Some(Why::Disabled | Why::Failed(_))) => format!( "{purl} {switched}, but the shared gem home still holds its {stale} install at \ {}, and {reuse}. Other projects may load that gem home, so it was left alone. \ @@ -637,14 +655,26 @@ pub(crate) fn report( _ => local.entry(why).or_default().push(gem), } } + // A gem whose copy could not be checked is not known to be stale: it + // is counted apart from the ones that are. + let unchecked: BTreeSet<&str> = local + .iter() + .filter(|(why, _)| matches!(why, Why::Unverified(_))) + .flat_map(|(_, gems)| gems.iter().map(|gem| gem.purl.as_str())) + .collect(); let count = stale .iter() .map(|gem| gem.purl.as_str()) + .filter(|purl| !unchecked.contains(purl)) .collect::>() .len(); - let headline = match direction { + let switch = match direction { + Direction::Patched => "the switch to hosted patches", + Direction::Upstream => "the switch back to the upstream registry", + }; + let known = match direction { Direction::Patched if stale.iter().all(|gem| gem.in_place) => format!( - "{} on disk after the switch to hosted patches", + "{} on disk after {switch}", plural( count, "gem patched in place still has its upstream archive", @@ -652,18 +682,29 @@ pub(crate) fn report( ) ), Direction::Patched if stale.iter().any(|gem| gem.in_place) => format!( - "{} unpatched files or archives on disk after the switch to hosted patches", + "{} unpatched files or archives on disk after {switch}", plural(count, "gem still has", "gems still have") ), Direction::Patched => format!( - "{} still unpatched on disk after the switch to hosted patches", + "{} still unpatched on disk after {switch}", plural(count, "gem is", "gems are") ), Direction::Upstream => format!( - "{} the patched build on disk after the switch back to the upstream registry", + "{} the patched build on disk after {switch}", plural(count, "gem still holds", "gems still hold") ), }; + let headline = match (count, unchecked.len()) { + (_, 0) => known, + (0, n) => format!( + "{} on disk could not be checked after {switch}", + plural(n, "gem", "gems") + ), + (_, n) => format!( + "{known}, and {} could not be checked", + plural(n, "gem", "gems") + ), + }; let mut bullets = Vec::new(); let shared_gems: usize = shared.values().map(Vec::len).sum(); for (home, purls) in &shared { @@ -700,15 +741,20 @@ pub(crate) fn report( for (why, gems) in &local { let files: Vec = gems.iter().flat_map(|gem| files_to_remove(gem)).collect(); let files: Vec = files.iter().map(|p| p.display().to_string()).collect(); - bullets.push(format!( - "Not refreshed{}: {}. {}.", - reason(Some(why)), - labels(gems.iter().map(|gem| gem.purl.as_str())), - after_hint( - retry_hint(direction, Some(why)), - &format!("run `rm -f {} && bundle install`", files.join(" ")) + let reinstall = format!("run `rm -f {} && bundle install`", files.join(" ")); + let names = labels(gems.iter().map(|gem| gem.purl.as_str())); + bullets.push(match why { + Why::Unverified(_) => format!( + "Not checked against the {wanted} gem{}: {names}. A copy installed before \ + the switch still holds the {stale_word} build; to be sure, {reinstall}.", + reason(Some(why)), ), - )); + _ => format!( + "Not refreshed{}: {names}. {}.", + reason(Some(why)), + after_hint(retry_hint(direction, Some(why)), &reinstall), + ), + }); } out.summary = Some(Summary { headline, bullets }); out @@ -782,10 +828,12 @@ enum Scope { /// archive RubyGems installed it from, `/cache/.gem`, is /// readable and is not the upstream one, and so is (in [`Scope::All`]) /// such an archive in Bundler's cache dir. `upstream` is each purl's -/// upstream sha256; a purl without one is not judged. +/// upstream sha256; a purl without an entry is not judged. A purl whose +/// sha256 is `None` (the registry that would give it was refused) cannot +/// be judged either, and every installed copy of it is listed. async fn stale_after_restore( common: &GlobalArgs, - upstream: &BTreeMap, + upstream: &BTreeMap>, scope: Scope, ) -> Vec { use socket_patch_core::vendor::file_sha256_hex; @@ -796,23 +844,38 @@ async fn stale_after_restore( let Some(sha) = upstream.get(©.purl) else { continue; }; - match file_sha256_hex(©.archive).await { - Some(got) if &got != sha => out.push(StaleGem { + // With no upstream sha256 (the registry that would give it was + // refused) nothing can be judged, so the copy is listed whether + // or not its archive is still in the home's cache. With one, + // only a readable archive that is not the upstream gem makes + // the copy stale. + let listed = match sha { + None => true, + Some(sha) => { + matches!(file_sha256_hex(©.archive).await, Some(got) if &got != sha) + } + }; + if listed { + out.push(StaleGem { purl: copy.purl, leaf: copy.leaf, installed: Some((copy.dir, copy.project_local)), cache_archive: None, in_place: false, - }), - _ => {} + }); } } if scope == Scope::Installed { return out; } + // (An archive in Bundler's cache dir that cannot be checked is the + // restore's own `upstream_gem_stale_cache` to name.) let app_cache = socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(&common.cwd).await; for (purl, sha) in upstream { + let Some(sha) = sha else { + continue; + }; let Some((_, name, version)) = socket_patch_core::utils::purl::purl_parts(purl) else { continue; }; @@ -893,60 +956,75 @@ async fn refresh_restored( staged: &BTreeMap>, scope: Scope, ) -> RestoreRefresh { - use socket_patch_core::patch::redirect::upstream::gem_upstream_archive; + use socket_patch_core::patch::redirect::upstream::{gem_upstream_archive, UpstreamArchive}; + use socket_patch_core::vendor::registry_fetch::SecureRegistryClient; let policy = Policy::of(common); let direction = Direction::Upstream; - let mut shas: BTreeMap = BTreeMap::new(); + let mut shas: BTreeMap> = BTreeMap::new(); let mut urls: BTreeMap> = BTreeMap::new(); + // The gems whose upstream sha256 the registry is not asked for, each + // with why: their installed copies are reported, not passed over. + let mut unverified: BTreeMap = BTreeMap::new(); for purl in restored .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) { - if let Some((sha, url)) = - gem_upstream_archive(&common.cwd, staged, purl, common.offline).await - { - // A vendored revert does not prove where the lock resolves the - // gem from: an entry vendored over hosted wiring before v5 - // reverts to its hosted pin, whose `CHECKSUMS` sha256 is the - // patched gem's (the hosted unwind restores that pin next, and - // refreshes then). Only a gem the lock resolves from - // rubygems.org is known to be back on its upstream entry. - if scope == Scope::Installed && url.is_none() { - continue; + match gem_upstream_archive(&common.cwd, staged, purl, common.offline).await { + Some(UpstreamArchive::Known { sha256, url }) => { + // A vendored revert does not prove where the lock resolves + // the gem from: an entry vendored over hosted wiring before + // v5 reverts to its hosted pin, whose `CHECKSUMS` sha256 is + // the patched gem's (the hosted unwind restores that pin + // next, and refreshes then). Only a gem the lock resolves + // from rubygems.org is known to be back on its upstream + // entry. + if scope == Scope::Installed && url.is_none() { + continue; + } + shas.insert(purl.clone(), Some(sha256)); + urls.insert(purl.clone(), url); + } + // (Only a gem the lock resolves from rubygems.org comes back + // unverified, so the vendored unwind's rule holds for it too.) + Some(UpstreamArchive::Unverified(why)) => { + unverified.insert(purl.clone(), why); } - shas.insert(purl.clone(), sha); - urls.insert(purl.clone(), url); + None => {} } } - if shas.is_empty() { + if shas.is_empty() && unverified.is_empty() { return RestoreRefresh::default(); } let stale = stale_after_restore(common, &shas, scope).await; - if stale.is_empty() { + let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); + let unchecked = stale_after_restore(common, &unjudged, Scope::Installed).await; + if stale.is_empty() && unchecked.is_empty() { return RestoreRefresh::default(); } let wanted = |gem: &StaleGem| { Some(Wanted { leaf: gem.leaf.clone(), kind: direction.wanted(), - sha256: BTreeSet::from([shas.get(&gem.purl)?.clone()]), + sha256: BTreeSet::from([shas.get(&gem.purl)?.clone()?]), urls: urls.get(&gem.purl)?.iter().cloned().collect(), on_disk: Vec::new(), }) }; - let source = if common.offline { - Source::DiskOnly - } else { - Source::Registry + // One client for the run's downloads, when there is something to + // download. + let registry = (!common.offline && !stale.is_empty()).then(SecureRegistryClient::new); + let source = match ®istry { + Some(registry) => Source::Registry(registry), + None => Source::DiskOnly, }; - let pass = attempt(&stale, wanted, &source, &policy, direction).await; + let mut pass = attempt(&stale, wanted, &source, &policy, direction).await; let still = if pass.changed(&policy) { stale_after_restore(common, &shas, scope).await } else { stale }; - let installed: Vec = still + let mut installed: Vec = still .into_iter() .filter(|gem| gem.installed.is_some()) .collect(); @@ -958,6 +1036,13 @@ async fn refresh_restored( }) .map(|(purl, _)| purl.clone()) .collect(); + for gem in unchecked { + if let (Some((dir, _)), Some(why)) = (&gem.installed, unverified.get(&gem.purl)) { + pass.left + .insert(dir.clone(), Why::Unverified(why.to_string())); + installed.push(gem); + } + } RestoreRefresh { refreshed_installs, report: report(direction, &installed, &pass, &policy), @@ -1068,6 +1153,95 @@ mod tests { assert!(fixed < 480, "the whole warning stays short: {fixed}"); } + /// A copy that could not be checked against the upstream gem (the + /// registry that would say is refused) is reported with the reason and + /// the files to remove, apart from the copies known to be stale: it is + /// not said to hold the patched build, and it is not passed over. In a + /// shared gem home too, where nothing was tried either way. + #[tokio::test] + async fn a_copy_that_could_not_be_checked_is_reported_with_the_reason() { + const WHY: &str = "SOCKET_RUBYGEMS_URL is not used as the gem registry: \ + `http://gemstash:9292` is not an https URL; set it to an https URL"; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); + let shared = tmp.path().join("elsewhere/gemhome"); + let unchecked = [ + installed("rack", &home, true), + installed("rexml", &shared, false), + ]; + let stale = installed("nokogiri", &home, true); + let policy = policy(tmp.path(), true, false, false); + let mut pass = attempt( + std::slice::from_ref(&stale), + unobtainable, + &Source::DiskOnly, + &policy, + Direction::Upstream, + ) + .await; + for gem in &unchecked { + let (dir, _) = gem.installed.clone().unwrap(); + pass.left.insert(dir, Why::Unverified(WHY.to_string())); + } + + // Unchecked copies alone. + let out = report(Direction::Upstream, &unchecked, &pass, &policy); + assert_eq!(out.warnings.len(), 2); + for ((code, detail), gem) in out.warnings.iter().zip(&unchecked) { + let (dir, _) = gem.installed.clone().unwrap(); + assert_eq!(*code, "upstream_gem_stale_install"); + for needle in [ + gem.purl.as_str(), + "is back on its upstream registry entry", + "could not be checked against the upstream gem", + WHY, + "If it was installed before the switch it still holds the patched build", + "run `bundle install`", + &dir.display().to_string(), + &format!("{}.gemspec", gem.leaf), + ] { + assert!(detail.contains(needle), "missing {needle:?}: {detail}"); + } + assert!(!detail.contains("--gem-refresh-shared"), "{detail}"); + assert!(!detail.contains("its patched install"), "{detail}"); + } + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "2 gems on disk could not be checked after the switch back to the upstream registry" + ); + assert_eq!(summary.bullets.len(), 1, "{:?}", summary.bullets); + assert!( + summary.bullets[0].starts_with(&format!( + "Not checked against the upstream gem ({WHY}): rack 1.0.0, rexml 1.0.0. A copy \ + installed before the switch still holds the patched build; to be sure, run \ + `rm -f " + )), + "{}", + summary.bullets[0] + ); + + // Beside a copy that is known to be stale. + let all = [vec![stale], unchecked.to_vec()].concat(); + let out = report(Direction::Upstream, &all, &pass, &policy); + assert_eq!(out.warnings.len(), 3); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds the patched build on disk after the switch back to the upstream \ + registry, and 2 gems could not be checked" + ); + assert_eq!(summary.bullets.len(), 2, "{:?}", summary.bullets); + + // A dry run switched nothing: nothing is stale or unchecked yet. + let dry = Policy { + dry_run: true, + ..policy + }; + let out = report(Direction::Upstream, &all, &pass, &dry); + assert!(out.summary.is_none()); + } + /// A project-local copy the refresh could not fix says why and names /// the two files whose removal makes Bundler fetch the gem. #[tokio::test] diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index b2cb9acd2..c65adf6b7 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -1699,6 +1699,41 @@ fn a_precompiled_copy_without_its_source_gem_is_refused() { assert_eq!(ruby.calls(), ["extensions_dir"]); assert_tree(&proj.join("vendor"), &tree_before, ""); + // Online, with a registry reached over plain http that is not this + // machine: whoever sits on the path would choose the archive and the + // checksum it is verified against, and the archive's build scripts + // would run. It is not asked, in a dry run either, and the refusal + // says to use https. + let ruby = FakeRuby::new(); + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = ruby.run( + &proj, + args, + &[("SOCKET_RUBYGEMS_URL", "http://gems.example.test/mirror")], + ); + assert_eq!(code, 1, "{args:?}: {stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let error = common::envelope::event_for(&env, PURL)["error"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + error.starts_with("native_extensions_unsupported:"), + "{args:?}: {stdout}" + ); + for needle in [ + "sp_native-1.0.0.gem", + "SOCKET_RUBYGEMS_URL", + "`http://gems.example.test/mirror` is not an https URL", + "set it to an https URL", + "nothing was written", + ] { + assert!(error.contains(needle), "{args:?}: no {needle:?} in {error}"); + } + assert_eq!(ruby.calls(), Vec::::new(), "{args:?}: Ruby ran"); + assert_tree(&proj.join("vendor"), &tree_before, &format!("{args:?}")); + } + // Online, for a gem the lock resolves from another source: the // registry's gem of that name is not this gem, and the lock's remote // is not a place the run downloads from. Nothing is asked of anyone. @@ -1857,7 +1892,8 @@ fn a_failed_staged_build_changes_nothing() { /// rebuild it had before there was a stage: from its own tree, in place. /// The cached archive not being its own source (a patched archive a hosted /// install left there), a record that does not apply to it, a stage that -/// cannot be opened, a build that fails in the stage. +/// cannot be opened, a build that fails in the stage, no cached archive +/// and a registry that is not asked because it is reached over plain http. #[cfg(unix)] #[test] fn a_built_gem_falls_back_to_its_own_tree() { @@ -1866,6 +1902,7 @@ fn a_built_gem_falls_back_to_its_own_tree() { "record does not apply", "no stage", "staged build fails", + "registry over plain http", ] { let (_tmp, proj, gem_dir) = fake_native_gem(true); let home = proj.join("vendor/bundle/ruby/3.4.0"); @@ -1895,6 +1932,10 @@ fn a_built_gem_falls_back_to_its_own_tree() { std::fs::write(home.join(".socket-patch-build"), b"").unwrap(); staged_steps.clear(); } + "registry over plain http" => { + std::fs::remove_file(home.join("cache/sp_native-1.0.0.gem")).unwrap(); + staged_steps.clear(); + } _ => { ruby.fail_staged_builds(); staged_steps.extend(["missing_deps", "stage_build"]); @@ -1902,7 +1943,17 @@ fn a_built_gem_falls_back_to_its_own_tree() { } write_record(&proj.join(".socket"), PURL, &record); - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + // Online for the registry case: nothing is asked of a registry + // that is neither https nor this machine. + let (args, env): (&[&str], &[(&str, &str)]) = if case == "registry over plain http" { + ( + &["apply", "--json"], + &[("SOCKET_RUBYGEMS_URL", "http://gems.example.test/mirror")], + ) + } else { + (&["apply", "--json", "--offline"], &[]) + }; + let (code, stdout, stderr) = ruby.run(&proj, args, env); if case == "record does not apply" { // The record changes a file the copy does not hold: only the // source gem could have vouched for it, so there is nothing to @@ -2807,6 +2858,12 @@ async fn a_precompiled_gem_is_rebuilt_from_its_source_gem_and_grafted() { /// hold it, is downloaded from the registry and used only when it has the /// sha256 the registry's compact index records for the ruby-platform gem. /// (The stand-in Ruby builds; the download and its check are the CLI's.) +/// +/// The registry here is on this machine, reached over plain http, which is +/// taken only because such a request crosses no network. So it is sent +/// straight there: with `HTTP_PROXY` / `ALL_PROXY` set and no `NO_PROXY`, +/// nothing of it goes to the proxy, which would carry it in clear text to +/// another host. #[cfg(unix)] #[tokio::test(flavor = "multi_thread")] async fn the_source_gem_is_downloaded_and_checked_against_the_registry_index() { @@ -2820,6 +2877,9 @@ async fn the_source_gem_is_downloaded_and_checked_against_the_registry_index() { (common::sha256_hex(b"another archive"), false), ] { let server = MockServer::start().await; + // A proxy that answers nothing (404): a request sent through it + // fails, and is counted. + let proxy = MockServer::start().await; // The platform gem's line comes first: it is not the source gem's. let info = format!( "---\n1.0.0-x86_64-linux |checksum:{}\n1.0.0 |checksum:{indexed}\n", @@ -2845,10 +2905,31 @@ async fn the_source_gem_is_downloaded_and_checked_against_the_registry_index() { let home = proj.join("vendor/bundle/ruby/3.4.0"); let tree_before = walk_files(&proj.join("vendor")); + let proxied = proxy.uri(); let (code, stdout, stderr) = ruby.run( &proj, &["apply", "--json"], - &[("SOCKET_RUBYGEMS_URL", registry.as_str())], + &[ + ("SOCKET_RUBYGEMS_URL", registry.as_str()), + ("HTTP_PROXY", proxied.as_str()), + ("http_proxy", proxied.as_str()), + ("ALL_PROXY", proxied.as_str()), + ("all_proxy", proxied.as_str()), + ("NO_PROXY", ""), + ("no_proxy", ""), + ], + ); + let through_proxy: Vec = proxy + .received_requests() + .await + .unwrap() + .iter() + .map(|request| request.url.to_string()) + .collect(); + assert_eq!( + through_proxy, + Vec::::new(), + "a loopback request went through the proxy" ); let asked: Vec = server .received_requests() 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 27f85cf10..f15166818 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 @@ -2562,6 +2562,107 @@ async fn refresh_after_rollback_restores_the_upstream_gem() { ); } +/// A registry that is refused (plain http, and not this machine) is not +/// asked what the upstream gem is. `rollback` still puts the lock back, +/// leaves the installed copy as it is, and says so: the copy is reported as +/// one it could not check, with the reason, not passed over in silence +/// while it still holds the patched build. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_reports_the_copy_a_refused_registry_left_unchecked() { + refused_registry_leaves_the_copy_reported(true).await; +} + +/// The same with the copy's archive gone from the home's cache (a pruned +/// `cache/`, as slim images have). With nothing to judge the copy by it is +/// still reported, not passed over. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_reports_an_unchecked_copy_whose_cached_archive_is_gone() { + refused_registry_leaves_the_copy_reported(false).await; +} + +async fn refused_registry_leaves_the_copy_reported(cached_archive: bool) { + 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"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let cache = home.join("cache").join(format!("{leaf}.gem")); + + 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, "scan refreshed it"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let asked_before = server.received_requests().await.unwrap().len(); + if !cached_archive { + std::fs::remove_file(&cache).unwrap(); + } + + // Refused before any request: nothing is looked up or sent. + const REFUSED: &str = "http://gemstash.example.test:9292"; + let args = [ + "rollback", + PURL, + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + "--json", + ]; + let (code, stdout, stderr) = + common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", REFUSED)]); + 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}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + !lock.contains("/patch-registry/"), + "the lock is back on upstream:\n{lock}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "left as it is"); + if cached_archive { + assert_eq!(std::fs::read(&cache).unwrap(), patched); + } + assert!( + warnings_with_code(&env, "upstream_gem_install_refreshed").is_empty(), + "{env}" + ); + let unchecked = warnings_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); + for needle in [ + PURL, + "could not be checked against the upstream gem", + "`http://gemstash.example.test:9292` is not an https URL", + "set it to an https URL", + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + ] { + assert!( + unchecked[0].contains(needle), + "missing {needle:?}: {}", + unchecked[0] + ); + } + assert_eq!( + server.received_requests().await.unwrap().len(), + asked_before, + "the rollback asked a registry" + ); +} + /// 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 @@ -2822,7 +2923,16 @@ async fn hosted_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, Pat /// Run `args` in `proj` against the mock API, with rubygems.org's stand-in. fn unwind_run(proj: &Path, uri: &str, args: &[&str]) -> (i32, String, String) { - let rubygems = format!("{uri}/upstream"); + unwind_run_with_registry(proj, uri, args, &format!("{uri}/upstream")) +} + +/// [`unwind_run`], with `rubygems` as the gem registry (`SOCKET_RUBYGEMS_URL`). +fn unwind_run_with_registry( + proj: &Path, + uri: &str, + args: &[&str], + rubygems: &str, +) -> (i32, String, String) { let mut args = args.to_vec(); args.extend([ "--cwd", @@ -2836,7 +2946,7 @@ fn unwind_run(proj: &Path, uri: &str, args: &[&str]) -> (i32, String, String) { "--patch-server-url", uri, ]); - common::run_with_env(proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) + common::run_with_env(proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems)]) } /// The commands that unwind a vendored gem. @@ -3027,6 +3137,65 @@ async fn vendored_unwind_warns_once_in_a_human_run() { } } +/// A registry that is refused (plain http, and not this machine) is not +/// asked what the upstream gem is, in a vendored unwind as in a hosted one: +/// the installed copy is left exactly as it was and reported as one that +/// could not be checked, with the reason, not passed over while it still +/// holds the patched build. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_reports_the_copy_a_refused_registry_left_unchecked() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = hosted_then_vendored(&server, &proj).await; + let home = project_home(&proj); + let held_before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + // Refused before any request: nothing is looked up or sent. + let (code, stdout, stderr) = unwind_run_with_registry( + &proj, + &server.uri(), + &args, + "http://gemstash.example.test:9292", + ); + let env = common::parse_json_envelope(&stdout); + let case = format!("{unwind:?}"); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + let text = env.to_string(); + for needle in [ + "upstream_gem_stale_install", + "could not be checked against the upstream gem", + "`http://gemstash.example.test:9292` is not an https URL", + "set it to an https URL", + gem_dir.to_str().unwrap(), + ] { + // The envelope JSON-escapes a Windows path's backslashes. + let needle = needle.replace('\\', "\\\\"); + assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); + } + assert!( + !text.contains("upstream_gem_install_refreshed"), + "{case}: {env}" + ); + let upstream_asked = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!(!upstream_asked, "{case}: the unwind asked a registry"); + } +} + /// A gem that was only ever vendored still has the upstream build /// installed: its unwind changes nothing in the gem home, downloads no /// gem and raises nothing about it. diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 72c3874b9..77d855627 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -204,6 +204,7 @@ use crate::patch::apply::{ }; use crate::patch::file_hash::compute_file_git_sha256_sync; use crate::patch::gem_source::{GemId, GemSource, RubyVersions}; +use crate::utils::containment::{ensure_dir_or_absent, try_entry_type}; use crate::utils::fs::read_regular_to_bytes_sync; /// The refusal when a native-extension patch cannot be rebuilt here (the @@ -936,8 +937,38 @@ fn is_confined_ext_label(full_name: &str, label: &str) -> bool { && is_safe_relative_subpath(label) } -fn is_symlink(path: &Path) -> bool { - std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) +/// `Err` when `path` is a symlink, and when nothing says it is not one: +/// only "not found" reads as no link, and a path that cannot be probed +/// (permission denied, a parent that is no directory, an I/O error) is +/// refused like a link ([`try_entry_type`]). For a path this module is +/// about to follow, empty or delete; `what` is what belongs there ("an +/// extension dir"). The error names the path. +fn refuse_link(path: &Path, what: &str) -> std::io::Result<()> { + match try_entry_type(path)? { + Some(kind) if kind.is_symlink() => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} is a symlink, not {what}", path.display()), + )), + _ => Ok(()), + } +} + +/// [`read_marker_sync`] for a caller that must not take a marker it cannot +/// read for no marker (a rollback deciding whether the compiled code is the +/// gem's own): `Ok(None)` only when no marker file is there. One that +/// cannot be probed, read or understood (another schema) is an error +/// naming it. +fn read_marker_strict(gem_dir: &Path) -> std::io::Result> { + let path = gem_dir.join(MARKER_FILE); + if try_entry_type(&path)?.is_none() { + return Ok(None); + } + read_marker_sync(gem_dir).map(Some).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} could not be read as a build marker", path.display()), + ) + }) } fn read_marker_sync(gem_dir: &Path) -> Option { @@ -1608,20 +1639,21 @@ fn recover_interrupted_rebuild_sync( Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, Err(e) => return Err(e), }; - if is_symlink(&ext) { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("{} is a symlink, not an extension dir", ext.display()), - )); - } + refuse_link(&ext, "an extension dir")?; // An in-place build was under way: the gem's own tree goes back to // what it was before it ([`TreeSnapshot`]), whichever way the // extension dir is settled, since no marker speaks for what the // build left there. Unless one does: a run that died after it // recorded the build, before it dropped the parked one, left a // finished build that stands with its tree. + // + // Whether there is a snapshot is not guessed: one that cannot be + // probed may be all that says the tree holds a half-made build, and + // settling the extension dir without it would leave that build in + // the tree with nothing to undo it from. let snapshot = tree_snapshot_path(&ext); - let in_place = is_real_dir(&snapshot) && !build_committed_since(copy, &ext, &snapshot); + let taken = try_entry_type(&snapshot)?.is_some_and(|kind| kind.is_dir()); + let in_place = taken && !build_committed_since(copy, &ext, &snapshot)?; if in_place { restore_tree(copy, &snapshot)?; } @@ -2191,11 +2223,13 @@ fn ext_dir_label(home: &Path, ext_dir: &Path) -> String { /// list. `Ok(true)` when this call made the backup. fn back_up_original(copy: &GemCopy, probe: &Probe, absent: &[String]) -> std::io::Result { let backup = copy.gem_dir.join(BACKUP_DIR); - if std::fs::symlink_metadata(&backup).is_ok() { + // "Not there" is the one answer a new backup is made on: a backup or a + // marker that cannot be probed may hold the original build already. + if try_entry_type(&backup)?.is_some() { note_absent_files(&backup, absent)?; return Ok(false); } - if std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { + if try_entry_type(©.gem_dir.join(MARKER_FILE))?.is_some() { return Ok(false); } let stage = copy.gem_dir.join(format!("{BACKUP_DIR}.tmp")); @@ -2240,8 +2274,33 @@ fn back_up_original(copy: &GemCopy, probe: &Probe, absent: &[String]) -> std::io /// The description of the backup dir `backup`, when it has a readable one. fn read_backup_info(backup: &Path) -> Option { - let bytes = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()?; - serde_json::from_slice(&bytes).ok() + try_read_backup_info(backup).ok().flatten() +} + +/// [`read_backup_info`] for a caller that is about to add to the backup, +/// and must not take a description it cannot read for none: `Ok(None)` +/// only when the backup has no description file. One that cannot be +/// probed, read or parsed is an error naming it. (A rollback removes what +/// the marker lists and the backup does not hold: a build recorded in the +/// marker and not in a backup that is there would lose its files to it.) +fn try_read_backup_info(backup: &Path) -> std::io::Result> { + let path = backup.join(BACKUP_INFO); + if try_entry_type(&path)?.is_none() { + return Ok(None); + } + let unreadable = |why: String| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "{} could not be read as a backup's description ({why})", + path.display() + ), + ) + }; + let bytes = read_regular_to_bytes_sync(&path).map_err(|e| unreadable(e.to_string()))?; + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|e| unreadable(e.to_string())) } /// Write a backup's description into `dir`: staged beside its place and @@ -2262,7 +2321,7 @@ fn note_absent_files(backup: &Path, absent: &[String]) -> std::io::Result<()> { if absent.is_empty() || !is_real_dir(backup) { return Ok(()); } - let Some(mut info) = read_backup_info(backup) else { + let Some(mut info) = try_read_backup_info(backup)? else { return Ok(()); }; let before = info.absent_files.len(); @@ -2443,6 +2502,50 @@ fn gem_tree_files(gem_dir: &Path) -> Vec { .collect() } +/// [`tree_files`] for a caller that acts on what the listing lacks (a file +/// that is not in a snapshot is removed; one that was not snapshotted +/// cannot be put back): `Err`, naming the tree, when any part of it cannot +/// be read, where `tree_files` leaves that part out. Only a `dir` that is +/// not there has no files. +fn try_tree_files(dir: &Path) -> std::io::Result> { + if try_entry_type(dir)?.is_none() { + return Ok(Vec::new()); + } + let mut files = Vec::new(); + for entry in walkdir::WalkDir::new(dir) + .follow_links(false) + .sort_by_file_name() + { + let entry = entry.map_err(|e| { + let kind = e + .io_error() + .map_or(std::io::ErrorKind::Other, std::io::Error::kind); + std::io::Error::new(kind, format!("{} could not be listed ({e})", dir.display())) + })?; + if !entry.file_type().is_file() { + continue; + } + if let Ok(rel) = entry.path().strip_prefix(dir) { + files.push( + rel.components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"), + ); + } + } + Ok(files) +} + +/// [`gem_tree_files`], failing where it would leave part of the tree out +/// ([`try_tree_files`]). +fn try_gem_tree_files(gem_dir: &Path) -> std::io::Result> { + Ok(try_tree_files(gem_dir)? + .into_iter() + .filter(|rel| !is_own_entry(rel)) + .collect()) +} + /// The gem's own tree as it was before an in-place build: a copy of every /// file, beside the parked build ([`tree_snapshot_path`]). /// @@ -2507,7 +2610,9 @@ fn snapshot_tree(copy: &GemCopy, ext: &Path, left: &[String]) -> std::io::Result std::fs::create_dir_all(&stage)?; let taken = (|| { let mut files = BTreeMap::new(); - for rel in gem_tree_files(©.gem_dir) { + // The whole tree, or no snapshot: a file that is not in it is one + // the undo of a failed build removes. + for rel in try_gem_tree_files(©.gem_dir)? { if left.contains(&rel) { continue; } @@ -2564,15 +2669,39 @@ fn tree_changes(copy: &GemCopy, snapshot: &TreeSnapshot) -> TreeChanges { /// back (through [`replace_file`]), and the snapshot is dropped. A file /// that is as it was is not written, and the paths the snapshot left out /// are not touched. A snapshot that does not say which those are is not -/// used: `Err`, with the tree as it is. +/// used: `Err`, with the tree as it is. Neither is one whose copies cannot +/// all be listed, nor is a tree that cannot be: every file the listing of +/// the snapshot lacks is removed, so a listing that left some out would +/// delete the gem's own files ([`try_tree_files`]). Nor is one that names a +/// file under a link in the gem dir, which would be written through it. fn restore_tree(copy: &GemCopy, snapshot_dir: &Path) -> std::io::Result<()> { let left: Vec = serde_json::from_slice(&read_regular_to_bytes_sync( &snapshot_dir.join(SNAPSHOT_LEFT), )?) .map_err(std::io::Error::other)?; let saved_tree = snapshot_dir.join(SNAPSHOT_TREE); - let kept: std::collections::BTreeSet = tree_files(&saved_tree).into_iter().collect(); - for rel in gem_tree_files(©.gem_dir) { + let kept: std::collections::BTreeSet = + try_tree_files(&saved_tree)?.into_iter().collect(); + // Each file goes back by path. A snapshot this module took holds no + // file under a link (links are not walked when it is taken), so one + // that names such a path was not taken of this tree: a gem home can + // come from the repository being scanned, with a snapshot planted + // beside a parked build and a link in the gem dir to write through. + // Checked for every file before any is removed or written. + for rel in &kept { + let path = copy.gem_dir.join(rel); + if let Some(link) = crate::utils::containment::try_linked_level(©.gem_dir, &path)? { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "{} is a symlink, and the snapshot at {} names {rel} under it", + link.display(), + snapshot_dir.display() + ), + )); + } + } + for rel in try_gem_tree_files(©.gem_dir)? { if !kept.contains(&rel) && !left.contains(&rel) { std::fs::remove_file(copy.gem_dir.join(&rel))?; } @@ -2595,13 +2724,19 @@ fn restore_tree(copy: &GemCopy, snapshot_dir: &Path) -> std::io::Result<()> { /// for hash, what is in the gem's tree. ([`commit_build`] writes the /// marker before it drops the parked build, and the snapshot goes after /// both.) -fn build_committed_since(copy: &GemCopy, ext: &Path, snapshot: &Path) -> bool { +/// +/// With no marker file there, no build was recorded. A marker that cannot +/// be probed says neither: `Err`, and the tree is not touched on a guess. +fn build_committed_since(copy: &GemCopy, ext: &Path, snapshot: &Path) -> std::io::Result { + let marker = copy.gem_dir.join(MARKER_FILE); + if try_entry_type(&marker)?.is_none() { + return Ok(false); + } let written = |path: &Path| std::fs::symlink_metadata(path).and_then(|meta| meta.modified()); - let (Ok(marked), Ok(taken)) = (written(©.gem_dir.join(MARKER_FILE)), written(snapshot)) - else { - return false; + let (Ok(marked), Ok(taken)) = (written(&marker), written(snapshot)) else { + return Ok(false); }; - ext.join(BUILD_COMPLETE).is_file() + Ok(ext.join(BUILD_COMPLETE).is_file() && marked >= taken && read_marker_sync(©.gem_dir).is_some_and(|marker| { !marker.grafted @@ -2610,7 +2745,7 @@ fn build_committed_since(copy: &GemCopy, ext: &Path, snapshot: &Path) -> bool { && compute_file_git_sha256_sync(©.gem_dir.join(rel)) .is_ok_and(|now| &now == hash) }) - }) + })) } /// Drop what a run that died left of a [`TreeSnapshot`] of `copy`, once no @@ -2639,6 +2774,11 @@ fn drop_stale_tree_snapshots(copy: &GemCopy) { /// left as recorded: that is the original, and this build ran over /// socket-patch's own. Without a backup of a build RubyGems made there is /// nothing to add to (the original is gone, and `rollback` rebuilds). +/// +/// "Without a backup" is a backup dir, or its description, that is not +/// there. One that is there and cannot be probed or read is an error: the +/// build is then not recorded, and is undone +/// ([`try_read_backup_info`]). fn back_up_tree_changes( copy: &GemCopy, snapshot: &TreeSnapshot, @@ -2646,8 +2786,10 @@ fn back_up_tree_changes( changes: &TreeChanges, ) -> std::io::Result<()> { let backup = copy.gem_dir.join(BACKUP_DIR); - let known = read_backup_info(&backup).filter(|info| !info.grafted && is_real_dir(&backup)); - let Some(mut info) = known else { + if !try_entry_type(&backup)?.is_some_and(|kind| kind.is_dir()) { + return Ok(()); + } + let Some(mut info) = try_read_backup_info(&backup)?.filter(|info| !info.grafted) else { return Ok(()); }; let before = (info.lib_files.len(), info.created_files.len()); @@ -2830,11 +2972,13 @@ async fn rebuild( Err(e) => { // The parked build stays where it is when the tree // cannot be put back: the next run tries again. + // (A snapshot that cannot be probed is not taken for + // none: files may be gone from the tree by now.) let snapshot_dir = tree_snapshot_path(&probe.extension_dir); - let undone = if is_real_dir(&snapshot_dir) { - restore_tree(©, &snapshot_dir) - } else { - Ok(()) + let undone = match try_entry_type(&snapshot_dir) { + Ok(Some(kind)) if kind.is_dir() => restore_tree(©, &snapshot_dir), + Ok(_) => Ok(()), + Err(e) => Err(e), }; let undone = undone.and_then(|()| put_back(©, &probe, aside)); if undone.is_ok() { @@ -2920,15 +3064,15 @@ fn stage_root(copy: &GemCopy) -> PathBuf { /// at all. The gem tree can come from the repository being scanned, and a /// stage is created, emptied and deleted by path: a link (or a file) /// planted at either name would steer those writes and deletes into -/// whatever it points at. `Err` names the entry that is in the way. Every -/// use of the stage goes through here. -fn stage_dirs(copy: &GemCopy) -> Result<(PathBuf, PathBuf), PathBuf> { +/// whatever it points at. An entry that cannot be probed is no better: only +/// "not found" says nothing is there ([`ensure_dir_or_absent`]). `Err` says +/// which entry is in the way, and how. Every use of the stage goes through +/// here. +fn stage_dirs(copy: &GemCopy) -> Result<(PathBuf, PathBuf), String> { let parent = copy.home.join(BUILD_STAGE_DIR); let root = stage_root(copy); for dir in [&parent, &root] { - if std::fs::symlink_metadata(dir).is_ok_and(|meta| !meta.is_dir()) { - return Err(dir.clone()); - } + ensure_dir_or_absent(dir).map_err(|e| format!("its stage directory {e}"))?; } Ok((parent, root)) } @@ -2966,8 +3110,9 @@ fn unlocked_stage_is_dead(root: &Path) -> bool { /// one that is left is only disk space. `Err` of kind `WouldBlock`: a run /// that is still alive holds it ([`lock_build_dir`]); or, where a /// directory cannot be locked, it is not old enough to be provably dead -/// ([`unlocked_stage_is_dead`]). A link planted where the stage goes is -/// left alone, with whatever it points at ([`stage_dirs`]). +/// ([`unlocked_stage_is_dead`]). A link planted where the stage goes, or +/// an entry there that cannot be probed, is left alone, with whatever it +/// points at ([`stage_dirs`]). fn sweep_stale_stage(copy: &GemCopy) -> std::io::Result<()> { sweep_stale_stage_with(copy, lock_build_dir) } @@ -3025,12 +3170,7 @@ impl Stage { fn open_stage(copy: &GemCopy) -> Result { // The stage is emptied and written under the gem home. A link planted // where it goes would move both somewhere else. - let (parent, root) = stage_dirs(copy).map_err(|planted| { - StageFailure::NoStage(format!( - "its stage directory {} is not a directory", - planted.display() - )) - })?; + let (parent, root) = stage_dirs(copy).map_err(StageFailure::NoStage)?; let failed = |e: std::io::Error| { if e.kind() == std::io::ErrorKind::WouldBlock { StageFailure::Busy(recovery_refusal(copy, &e)) @@ -3237,12 +3377,15 @@ fn prove_own_source( let mut agreed = 0; for rel in tree_files(staged) { let theirs = installed.join(&rel); - match std::fs::symlink_metadata(&theirs) { - Err(_) => continue, - Ok(meta) if !meta.is_file() => { + // Only a file that is not there is one the copy does not hold. One + // that cannot be probed is not compared, so it proves nothing. + match try_entry_type(&theirs) { + Ok(None) => continue, + Ok(Some(kind)) if !kind.is_file() => { return Err(format!("{rel} is not a file in the installed gem")) } - Ok(_) => {} + Ok(Some(_)) => {} + Err(e) => return Err(format!("{rel}: in the installed gem, {e}")), } let (Ok(ours), Ok(theirs)) = ( compute_file_git_sha256_sync(&staged.join(&rel)), @@ -3919,11 +4062,14 @@ fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std: std::fs::write(&dst, read_regular_to_bytes_sync(&src)?)?; std::fs::set_permissions(&dst, std::fs::symlink_metadata(&src)?.permissions()) }; - if std::fs::symlink_metadata(&backup).is_ok() { - let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) - .ok() + // As [`back_up_original`]: only "not there" makes a new backup. + if let Some(kind) = try_entry_type(&backup)? { + let known = kind + .is_dir() + .then(|| read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()) + .flatten() .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); - if let Some(mut info) = known.filter(|info| info.grafted && is_real_dir(&backup)) { + if let Some(mut info) = known.filter(|info| info.grafted) { let before = (info.lib_files.len(), info.absent_files.len()); for graft in grafts { if original(&graft.target) && !info.lib_files.contains(&graft.target) { @@ -3944,7 +4090,7 @@ fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std: } // A marker that cannot be read says nothing of which binaries are the // gem's own. - if marker.is_none() && std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { + if marker.is_none() && try_entry_type(©.gem_dir.join(MARKER_FILE))?.is_some() { return Ok(false); } let fresh: Vec<&Graft> = grafts.iter().filter(|g| original(&g.target)).collect(); @@ -4143,9 +4289,9 @@ pub async fn rollback_files( }; let info = crate::utils::fs::run_blocking(move || { let backup = copy.gem_dir.join(BACKUP_DIR); - if is_symlink(&backup) { - return None; - } + // A backup this tool made is a directory. A link there, or an + // entry that cannot be told from one, is not read through. + refuse_link(&backup, "a backup").ok()?; let bytes = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()?; serde_json::from_slice::(&bytes).ok() }) @@ -4962,22 +5108,31 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result std::io::Result<_> { + refuse_link(&backup, "a backup this tool made")?; + if try_entry_type(&backup.join(BACKUP_INFO))?.is_some() { + // The backup is this gem version's install-time build + // whatever the marker says, or fails to say. + return Ok((true, read_marker_sync(&gem_dir))); + } + Ok((false, read_marker_strict(&gem_dir)?)) + }) + .await + }; + let (has_backup, marker) = + carried.map_err(|e| format!("{e}; left as it is, {pristine_hint}"))?; if has_backup { let c = copy.clone(); return crate::utils::fs::run_blocking(move || restore_backup(&c, marker.as_ref())) @@ -5111,18 +5266,18 @@ fn restore_backup(copy: &GemCopy, marker: Option<&BuildMarker>) -> std::io::Resu if info.grafted { restore_lib_files()?; } else { - let ext_dir = confined_ext_dir(copy, &info.extension_dir) - .filter(|dir| !is_symlink(dir)) - .ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!( - "the backup names {:?}, which is not this gem's extension dir under {}", - info.extension_dir, - copy.home.display() - ), - ) - })?; + let ext_dir = confined_ext_dir(copy, &info.extension_dir).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "the backup names {:?}, which is not this gem's extension dir under {}", + info.extension_dir, + copy.home.display() + ), + ) + })?; + // It is emptied and refilled by path. + refuse_link(&ext_dir, "this gem's extension dir")?; // socket-patch's lib copies go; the originals come back. for lib in marker.iter().flat_map(|m| m.lib_artifacts.keys()) { if is_safe_relative_subpath(lib) && !info.lib_files.contains(lib) { @@ -6933,7 +7088,7 @@ mod tests { ); assert!(outside.join("a-1/keep").is_file(), "{case}"); assert!( - is_symlink(&home.join(BUILD_STAGE_DIR)), + crate::utils::containment::is_link(&home.join(BUILD_STAGE_DIR)), "{case}: the link is left" ); let why = open_stage(©).err().unwrap().describe(); @@ -6953,6 +7108,166 @@ mod tests { assert!(outside.join("a-1/keep").is_file()); } + /// Only "not found" says a path holds nothing. One that cannot be + /// probed (a parent that is a file; a directory that may not be + /// searched) may hold a planted link, so it is refused like one: the + /// stage is neither swept nor opened, a backup is not restored through, + /// and a file the own-source proof cannot look at proves nothing. Each + /// refusal names the path. + #[cfg(unix)] + #[tokio::test] + async fn an_unprobeable_path_is_never_taken_for_a_real_one() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let copy = installed_gem(&home, "lib"); + std::fs::write(copy.gem_dir.join("lib/a.rb"), b"x").unwrap(); + + let link = tmp.path().join("link"); + std::os::unix::fs::symlink(&home, &link).unwrap(); + let why = refuse_link(&link, "an extension dir").unwrap_err(); + assert!( + why.to_string() + .contains("is a symlink, not an extension dir"), + "{why}" + ); + refuse_link(&tmp.path().join("missing"), "a dir").unwrap(); + refuse_link(&home, "a dir").unwrap(); + // ENOTDIR: a file where a directory is named. + let through_file = copy.gem_dir.join("lib/a.rb/below"); + let why = refuse_link(&through_file, "a dir").unwrap_err().to_string(); + assert!( + why.contains("lib/a.rb/below") && why.contains("could not be checked"), + "{why}" + ); + + // Root searches any directory: the rest needs a user. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipping the unreadable-directory cases: running as root"); + return; + } + let mode = |path: &Path, mode: u32| { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap() + }; + + // A stage a dead run left, in a gem home that may not be searched. + let root = stage_root(©); + std::fs::create_dir_all(root.join("home")).unwrap(); + std::fs::write(root.join("home/half"), b"x").unwrap(); + mode(&home, 0o000); + let named = stage_dirs(©); + let swept = sweep_stale_stage(©); + let opened = open_stage(©).map(|_| ()).map_err(|e| e.describe()); + mode(&home, 0o755); + for why in [named.unwrap_err(), opened.unwrap_err()] { + assert!( + why.contains(BUILD_STAGE_DIR) + && why.contains("could not be checked") + && why.contains("ermission denied"), + "{why}" + ); + } + swept.unwrap(); + assert!( + root.join("home/half").is_file(), + "an unverified stage was swept" + ); + + // A file the installed copy holds, where it cannot be looked at: the + // archive's differs, and the proof must not pass on the rest. + let (installed, staged) = (tmp.path().join("installed"), tmp.path().join("staged")); + for (tree, lib) in [(&installed, "theirs"), (&staged, "ours")] { + std::fs::create_dir_all(tree.join("lib")).unwrap(); + std::fs::create_dir_all(tree.join("ext/a")).unwrap(); + std::fs::write(tree.join("lib/a.rb"), lib).unwrap(); + std::fs::write(tree.join("ext/a/a.c"), b"int a;").unwrap(); + } + mode(&installed.join("lib"), 0o000); + let proved = prove_own_source(&installed, &staged, &HashMap::new()); + mode(&installed.join("lib"), 0o755); + let why = proved.unwrap_err(); + assert!( + why.contains("lib/a.rb") && why.contains("could not be checked"), + "{why}" + ); + let why = prove_own_source(&installed, &staged, &HashMap::new()).unwrap_err(); + assert!(why.contains("lib/a.rb differs"), "{why}"); + + // A gem dir that may not be searched: whether it holds a backup (or + // a link planted where one goes) cannot be told, so rollback does + // not report the copy as carrying none. + let env = RubyEnv { + cwd: tmp.path().to_path_buf(), + rebuild: true, + offline: true, + }; + mode(©.gem_dir, 0o000); + let restored = restore_original_build(©.gem_dir, &env).await; + mode(©.gem_dir, 0o755); + let why = restored.unwrap_err(); + assert!( + why.contains(BACKUP_DIR) + && why.contains("could not be checked") + && why.contains("gem pristine a"), + "{why}" + ); + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(false)); + + // A backup dir that may not be searched: its description cannot be + // probed, so the backup is not taken for missing (which would have + // rollback rebuild in place over it, or report nothing to restore). + let backup = copy.gem_dir.join(BACKUP_DIR); + std::fs::create_dir_all(&backup).unwrap(); + std::fs::write(backup.join(BACKUP_INFO), b"{}").unwrap(); + mode(&backup, 0o000); + let restored = restore_original_build(©.gem_dir, &env).await; + mode(&backup, 0o755); + let why = restored.unwrap_err(); + assert!( + why.contains(BACKUP_INFO) + && why.contains("could not be checked") + && why.contains("gem pristine a"), + "{why}" + ); + assert!(backup.join(BACKUP_INFO).is_file()); + } + + /// A marker that is there and cannot be read is not "no marker": a + /// rollback with no backup to restore does not report such a copy as + /// carrying nothing. With no marker file at all, it does. + #[tokio::test] + async fn a_marker_that_cannot_be_read_is_not_taken_for_none() { + let tmp = tempfile::tempdir().unwrap(); + let copy = installed_gem(&tmp.path().join("home"), "lib"); + let env = RubyEnv { + cwd: tmp.path().to_path_buf(), + rebuild: true, + offline: true, + }; + assert_eq!(read_marker_strict(©.gem_dir).unwrap(), None); + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(false)); + + let marker = copy.gem_dir.join(MARKER_FILE); + for unreadable in [ + "not json".to_string(), + // A schema this version does not know. + serde_json::json!({ "schema": 99, "sources": {} }).to_string(), + ] { + std::fs::write(&marker, &unreadable).unwrap(); + assert_eq!(read_marker_sync(©.gem_dir), None); + let why = restore_original_build(©.gem_dir, &env) + .await + .unwrap_err(); + assert!( + why.contains(MARKER_FILE) + && why.contains("could not be read as a build marker") + && why.contains("gem pristine a"), + "{unreadable}: {why}" + ); + assert!(marker.is_file(), "the marker is left"); + } + } + /// Where a directory cannot be locked, nothing vouches that a stage is /// dead: one whose heartbeat is younger than any live step lasts is /// left to the run that may still be building in it, and the purl is @@ -7667,4 +7982,139 @@ mod tests { b"committed" ); } + + /// The snapshot and the backup of an in-place build are acted on by + /// what they lack: a file the snapshot does not list is removed, and a + /// build the backup does not record loses its files to a rollback. So + /// neither is used when it cannot be read whole. A gem tree that + /// cannot be listed gets no snapshot; a snapshot whose copies cannot be + /// listed restores nothing and removes nothing; a backup whose + /// description is there and cannot be read is not taken for no backup. + #[cfg(unix)] + #[test] + fn a_snapshot_or_backup_that_cannot_be_read_is_never_taken_for_none() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let installed = tree_bytes(©.gem_dir); + let absent = ["patches/a.patch".to_string()]; + + // A backup whose description is there and is not one. + let backup = copy.gem_dir.join(BACKUP_DIR); + std::fs::create_dir_all(&backup).unwrap(); + std::fs::write(backup.join(BACKUP_INFO), b"not json").unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + build_in_tree(©, &probe); + let changes = tree_changes(©, &snapshot); + assert!(read_backup_info(&backup).is_none()); + for why in [ + back_up_tree_changes(©, &snapshot, &[], &changes).unwrap_err(), + note_absent_files(&backup, &absent).unwrap_err(), + ] { + let why = why.to_string(); + assert!( + why.contains(BACKUP_INFO) + && why.contains("could not be read as a backup's description"), + "{why}" + ); + } + assert!(!backup.join("lib").exists(), "nothing was added to it"); + // With no description at all there is no backup to add to. + std::fs::remove_file(backup.join(BACKUP_INFO)).unwrap(); + back_up_tree_changes(©, &snapshot, &[], &changes).unwrap(); + note_absent_files(&backup, &absent).unwrap(); + std::fs::remove_dir_all(&backup).unwrap(); + restore_tree(©, &snapshot.dir).unwrap(); + assert_eq!(tree_bytes(©.gem_dir), installed); + + // Root reads any directory: the rest needs a user. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipping the unreadable-directory cases: running as root"); + return; + } + let mode = |path: &Path, mode: u32| { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap() + }; + + // A dir of the gem's tree that cannot be listed: no snapshot is + // taken of the rest, since undoing a build from it would remove + // nothing it does not show, and put back nothing it does not hold. + let hidden = copy.gem_dir.join("ext/a"); + mode(&hidden, 0o000); + let taken = snapshot_tree(©, &probe.extension_dir, &record_paths()); + mode(&hidden, 0o755); + let why = taken + .err() + .expect("a partial snapshot was taken") + .to_string(); + assert!(why.contains("could not be listed"), "{why}"); + let dir = tree_snapshot_path(&probe.extension_dir); + assert!(!dir.exists() && !tree_snapshot_stage(&dir).exists()); + + // A snapshot whose copies cannot be listed: read as holding none, + // it would have every file of the gem removed. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + build_in_tree(©, &probe); + let built = tree_bytes(©.gem_dir); + let copies = snapshot.dir.join(SNAPSHOT_TREE); + mode(&copies, 0o000); + let restored = restore_tree(©, &snapshot.dir); + mode(&copies, 0o755); + let why = restored.unwrap_err().to_string(); + assert!(why.contains("could not be listed"), "{why}"); + assert_eq!( + tree_bytes(©.gem_dir), + built, + "the gem's files were removed" + ); + assert!( + snapshot.dir.is_dir(), + "the snapshot is kept for the next run" + ); + restore_tree(©, &snapshot.dir).unwrap(); + assert_eq!(tree_bytes(©.gem_dir), installed); + } + + /// A gem home can come from the repository being scanned, and recovery + /// runs before anything else is looked at. A snapshot planted beside a + /// parked build, naming a file under a link in the gem dir, writes + /// nothing through that link: no file is created or replaced outside + /// the gem dir, and none of the gem's own is removed. + #[cfg(unix)] + #[test] + fn a_planted_tree_snapshot_writes_nothing_through_a_link() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let installed = tree_bytes(©.gem_dir); + let outside = tmp.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("existing"), b"mine").unwrap(); + std::fs::create_dir_all(parked_build_path(&probe.extension_dir)).unwrap(); + let planted = tree_snapshot_path(&probe.extension_dir); + std::fs::create_dir_all(planted.join(SNAPSHOT_TREE).join("out")).unwrap(); + for name in ["created", "existing"] { + let file = planted.join(SNAPSHOT_TREE).join("out").join(name); + std::fs::write(file, b"planted").unwrap(); + } + std::fs::write(planted.join(SNAPSHOT_LEFT), b"[]").unwrap(); + std::os::unix::fs::symlink(&outside, copy.gem_dir.join("out")).unwrap(); + + let why = recover_interrupted_rebuild_sync(©, Some("lib")) + .unwrap_err() + .to_string(); + assert!( + why.contains("is a symlink") && why.contains("out/created"), + "{why}" + ); + assert!( + !outside.join("created").exists(), + "written through the link" + ); + assert_eq!(std::fs::read(outside.join("existing")).unwrap(), b"mine"); + assert_eq!( + tree_bytes(©.gem_dir), + installed, + "the gem's own files were removed" + ); + } } diff --git a/crates/socket-patch-core/src/patch/gem_refresh.rs b/crates/socket-patch-core/src/patch/gem_refresh.rs index 261f0bd91..9a7506adf 100644 --- a/crates/socket-patch-core/src/patch/gem_refresh.rs +++ b/crates/socket-patch-core/src/patch/gem_refresh.rs @@ -58,8 +58,9 @@ const MAX_METADATA_BYTES: u64 = 16 * 1024 * 1024; pub enum Source<'a> { /// The patch server's serve routes. PatchServer(&'a crate::api::client::ApiClient), - /// A public gem registry. - Registry, + /// A public gem registry, reached over `https` (or on this machine) + /// through the run's one client for it. + Registry(&'a crate::vendor::registry_fetch::SecureRegistryClient), /// `--offline`: only what is already on disk. DiskOnly, } @@ -156,10 +157,9 @@ async fn obtain(wanted: &Wanted, source: &Source<'_>) -> Result, String> .download_artifact(url) .await .map_err(|e| crate::utils::redact::redact_urls_in(&e.to_string()).into_owned()), - Source::Registry => { - let client = crate::vendor::registry_fetch::build_registry_client(); - crate::vendor::registry_fetch::download(&client, url).await - } + // The gem is installed, and built when it has a native + // extension: over https, or from this machine, and nothing else. + Source::Registry(registry) => registry.download(url).await, }; match fetched { Ok(bytes) if wanted.sha256.contains(&sha256_hex_of(&bytes)) => return Ok(bytes), @@ -379,14 +379,12 @@ async fn refresh_installed( return Err(format!("{} is not a directory", install.gem_dir.display())); } // The stage is emptied and written under the gem home. A link - // planted where it goes would move both somewhere else. + // planted where it goes would move both somewhere else, and an + // entry that cannot be probed may be one: only "not found" + // says nothing is there. for dir in [install.home.join(STAGE_DIR), install.stage()] { - if std::fs::symlink_metadata(&dir).is_ok_and(|meta| !meta.is_dir()) { - return Err(format!( - "its stage directory {} is not a directory", - dir.display() - )); - } + crate::utils::containment::ensure_dir_or_absent(&dir) + .map_err(|e| format!("its stage directory {e}"))?; } let spec = crate::utils::fs::read_regular_to_string_sync(&install.spec()) .map_err(|e| format!("its installed gemspec is unreadable: {e}"))?; @@ -835,6 +833,53 @@ mod tests { ); } + /// Only "not found" says nothing is where the stage goes. A stage + /// entry that cannot be probed may be a planted link: the refresh + /// refuses, names it, and touches nothing. + #[cfg(unix)] + #[tokio::test] + async fn an_unprobeable_stage_directory_is_refused() { + use std::os::unix::fs::PermissionsExt; + // Root searches any directory. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipping: running as root, directory perms are not enforced"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let gem_dir = install(&home, "VULNERABLE\n", &upstream()); + let archive = tmp.path().join("patched.gem"); + std::fs::write(&archive, patched()).unwrap(); + // The stage dir of the home may not be searched: what is at the + // gem's own stage inside it cannot be told. + let stages = home.join(STAGE_DIR); + std::fs::create_dir_all(stages.join("rack-2.2.3")).unwrap(); + std::fs::write(stages.join("rack-2.2.3/keep"), b"left").unwrap(); + std::fs::set_permissions(&stages, std::fs::Permissions::from_mode(0o000)).unwrap(); + + let out = refresh( + &wanted(&patched(), &[&archive]), + &[Target::Installed(gem_dir.clone())], + &Source::DiskOnly, + &ruby(tmp.path()), + ) + .await; + std::fs::set_permissions(&stages, std::fs::Permissions::from_mode(0o755)).unwrap(); + let why = out[0].clone().expect_err("an unprobeable stage is refused"); + assert!( + why.contains("could not be checked") && why.contains("rack-2.2.3"), + "{why}" + ); + assert_eq!( + std::fs::read(stages.join("rack-2.2.3/keep")).unwrap(), + b"left" + ); + assert_eq!( + std::fs::read(gem_dir.join("lib/rack.rb")).unwrap(), + UPSTREAM_LIB + ); + } + #[tokio::test] async fn an_unverified_archive_changes_nothing() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs index d7d047e56..a4c26d7f3 100644 --- a/crates/socket-patch-core/src/patch/gem_source.rs +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -18,6 +18,14 @@ //! their sha256 is the one that registry's compact index //! (`info/`) records. `--offline` skips this step. //! +//! The index vouches for the archive only when nobody on the network path +//! can rewrite both, and the archive's build scripts are about to run: the +//! registry is asked over `https`, or over plain `http` on this machine (a +//! local mirror, the hermetic tests), and over nothing else. A +//! `SOCKET_RUBYGEMS_URL` that is neither is refused before any request, and +//! so is a redirect that would leave `https` +//! ([`SecureRegistryClient`]); the gem then has no archive but a cached one. +//! //! Wherever it comes from, the archive is only a candidate: before //! anything of it is built, `gem_ext` proves it is the installed copy's //! own source, file by file (`prove_own_source` there). That, not this @@ -52,9 +60,11 @@ use std::path::Path; use std::sync::OnceLock; use crate::formats::gem::{self, BUNDLER_LOCKS}; -use crate::patch::redirect::upstream::{compact_index_checksum, is_rubygems_remote, rubygems_base}; +use crate::patch::redirect::upstream::{ + compact_index_checksum, is_rubygems_remote, rubygems_base, rubygems_secure_base, +}; use crate::utils::digest::{sha256_hex, sha256_hex_of}; -use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient}; +use crate::vendor::registry_fetch::SecureRegistryClient; /// One gem release: `-[-]`. #[derive(Debug, Clone, PartialEq, Eq)] @@ -126,9 +136,12 @@ pub(crate) struct GemSource { /// [`resolved_elsewhere`] of the project's lock. elsewhere: HashMap, offline: bool, + /// The default registry's base URL, or why nothing is downloaded from + /// it: it is reached over plain http ([`rubygems_secure_base`]). + registry: Result, /// Built by the first download: a dry run, an offline run and a run /// that finds its archive cached never make one. - http: OnceLock, + http: OnceLock, } impl GemSource { @@ -146,6 +159,7 @@ impl GemSource { GemSource { elsewhere, offline, + registry: rubygems_secure_base(), http: OnceLock::new(), } } @@ -154,18 +168,33 @@ impl GemSource { self.offline } + /// The registry as a message names it: its base URL with any + /// credentials redacted (`SOCKET_RUBYGEMS_URL` may carry a mirror's + /// `user:token@`, and these messages reach `--json` output and CI + /// logs). Every message of this module that names the registry, or a + /// URL under it, goes through [`shown`]. + fn registry_name(&self) -> String { + match &self.registry { + Ok(base) => shown(base), + Err(_) => shown(&rubygems_base()), + } + } + /// Why nothing is downloaded for the gem `name`: the lock resolves it - /// from another source, or the run is offline. `None` when the - /// registry may be asked. + /// from another source, the run is offline, or the registry is reached + /// over plain http. `None` when the registry may be asked. fn withheld(&self, name: &str) -> Option { if let Some(source) = self.elsewhere.get(name) { return Some(format!( "the project's lock resolves {name} from {source}, not from {}, so it is not \ downloaded", - rubygems_base() + self.registry_name() )); } - self.offline.then(|| "this run is offline".to_string()) + if self.offline { + return Some("this run is offline".to_string()); + } + self.registry.as_ref().err().cloned() } /// Whether the archive of `id` is in the gem home `home`'s `cache/` @@ -214,13 +243,18 @@ impl GemSource { home.join("cache").display().to_string(), ); if self.elsewhere.contains_key(&id.name) { - format!("Put {file} in {cache}.") - } else { - format!( + return format!("Put {file} in {cache}."); + } + match &self.registry { + Ok(_) => format!( "Run `socket-patch apply` once with network access to {}, or put {file} in \ {cache}.", - rubygems_base() - ) + self.registry_name() + ), + Err(_) => format!( + "With an https registry (or SOCKET_RUBYGEMS_URL unset), run `socket-patch \ + apply` once with network access, or put {file} in {cache}." + ), } } @@ -242,25 +276,34 @@ impl GemSource { return Err(format!("{} is not there and {withheld}", cache.display())); } let fetched = async { - let base = rubygems_base(); - let info = self.index(&base, &id.name).await?; + let base = self.registry.as_ref().map_err(String::clone)?; + let info = self.index(base, &id.name).await?; let want = compact_index_checksum(&info, &id.token()).ok_or_else(|| { format!("{base} lists no {} {} with a checksum", id.name, id.token()) })?; - self.fetch_verified(&base, id, &want).await + self.fetch_verified(base, id, &want).await }; fetched.await.map_err(|why: String| { format!( - "{} is not there and it could not be downloaded ({why})", - cache.display() + "{} is not there and it could not be downloaded ({})", + cache.display(), + shown(&why) ) }) } + /// `url`'s bytes, from the registry and over a transport nobody can + /// rewrite ([`SecureRegistryClient`]): the one way this module makes a + /// request. + async fn get(&self, url: &str) -> Result, String> { + let registry = self.http.get_or_init(SecureRegistryClient::new); + registry.download(url).await + } + /// The registry's compact index document of the gem `name`. async fn index(&self, base: &str, name: &str) -> Result { let url = format!("{base}/info/{name}"); - let bytes = download(self.http.get_or_init(build_registry_client), &url).await?; + let bytes = self.get(&url).await?; String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8")) } @@ -268,7 +311,7 @@ impl GemSource { /// (what the registry's index records for it). async fn fetch_verified(&self, base: &str, id: &GemId, want: &str) -> Result, String> { let url = format!("{base}/gems/{}.gem", id.full_name()); - let bytes = download(self.http.get_or_init(build_registry_client), &url).await?; + let bytes = self.get(&url).await?; if sha256_hex_of(&bytes) == want { Ok(bytes) } else { @@ -294,23 +337,33 @@ impl GemSource { if let Some(withheld) = self.withheld(name) { return Err(withheld); } - let base = rubygems_base(); - let info = self.index(&base, name).await?; - let (version, sha) = pick_release(&info, requirement, ruby) - .ok_or_else(|| format!("{base} lists no release of {name} that meets {requirement}"))?; - let id = GemId { - name: name.to_string(), - version, - platform: None, + let fetched = async { + let base = self.registry.as_ref().map_err(String::clone)?; + let info = self.index(base, name).await?; + let (version, sha) = pick_release(&info, requirement, ruby).ok_or_else(|| { + format!("{base} lists no release of {name} that meets {requirement}") + })?; + let id = GemId { + name: name.to_string(), + version, + platform: None, + }; + if !id.is_plain() { + return Err(format!("{} is not a plain gem name", id.full_name())); + } + let bytes = self.fetch_verified(base, &id, &sha).await?; + Ok((id, bytes)) }; - if !id.is_plain() { - return Err(format!("{} is not a plain gem name", id.full_name())); - } - let bytes = self.fetch_verified(&base, &id, &sha).await?; - Ok((id, bytes)) + fetched.await.map_err(|why: String| shown(&why)) } } +/// `text` as a message carries it: the credentials of every URL in it +/// redacted. +fn shown(text: &str) -> String { + crate::utils::redact::redact_urls_in(text).into_owned() +} + /// `/cache/.gem`. pub(crate) fn cache_path(home: &Path, id: &GemId) -> std::path::PathBuf { home.join("cache").join(format!("{}.gem", id.full_name())) @@ -790,4 +843,213 @@ mod tests { std::fs::write(cache_path(&home, &private), b"private").unwrap(); assert_eq!(online.archive(&home, &private).await.unwrap(), b"private"); } + + /// A source with nothing in its lock, online, asking `registry`. + fn asking(registry: Result) -> GemSource { + GemSource { + elsewhere: HashMap::new(), + offline: false, + registry, + http: OnceLock::new(), + } + } + + /// A registry reached over plain http is never asked: whoever sits on + /// the path would choose the archive and the checksum it is verified + /// against, and the archive's build scripts run. The gem is as far out + /// of reach as offline, the reason says to use https, and the home's + /// cached archive is still its source. + #[tokio::test] + async fn a_registry_over_plain_http_is_never_asked() { + use crate::patch::redirect::upstream::secure_gem_registry; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + std::fs::create_dir_all(home.join("cache")).unwrap(); + let racc = id("racc", "1.8.1", None); + let nokogiri = id("nokogiri", "1.18.3", None); + std::fs::write(cache_path(&home, &racc), b"archive").unwrap(); + + // Nothing answers at this name: a request would fail on the lookup, + // with another message. + let base = "http://user:hunter2@gems.example.test/mirror".to_string(); + let gems = asking(secure_gem_registry(base)); + for why in [ + gems.out_of_reach(&home, &nokogiri).await.unwrap(), + gems.archive(&home, &nokogiri).await.unwrap_err(), + gems.dependency("mini_portile2", "~> 2.8.2", &RubyVersions::default()) + .await + .unwrap_err(), + ] { + assert!( + why.contains("SOCKET_RUBYGEMS_URL") + && why.contains("gems.example.test") + && why.contains("is not an https URL") + && why.contains("set it to an https URL"), + "{why}" + ); + assert!(!why.contains("hunter2"), "{why}"); + } + let remedy = gems.remedy(&home, &nokogiri); + assert!( + remedy.contains("With an https registry") && remedy.contains("nokogiri-1.18.3.gem"), + "{remedy}" + ); + assert!(gems.http.get().is_none(), "no client was built"); + assert_eq!(gems.archive(&home, &racc).await.unwrap(), b"archive"); + assert_eq!(gems.out_of_reach(&home, &racc).await, None); + } + + /// A registry on this machine (a local mirror, the hermetic tests) is + /// asked over plain http: the archive is the one its index records. + /// A redirect from it to a plain-http host elsewhere is not followed, + /// for the index or for the archive. (The host "elsewhere" is + /// `0.0.0.0`: no loopback address to the rule, and nothing sent to it + /// leaves this machine, so the test is off the network even if the + /// rule broke.) + #[tokio::test] + async fn a_loopback_registry_is_asked_and_no_redirect_leaves_it() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + let serve = |from: &'static str, response: ResponseTemplate| { + Mock::given(method("GET")) + .and(path(from)) + .respond_with(response) + .mount(&server) + }; + let away = |to: &str| { + ResponseTemplate::new(302) + .insert_header("location", format!("http://0.0.0.0:9{to}").as_str()) + }; + let archive = b"the source gem".to_vec(); + let listed = |sha: &str| { + ResponseTemplate::new(200).set_body_string(format!("---\n1.0.0 |checksum:{sha}\n")) + }; + serve("/info/good", listed(&sha256_hex_of(&archive))).await; + serve( + "/gems/good-1.0.0.gem", + ResponseTemplate::new(200).set_body_bytes(archive.clone()), + ) + .await; + // Its archive is not the one the index records. + serve("/info/swapped", listed(SHA_A)).await; + serve( + "/gems/swapped-1.0.0.gem", + ResponseTemplate::new(200).set_body_bytes(archive.clone()), + ) + .await; + // Its archive, and the other's index, are redirected elsewhere. + serve("/info/moved", listed(&sha256_hex_of(&archive))).await; + serve("/gems/moved-1.0.0.gem", away("/gems/moved-1.0.0.gem")).await; + serve("/info/gone", away("/info/gone")).await; + + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let gems = asking(Ok(server.uri())); + let of = |name: &str| id(name, "1.0.0", None); + assert_eq!(gems.archive(&home, &of("good")).await.unwrap(), archive); + let (picked, bytes) = gems + .dependency("good", ">= 0", &RubyVersions::default()) + .await + .unwrap(); + assert_eq!((picked, bytes), (of("good"), archive)); + + let why = gems.archive(&home, &of("swapped")).await.unwrap_err(); + assert!(why.contains("does not have the sha256"), "{why}"); + for name in ["moved", "gone"] { + let why = gems.archive(&home, &of(name)).await.unwrap_err(); + assert!( + why.contains("refusing a redirect") && why.contains("0.0.0.0"), + "{name}: {why}" + ); + let why = gems + .dependency(name, ">= 0", &RubyVersions::default()) + .await + .unwrap_err(); + assert!(why.contains("refusing a redirect"), "{name}: {why}"); + } + } + + /// `SOCKET_RUBYGEMS_URL` may carry a mirror's credentials. No message + /// of this module repeats them: not the remedy, not a registry that + /// lists no such gem, not an archive or an index that is not what it + /// should be, not a gem the lock resolves elsewhere. + #[tokio::test] + async fn no_message_repeats_the_registrys_credentials() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + let serve = |from: &'static str, response: ResponseTemplate| { + Mock::given(method("GET")) + .and(path(from)) + .respond_with(response) + .mount(&server) + }; + let listed = + ResponseTemplate::new(200).set_body_string(format!("---\n1.0.0 |checksum:{SHA_A}\n")); + serve("/mirror/info/listed", listed).await; + serve( + "/mirror/gems/listed-1.0.0.gem", + ResponseTemplate::new(200).set_body_bytes(b"another archive".to_vec()), + ) + .await; + serve( + "/mirror/info/garbled", + ResponseTemplate::new(200).set_body_bytes(vec![0xff, 0xfe]), + ) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let base = format!( + "{}/mirror", + server.uri().replace("http://", "http://deploy:hunter2@") + ); + let mut gems = asking(Ok(base)); + gems.elsewhere + .insert("inhouse".to_string(), "a git source".to_string()); + let of = |name: &str, version: &str| id(name, version, None); + let any = RubyVersions::default(); + let said = [ + // The remedy of a refusal, and a gem the lock resolves elsewhere. + gems.remedy(&home, &of("listed", "1.0.0")), + gems.out_of_reach(&home, &of("inhouse", "1.0.0")) + .await + .unwrap(), + // The registry lists no such release. + gems.archive(&home, &of("listed", "2.0.0")) + .await + .unwrap_err(), + gems.dependency("listed", "~> 9.0", &any).await.unwrap_err(), + // Its archive is not the one its index records. + gems.archive(&home, &of("listed", "1.0.0")) + .await + .unwrap_err(), + gems.dependency("listed", ">= 0", &any).await.unwrap_err(), + // Its index is not text; it has none (HTTP 404). + gems.archive(&home, &of("garbled", "1.0.0")) + .await + .unwrap_err(), + gems.dependency("absent", ">= 0", &any).await.unwrap_err(), + ]; + for (text, expected) in said.iter().zip([ + "with network access to http://", + "not from http://", + "lists no listed 2.0.0 with a checksum", + "lists no release of listed that meets ~> 9.0", + "does not have the sha256", + "does not have the sha256", + "is not UTF-8", + "HTTP 404", + ]) { + assert!(text.contains(expected), "no {expected:?} in {text}"); + assert!( + text.contains("/mirror"), + "the registry is still named: {text}" + ); + for secret in ["hunter2", "deploy:"] { + assert!(!text.contains(secret), "{secret} in {text}"); + } + } + } } diff --git a/crates/socket-patch-core/src/patch/redirect/grant.rs b/crates/socket-patch-core/src/patch/redirect/grant.rs index 1373882c3..dbf7ea11a 100644 --- a/crates/socket-patch-core/src/patch/redirect/grant.rs +++ b/crates/socket-patch-core/src/patch/redirect/grant.rs @@ -102,21 +102,6 @@ fn is_url_char(c: char) -> bool { c.is_ascii_alphanumeric() || "-._~:/?[]@!()*+,=%".contains(c) } -/// Whether `url`'s host is the local machine, where a plain-`http` request -/// never crosses a network. -fn is_loopback(url: &reqwest::Url) -> bool { - let Some(host) = url.host_str() else { - return false; - }; - host == "localhost" - || host.ends_with(".localhost") - || host - .trim_start_matches('[') - .trim_end_matches(']') - .parse::() - .is_ok_and(|ip| ip.is_loopback()) -} - /// `url` (the grant's `what`) as a lockfile takes it: an `https` URL of /// [`is_url_char`]s with a host. Plain `http` is taken only from the local /// machine or from one of `origins`, the operator's own patch servers @@ -134,7 +119,9 @@ fn check_url(what: &str, url: &str, origins: &[String]) -> Result<(), Flaw> { let Some(host) = parsed.host_str() else { return Err(malformed()); }; - if parsed.scheme() == "https" || is_loopback(&parsed) || on_configured_origin(&parsed, origins) + if parsed.scheme() == "https" + || crate::utils::http::is_loopback_host(&parsed) + || on_configured_origin(&parsed, origins) { return Ok(()); } @@ -631,6 +618,8 @@ mod tests { // The host after the userinfo is the one that counts. ("http://127.0.0.1@evil.example", "evil.example"), ("http://localhost.evil.example", "localhost.evil.example"), + // A name under `.localhost` is whatever the resolver says. + ("http://patch.localhost:8080", "patch.localhost:8080"), ] { let Err(Flaw::InsecureUrl(reason)) = check(&at(origin), &configured) else { panic!("{origin} must be refused as insecure"); diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index 1a858d767..b5ee71310 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -11,6 +11,7 @@ use tokio::sync::{Mutex, Semaphore, SemaphorePermit}; use crate::api::client::network_error_detail; use crate::vendor::registry_fetch::{ build_registry_client, npm_registry_base, pypi_json_api_base, RegistryClient, + SecureRegistryClient, }; /// An npm version's `dist` block. @@ -108,6 +109,28 @@ pub(crate) fn rubygems_base() -> String { .unwrap_or_else(|| DEFAULT_RUBYGEMS.to_string()) } +/// [`rubygems_base`] as the registry a gem's sha256 is read from and a gem +/// that is built or installed is downloaded from: `Err` when it is not an +/// `https` URL, nor plain `http` to this machine +/// ([`crate::utils::http::insecure_transport`]). The default is `https`, so +/// only `SOCKET_RUBYGEMS_URL` can name such a base. A checksum and an +/// archive read over plain http are whatever the network path serves: no +/// request is made, and the reason says to use an https URL. +pub(crate) fn rubygems_secure_base() -> Result { + secure_gem_registry(rubygems_base()) +} + +/// `base` when a gem and its checksum may be fetched from it +/// ([`rubygems_secure_base`]). +pub(crate) fn secure_gem_registry(base: String) -> Result { + match crate::utils::http::insecure_transport(&base) { + None => Ok(base), + Some(why) => Err(format!( + "SOCKET_RUBYGEMS_URL is not used as the gem registry: {why}; set it to an https URL" + )), + } +} + /// Whether `remote` (a lock's `remote:`, a download base) is the default /// RubyGems registry: rubygems.org, or its `SOCKET_RUBYGEMS_URL` stand-in. /// The one test of it, shared by the upstream restore and by the source @@ -197,6 +220,9 @@ type RegistryCache = Mutex, String, String), /// (#1220). pub(crate) struct UpstreamClient { http: RegistryClient, + /// The client a gem's sha256 is read with ([`Self::rubygems_sha256`]), + /// built by the first such lookup. + secure: std::sync::OnceLock, /// At most [`crate::utils::concurrent::registry_concurrency`] requests /// in flight at once. Every request this client sends takes a slot: the /// public registries, a project's private registry or mirror, and the @@ -222,6 +248,7 @@ impl UpstreamClient { pub(crate) fn with_concurrency(offline: bool, limit: usize) -> Self { UpstreamClient { http: build_registry_client(), + secure: std::sync::OnceLock::new(), permits: Semaphore::new(limit.max(1)), offline, npm: Mutex::default(), @@ -548,6 +575,13 @@ impl UpstreamClient { /// The rubygems.org sha256 of the ruby-platform `name-version.gem`, /// from the compact index bundler itself reads (`info/`). + /// + /// The lock's `CHECKSUMS` entry is re-pinned from it, and after an + /// unwind the installed copy is replaced by the archive that has it + /// (`patch::gem_refresh`), which RubyGems builds when the gem has a + /// native extension. So it is read over a transport nobody can rewrite + /// ([`rubygems_secure_base`], [`SecureRegistryClient`]): a registry + /// reached over plain http is not asked. pub(crate) async fn rubygems_sha256( &self, name: &str, @@ -557,23 +591,44 @@ impl UpstreamClient { if let Some(hit) = self.rubygems.lock().await.get(&key) { return hit.clone(); } - let result = async { - if self.offline { - return Err(OFFLINE.to_string()); - } - if !crate::formats::gem::is_plain_gem_token(name) { - return Err(format!("{name:?} is not a plain gem name")); - } - let url = format!("{}/info/{name}", rubygems_base()); - let text = self.get_text(&url).await?; - compact_index_checksum(&text, version) - .ok_or_else(|| format!("{url} lists no ruby-platform {version} with a checksum")) - } - .await; + let result = self + .rubygems_sha256_at(rubygems_secure_base(), name, version) + .await; self.rubygems.lock().await.insert(key, result.clone()); result } + /// [`Self::rubygems_sha256`], uncached, from the registry at `base` + /// ([`rubygems_secure_base`]: its URL, or why it is not asked). The + /// base may carry a mirror's credentials: no error repeats them. + async fn rubygems_sha256_at( + &self, + base: Result, + name: &str, + version: &str, + ) -> Result { + if self.offline { + return Err(OFFLINE.to_string()); + } + if !crate::formats::gem::is_plain_gem_token(name) { + return Err(format!("{name:?} is not a plain gem name")); + } + let url = format!("{}/info/{name}", base?); + let looked_up = async { + let registry = self.secure.get_or_init(SecureRegistryClient::new); + let bytes = { + let _permit = self.permit().await; + registry.download(&url).await? + }; + let text = String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8"))?; + compact_index_checksum(&text, version) + .ok_or_else(|| format!("{url} lists no ruby-platform {version} with a checksum")) + }; + looked_up + .await + .map_err(|why: String| crate::utils::redact::redact_urls_in(&why).into_owned()) + } + /// Every version packagist serves for the composer package `name` /// (lowercase `vendor/package`), expanded: the stable `p2/.json` /// list, or the `~dev` one when `dev` (composer splits branches out). @@ -897,6 +952,96 @@ mod tests { } } + /// A gem's checksum, and a gem that is built or installed, come from + /// an https registry or one on this machine. Another base is refused + /// with what to do about it, its credentials not repeated. + #[test] + fn a_gem_registry_reached_over_plain_http_is_refused() { + for base in [ + DEFAULT_RUBYGEMS, + "https://gems.example.test/mirror", + "http://127.0.0.1:9292/upstream", + "http://localhost:9292", + "http://[::1]:9292", + ] { + assert_eq!( + secure_gem_registry(base.to_string()).as_deref(), + Ok(base), + "{base}" + ); + } + for base in [ + "http://gems.example.test", + "http://user:hunter2@10.1.2.3:9292/mirror", + "gems.example.test", + "file:///srv/gems", + ] { + let why = secure_gem_registry(base.to_string()).unwrap_err(); + assert!( + why.contains("SOCKET_RUBYGEMS_URL") && why.contains("set it to an https URL"), + "{why}" + ); + assert!(!why.contains("hunter2"), "{why}"); + } + } + + /// The registry's base may carry a mirror's credentials + /// (`SOCKET_RUBYGEMS_URL=https://user:token@…`): the checksum is read + /// with them, and no error of the lookup repeats them. A registry that + /// is refused is not asked at all. + #[tokio::test] + async fn a_gem_checksum_lookup_never_repeats_the_registrys_credentials() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + let sha = "a".repeat(64); + Mock::given(method("GET")) + .and(path("/info/rails")) + .respond_with( + ResponseTemplate::new(200).set_body_string(format!("---\n7.0.0 |checksum:{sha}\n")), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/info/garbled")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![0xff, 0xfe])) + .mount(&server) + .await; + let base = server.uri().replace("http://", "http://deploy:hunter2@"); + let client = UpstreamClient::new(false); + let at = |name: &'static str, version: &'static str| { + client.rubygems_sha256_at(Ok(base.clone()), name, version) + }; + assert_eq!(at("rails", "7.0.0").await, Ok(sha)); + for (name, version, expected) in [ + ( + "rails", + "7.1.0", + "lists no ruby-platform 7.1.0 with a checksum", + ), + ("garbled", "1.0.0", "is not UTF-8"), + ("absent", "1.0.0", "HTTP 404"), + ] { + let why = at(name, version).await.unwrap_err(); + assert!(why.contains(expected), "{why}"); + assert!(why.contains(&format!("/info/{name}")), "{why}"); + assert!( + !why.contains("hunter2") && !why.contains("deploy:"), + "{why}" + ); + } + + let asked = server.received_requests().await.unwrap().len(); + let refused = secure_gem_registry("http://deploy:hunter2@gems.example.test".to_string()); + let why = client + .rubygems_sha256_at(refused, "rails", "7.0.0") + .await + .unwrap_err(); + assert!(why.contains("set it to an https URL"), "{why}"); + assert!(!why.contains("hunter2"), "{why}"); + assert_eq!(server.received_requests().await.unwrap().len(), asked); + } + #[test] fn compact_index_checksum_picks_the_ruby_platform_line() { let sha = "a".repeat(64); 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 70122d768..8bd6e4bc9 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -1051,6 +1051,20 @@ pub(super) async fn unwound_stale_cache( stale_cache_warning(root, purl, &name, &version, lock.as_deref(), &client).await } +/// What is known of the upstream archive of a gem that is back on its +/// registry entry ([`upstream_archive`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UpstreamArchive { + /// Its sha256 (lowercase hex) and, when the lock resolves the gem from + /// rubygems.org, the URL it is served at. + Known { sha256: String, url: Option }, + /// The lock resolves the gem from rubygems.org and pins no sha256 for + /// it, and the registry is not asked for one: why (it is reached over + /// plain http, `rubygems_secure_base`). An installed copy can then + /// not be told from the patched build, and the caller says so. + Unverified(String), +} + /// The upstream archive of the ruby-platform gem `purl`, as the lock at /// `root` pins it once the gem is back on its registry entry: its sha256 /// (the `CHECKSUMS` entry, else the rubygems.org compact index, unless @@ -1059,13 +1073,14 @@ pub(super) async fn unwound_stale_cache( /// it (a restore's staged text; a dry run never wrote it), else the lock is /// read from disk. `None` when nothing proves the sha256: a gem from /// another remote with no `CHECKSUMS` entry, an offline run, a registry -/// error. +/// error. A registry that is refused, not merely out of reach, is +/// [`UpstreamArchive::Unverified`]: that is a setting to report. pub(super) async fn upstream_archive( root: &std::path::Path, restored: Option<&str>, purl: &str, offline: bool, -) -> Option<(String, Option)> { +) -> Option { let (_, name, version) = crate::utils::purl::purl_parts(purl)?; let mut lock = restored.map(str::to_string); if lock.is_none() { @@ -1081,10 +1096,18 @@ pub(super) async fn upstream_archive( let rubygems = rubygems_locked(&lock, &name, &version); let sha = match lock_checksum(&lock, &name, &version) { Some(sha) => sha, - None if rubygems => UpstreamClient::new(offline) - .rubygems_sha256(&name, &version) - .await - .ok()?, + None if rubygems => { + if offline { + return None; + } + if let Err(why) = super::rubygems_secure_base() { + return Some(UpstreamArchive::Unverified(why)); + } + UpstreamClient::new(offline) + .rubygems_sha256(&name, &version) + .await + .ok()? + } None => return None, }; let url = rubygems.then(|| { @@ -1093,7 +1116,10 @@ pub(super) async fn upstream_archive( super::rubygems_base().trim_end_matches('/') ) }); - Some((sha.to_ascii_lowercase(), url)) + Some(UpstreamArchive::Known { + sha256: sha.to_ascii_lowercase(), + url, + }) } /// Whether `lock` resolves `name (version)` from a `GEM` section whose diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index ff0184570..83b247c81 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -45,8 +45,12 @@ mod sbt; mod uv; mod vlt; +#[cfg(test)] +pub(crate) use client::secure_gem_registry; pub(crate) use client::UpstreamClient; -pub(crate) use client::{compact_index_checksum, is_rubygems_remote, rubygems_base}; +pub(crate) use client::{ + compact_index_checksum, is_rubygems_remote, rubygems_base, rubygems_secure_base, +}; pub(crate) use uv::{ declared_lock_specifier, lock_cutoff, pylock_no_binary, respell_lock_specifier, root_uv_settings, LockRequirementArray, @@ -927,6 +931,8 @@ fn format_of(rel: &str) -> Format { /// once its gem is back on the upstream registry entry (#1260, #1594). pub const GEM_STALE_CACHE: &str = gem::STALE_CACHE; +pub use gem::UpstreamArchive; + /// The [`GEM_STALE_CACHE`] advisory, as `(code, detail)`, for the gem /// `purl` a vendored unwind just put back on its upstream entry in the /// project at `root` (#1594). `None` when Bundler's cache dir holds no @@ -942,20 +948,22 @@ pub async fn gem_stale_cache_after_unwind( } /// The upstream `.gem` of a gem `purl` that is back on its registry entry -/// in the project at `root`: `(sha256, download url)`. The sha256 is what -/// the restored lock pins (its `CHECKSUMS` entry, else the rubygems.org -/// compact index, unless `offline`); the url is set when the lock resolves -/// the gem from rubygems.org. `staged` is a restore's -/// [`RestoreOutcome::staged_text`]: the restored lock is read from it when -/// it is there (a dry run's lock is not on disk), else from disk. `None` -/// when nothing proves the sha256, so there is nothing to judge an -/// installed copy or a cached archive by. +/// in the project at `root`: its sha256 and download url +/// ([`UpstreamArchive::Known`]). The sha256 is what the restored lock pins +/// (its `CHECKSUMS` entry, else the rubygems.org compact index, unless +/// `offline`); the url is set when the lock resolves the gem from +/// rubygems.org. `staged` is a restore's [`RestoreOutcome::staged_text`]: +/// the restored lock is read from it when it is there (a dry run's lock is +/// not on disk), else from disk. `None` when nothing proves the sha256, so +/// there is nothing to judge an installed copy or a cached archive by; +/// [`UpstreamArchive::Unverified`] when the registry that would is refused +/// (plain http), which the caller reports. pub async fn gem_upstream_archive( root: &Path, staged: &BTreeMap>, purl: &str, offline: bool, -) -> Option<(String, Option)> { +) -> Option { let restored = crate::formats::gem::BUNDLER_LOCKS .iter() .find_map(|lock| staged.get(*lock)?.as_deref()); diff --git a/crates/socket-patch-core/src/update/release.rs b/crates/socket-patch-core/src/update/release.rs index 73f62817b..3a9f5392c 100644 --- a/crates/socket-patch-core/src/update/release.rs +++ b/crates/socket-patch-core/src/update/release.rs @@ -240,20 +240,18 @@ pub fn sha256sums_entry(sums: &str, file: &str) -> Result { /// MITM tamper with whichever leg it captures (the SHA256SUMS leg is the /// integrity root, so it needs this exactly as much as the archive leg). /// Overridden bases (wiremock fixtures, mirrors) are plain-`http` loopback -/// by design, so there the policy is only hop-count-limited. +/// by design, so there the policy is only hop-count-limited. Both count +/// hops the same way: the crate's one policy +/// ([`crate::utils::http::redirects_unless`]) and its one limit. pub(crate) fn follow_redirect_policy(endpoints: &UpdateEndpoints) -> reqwest::redirect::Policy { + use crate::utils::http::{redirects_unless, MAX_REDIRECTS}; if endpoints.is_default() { - reqwest::redirect::Policy::custom(|attempt| { - if attempt.previous().len() > 10 { - attempt.error("too many redirects") - } else if attempt.url().scheme() != "https" { - attempt.error("refusing insecure (non-HTTPS) redirect for release metadata") - } else { - attempt.follow() - } + redirects_unless(|_, to| { + (to.scheme() != "https") + .then(|| "refusing insecure (non-HTTPS) redirect for release metadata".to_string()) }) } else { - reqwest::redirect::Policy::limited(10) + reqwest::redirect::Policy::limited(MAX_REDIRECTS) } } diff --git a/crates/socket-patch-core/src/utils/containment.rs b/crates/socket-patch-core/src/utils/containment.rs index a0ad66ccc..633cb1ba5 100644 --- a/crates/socket-patch-core/src/utils/containment.rs +++ b/crates/socket-patch-core/src/utils/containment.rs @@ -58,11 +58,46 @@ pub fn try_linked_level(root: &Path, path: &Path) -> std::io::Result bool { std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) } +/// What is at `path` itself (lstat: a link there is not followed), or +/// `Ok(None)` when nothing is. An lstat error other than `NotFound` +/// (EACCES, ENOTDIR, an I/O error) is returned, naming the path, instead +/// of being read as "nothing there" or "not a link": an entry that cannot +/// be probed may be a planted link, and whatever is done next by path +/// (create, empty, delete) would then land in its target. +pub fn try_entry_type(path: &Path) -> std::io::Result> { + match std::fs::symlink_metadata(path) { + Ok(meta) => Ok(Some(meta.file_type())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(std::io::Error::new( + e.kind(), + format!("{} could not be checked ({e})", path.display()), + )), + } +} + +/// `Err` unless `path` is a real directory or not there at all: the check +/// before a directory is created, emptied or deleted by path (a stage dir +/// inside a gem home that the repository being scanned may have laid out). +/// A link or a file there is refused, and so is an entry that cannot be +/// probed ([`try_entry_type`]). The error names the path and says which. +pub fn ensure_dir_or_absent(path: &Path) -> std::io::Result<()> { + match try_entry_type(path)? { + None => Ok(()), + Some(kind) if kind.is_dir() => Ok(()), + Some(_) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} is not a directory", path.display()), + )), + } +} + /// The refusal for writing or deleting `what` through the linked `link`. fn linked_level_refusal(action: &str, what: &Path, link: &Path) -> std::io::Error { std::io::Error::other(format!( @@ -211,6 +246,72 @@ mod tests { ); } + /// `try_entry_type` reads only "not found" as nothing there. An entry + /// it cannot probe (a parent that is a file; a directory it may not + /// search) is an error naming the path, where `is_link` says "no link". + #[cfg(unix)] + #[test] + fn try_entry_type_fails_closed_on_an_unprobeable_path() { + use std::os::unix::fs::{symlink, PermissionsExt}; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::create_dir(root.join("dir")).unwrap(); + std::fs::write(root.join("file"), b"x").unwrap(); + symlink(root.join("dir"), root.join("link")).unwrap(); + symlink(root.join("nowhere"), root.join("dangling")).unwrap(); + + let kind = |name: &str| try_entry_type(&root.join(name)).unwrap(); + assert!(kind("dir").unwrap().is_dir()); + assert!(kind("file").unwrap().is_file()); + assert!(kind("link").unwrap().is_symlink()); + assert!(kind("dangling").unwrap().is_symlink()); + assert!(kind("missing").is_none()); + assert!(kind("missing/deeper").is_none()); + + // The one check for a directory that is made, emptied or deleted + // by path: a real directory, or nothing. + ensure_dir_or_absent(&root.join("dir")).unwrap(); + ensure_dir_or_absent(&root.join("missing")).unwrap(); + for (name, why) in [ + ("file", "is not a directory"), + ("link", "is not a directory"), + ("dangling", "is not a directory"), + ("file/below", "could not be checked"), + ] { + let err = ensure_dir_or_absent(&root.join(name)) + .unwrap_err() + .to_string(); + assert!(err.contains(why) && err.contains(name), "{name}: {err}"); + } + + let through_file = root.join("file/below"); + let err = try_entry_type(&through_file).unwrap_err(); + assert!( + err.to_string() + .contains(&through_file.display().to_string()) + && err.to_string().contains("could not be checked"), + "{err}" + ); + assert!(!is_link(&through_file)); + + // Root searches any directory: the permission case needs a user. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipping the unreadable-directory case: running as root"); + return; + } + let locked = root.join("locked"); + std::fs::create_dir(&locked).unwrap(); + symlink(root.join("dir"), locked.join("planted")).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let probed = try_entry_type(&locked.join("planted")); + let seen = is_link(&locked.join("planted")); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + let err = probed.unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}"); + assert!(err.to_string().contains("planted"), "{err}"); + assert!(!seen, "`is_link` reads the planted link as no link"); + } + #[cfg(unix)] #[test] fn resolves_within_follows_links() { diff --git a/crates/socket-patch-core/src/utils/http.rs b/crates/socket-patch-core/src/utils/http.rs index a113d9570..60d994713 100644 --- a/crates/socket-patch-core/src/utils/http.rs +++ b/crates/socket-patch-core/src/utils/http.rs @@ -240,10 +240,245 @@ pub(crate) async fn read_capped_typed( Ok(bytes) } +/// `url`, parsed, when it may be asked for bytes that are built or +/// installed as fetched, or for the checksum such bytes are verified +/// against: an `https` URL, or a plain `http` one whose host is this machine +/// ([`is_loopback_host`]), which a local mirror and the hermetic tests use. +/// Over any other `http` URL whoever sits on the network path chooses the +/// archive and the checksum served beside it, so verifying one against the +/// other proves nothing. `Err` is why not, quoting the URL redacted. +/// +/// The request is made to the URL this returns +/// (`SecureRegistryClient::download`), so what is judged here is what is +/// fetched: a scheme or a host written in capitals is the same URL to both. +pub(crate) fn secure_url(url: &str) -> Result { + let url = url.trim(); + reqwest::Url::parse(url) + .ok() + .filter(|url| url.scheme() == "https" || is_loopback_http(url)) + .ok_or_else(|| { + format!( + "`{}` is not an https URL (plain http is accepted for a loopback host only)", + crate::utils::redact::redact_urls_in(url) + ) + }) +} + +/// Why [`secure_url`] refuses `url`, or `None` when it does not. +pub(crate) fn insecure_transport(url: &str) -> Option { + secure_url(url).err() +} + +/// Whether `url`'s host is this machine: `localhost`, or an IP address in a +/// loopback range (`127.0.0.1`, `[::1]`). A plain-`http` request sent +/// straight to it crosses no network. The one definition of "this machine" +/// for every plain-`http` exemption (a gem registry here, a patch server +/// URL in `patch::redirect::grant`). A name under `.localhost` is not +/// taken: nothing makes the system resolver answer it from this machine. +pub(crate) fn is_loopback_host(url: &reqwest::Url) -> bool { + let Some(host) = url.host_str() else { + return false; + }; + // An IPv6 host is spelled in brackets. + let host = host.trim_start_matches('[').trim_end_matches(']'); + host.eq_ignore_ascii_case("localhost") + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) +} + +/// Whether `url` is plain `http` to this machine ([`is_loopback_host`]). +pub(crate) fn is_loopback_http(url: &reqwest::Url) -> bool { + url.scheme() == "http" && is_loopback_host(url) +} + +/// The most redirects one request follows, for every client of this crate +/// that sets a policy: reqwest's own default (`Policy::limited(10)`). +pub(crate) const MAX_REDIRECTS: usize = 10; + +/// A redirect policy: at most [`MAX_REDIRECTS`] redirects are followed, and +/// none that `refusal` gives a reason against (it is handed the URL that +/// redirected and the URL it names). The one policy behind every client +/// that restricts where a redirect may lead; each brings its rule. +pub(crate) fn redirects_unless( + refusal: impl Fn(&reqwest::Url, &reqwest::Url) -> Option + Send + Sync + 'static, +) -> reqwest::redirect::Policy { + reqwest::redirect::Policy::custom(move |attempt| { + // `previous` starts with the URL that was asked for, which is no + // redirect: this is the count `Policy::limited` keeps. + if attempt.previous().len() > MAX_REDIRECTS { + return attempt.error("too many redirects"); + } + let why = attempt + .previous() + .last() + .and_then(|from| refusal(from, attempt.url())); + match why { + Some(why) => attempt.error(why), + None => attempt.follow(), + } + }) +} + +/// The redirects a client follows when the bytes it fetches are built or +/// installed ([`secure_url`]): none that leaves `https` for `http`, and +/// none to an `http` host other than this machine ([`redirect_refusal`]). +/// reqwest's default policy follows a redirect from `https` to `http`. +pub(crate) fn no_downgrade_redirects() -> reqwest::redirect::Policy { + redirects_unless(redirect_refusal) +} + +/// Why a redirect from `from` to `to` is not followed +/// ([`no_downgrade_redirects`]). Followed: any redirect to `https`, and one +/// between plain `http` URLs of this machine. Refused: every redirect that +/// leaves `https` (to a loopback host too: the registry does not get to +/// point the download at a local port), and every one to an `http` host +/// that is not this machine. +fn redirect_refusal(from: &reqwest::Url, to: &reqwest::Url) -> Option { + let followed = to.scheme() == "https" || (from.scheme() != "https" && is_loopback_http(to)); + (!followed).then(|| { + format!( + "refusing a redirect from {} to {}, which is not an https URL", + crate::utils::redact::redact_urls_in(from.as_str()), + crate::utils::redact::redact_urls_in(to.as_str()) + ) + }) +} + #[cfg(test)] mod tests { use super::*; + /// Bytes that are built or installed come over https, or from this + /// machine: every other URL is refused, with its credentials redacted. + #[test] + fn only_https_and_loopback_http_carry_bytes_to_build() { + for url in [ + "https://rubygems.org", + "https://gems.example.test/mirror/", + "HTTPS://RubyGems.org", + "http://127.0.0.1:9292", + "http://127.0.0.1", + "http://127.8.9.10:80/gems", + "http://localhost:8080/upstream", + "http://LOCALHOST", + "http://[::1]:3000", + " http://127.0.0.1:1 ", + ] { + assert_eq!(insecure_transport(url), None, "{url}"); + } + for url in [ + "http://rubygems.org", + "http://gems.example.test:8080/mirror", + "http://10.0.0.5", + "http://192.168.1.2:9292", + "http://0.0.0.0:9292", + "http://localhost.example.test", + "http://127.0.0.1.example.test", + "http://notlocalhost", + "http://mirror.localhost:9292", + "http://localhost.:9292", + "http://[::ffff:127.0.0.1]", + "http://[fe80::1]", + "ftp://127.0.0.1/gems", + "file:///tmp/gems", + "rubygems.org", + "//rubygems.org", + "", + ] { + let why = insecure_transport(url).unwrap_or_else(|| panic!("{url:?} was accepted")); + assert!(why.contains("is not an https URL"), "{why}"); + } + let why = insecure_transport("http://user:hunter2@gems.example.test/x").unwrap(); + assert!(why.contains("gems.example.test"), "{why}"); + assert!(!why.contains("hunter2"), "{why}"); + + // What is judged is what is fetched: the URL as it parses. + for (written, fetched) in [ + ( + "HTTPS://Gems.Example.Test/info/a", + "https://gems.example.test/info/a", + ), + ( + "HTTP://LOCALHOST:9292/info/a", + "http://localhost:9292/info/a", + ), + ( + " https://rubygems.org/gems/a-1.gem ", + "https://rubygems.org/gems/a-1.gem", + ), + ] { + assert_eq!(secure_url(written).unwrap().as_str(), fetched, "{written}"); + } + } + + /// No redirect leaves https, and none leads to an http host that is not + /// this machine. + #[test] + fn a_redirect_never_downgrades_the_transport() { + let url = |text: &str| reqwest::Url::parse(text).unwrap(); + for (from, to) in [ + ( + "https://rubygems.org/gems/a-1.gem", + "https://cdn.example.test/a-1.gem", + ), + ( + "http://127.0.0.1:9292/gems/a-1.gem", + "https://rubygems.org/gems/a-1.gem", + ), + ( + "http://127.0.0.1:9292/gems/a-1.gem", + "http://127.0.0.1:9293/a-1.gem", + ), + ( + "http://localhost:9292/gems/a-1.gem", + "http://[::1]:9293/a-1.gem", + ), + ] { + assert_eq!( + redirect_refusal(&url(from), &url(to)), + None, + "{from} -> {to}" + ); + } + for (from, to) in [ + ( + "https://rubygems.org/gems/a-1.gem", + "http://rubygems.org/gems/a-1.gem", + ), + ( + "https://rubygems.org/gems/a-1.gem", + "http://cdn.example.test/a-1.gem", + ), + ( + "https://rubygems.org/gems/a-1.gem", + "http://127.0.0.1:9292/a-1.gem", + ), + ( + "https://rubygems.org/gems/a-1.gem", + "http://localhost/a-1.gem", + ), + ( + "http://127.0.0.1:9292/gems/a-1.gem", + "http://cdn.example.test/a-1.gem", + ), + ( + "http://127.0.0.1:9292/gems/a-1.gem", + "ftp://127.0.0.1/a-1.gem", + ), + ] { + let why = redirect_refusal(&url(from), &url(to)) + .unwrap_or_else(|| panic!("{from} -> {to} was followed")); + assert!(why.contains("refusing a redirect"), "{why}"); + } + let why = redirect_refusal( + &url("https://rubygems.org/gems/a-1.gem"), + &url("http://user:hunter2@cdn.example.test/a-1.gem"), + ) + .unwrap(); + assert!(!why.contains("hunter2"), "{why}"); + } + /// Serve one raw HTTP/1.1 response on loopback and return a response /// whose body is still unread. async fn respond_raw(raw: &'static [u8]) -> reqwest::Response { diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs index 154e6acfd..9a7ff5610 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs @@ -4218,6 +4218,14 @@ fn unsupported_layout_warnings_rewrites_known_codes_and_forwards_unknown_ones() /// from nowhere. The lock's `remote:` and `CHECKSUMS` never become a URL /// or an expected hash. /// +/// The gem downloads (the refresh, the source gem and its build's gems) +/// are installed or built as fetched, so they and the compact index +/// checksum they are verified against (`UpstreamClient::rubygems_sha256`) +/// go through `registry_fetch::SecureRegistryClient`: the same `download`, +/// refused unless the URL is `https` or plain `http` to this machine, with +/// no redirect followed out of `https`. Its method is named `download` +/// too, so a new caller of it is a reference this check sees. +/// /// [`PINNED_REFERENCES`] lists every production reference to those three /// functions in this crate, by file and line text. What the check catches: /// any new reference by name — a call through any path, a method call, a @@ -4230,28 +4238,32 @@ fn unsupported_layout_warnings_rewrites_known_codes_and_forwards_unknown_ones() /// Those stay a review matter: read the pristine source from the /// registry, never from a lock entry that might be Socket-hosted. const PINNED_REFERENCES: &[(&str, &str, &str)] = &[ + // `SecureRegistryClient::download`: the one `download` behind every + // gem that is installed or built as fetched, and behind its checksum. ( - "patch/gem_refresh.rs", + "vendor/registry_fetch.rs", "download", - "crate::vendor::registry_fetch::download(&client, url).await", + "download(client, url.as_str()).await", ), - // The source gem of a native-extension rebuild, and a gem its build - // lacks: the registry's compact index document, then the archive it - // names by sha256. Never a URL or a hash out of the lock. ( - "patch/gem_source.rs", + "patch/gem_refresh.rs", "download", - "use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient};", + "Source::Registry(registry) => registry.download(url).await,", ), + // The source gem of a native-extension rebuild, and a gem its build + // lacks: the registry's compact index document, then the archive it + // names by sha256 (`GemSource::get`, the module's one request). Never + // a URL or a hash out of the lock. ( "patch/gem_source.rs", "download", - "let bytes = download(self.http.get_or_init(build_registry_client), &url).await?;", + "registry.download(url).await", ), + // `rubygems_sha256`: the compact index document of the gem's name. ( - "patch/gem_source.rs", + "patch/redirect/upstream/client.rs", "download", - "let bytes = download(self.http.get_or_init(build_registry_client), &url).await?;", + "registry.download(&url).await?", ), ( "patch/redirect/upstream/client.rs", diff --git a/crates/socket-patch-core/src/vendor/registry_fetch.rs b/crates/socket-patch-core/src/vendor/registry_fetch.rs index cf119c9ac..6520840f8 100644 --- a/crates/socket-patch-core/src/vendor/registry_fetch.rs +++ b/crates/socket-patch-core/src/vendor/registry_fetch.rs @@ -968,6 +968,75 @@ async fn download_unredacted(client: &reqwest::Client, url: &str) -> Result, +} + +impl Default for SecureRegistryClient { + fn default() -> Self { + Self::new() + } +} + +impl SecureRegistryClient { + pub fn new() -> Self { + SecureRegistryClient { + https: Self::builder() + .build() + .expect("failed to build registry HTTP client"), + direct: std::sync::OnceLock::new(), + } + } + + fn builder() -> reqwest::ClientBuilder { + registry_client_builder(USER_AGENT).redirect(crate::utils::http::no_downgrade_redirects()) + } + + /// [`download`] of `url`, over a transport nobody can rewrite. + pub(crate) async fn download(&self, url: &str) -> Result, String> { + let url = crate::utils::http::secure_url(url) + .map_err(|why| format!("no request is made: {why}"))?; + // `secure_url` passes https and loopback http alone, and no + // redirect leads from https to http: the proxied client never + // speaks plain http, and the direct one never uses a proxy. + let client = if url.scheme() == "https" { + &self.https + } else { + self.direct.get_or_init(|| { + Self::builder() + .no_proxy() + .build() + .expect("failed to build registry HTTP client") + }) + }; + download(client, url.as_str()).await + } +} + /// Verify archive bytes against lock-recorded integrity. Berry cache checksums /// require server metadata because they identify a different archive format. pub fn artifact_matches_integrity( @@ -2564,6 +2633,120 @@ mod tests { assert!(err.contains("sha256"), "{err}"); } + /// The client for bytes that are built or installed makes no request to + /// a plain-http host that is not this machine, and follows no redirect + /// to one. A loopback registry (a local mirror, the hermetic tests) is + /// served, redirects between its own URLs included, up to the one hop + /// limit; and the URL that is fetched is the one that was judged, + /// however its scheme is written. + /// + /// Every URL here names this machine, the refused ones too (`0.0.0.0` + /// is no loopback address to the rule, and no packet for it leaves the + /// host): the test stays off the network even if the rule broke. + #[tokio::test] + async fn the_secure_client_talks_https_or_loopback_only() { + use wiremock::matchers::{method, path, path_regex}; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + const ELSEWHERE: &str = "http://0.0.0.0:9"; + let server = MockServer::start().await; + let serve = |from: &'static str, response: ResponseTemplate| { + Mock::given(method("GET")) + .and(path(from)) + .respond_with(response) + .mount(&server) + }; + serve( + "/gems/a-1.gem", + ResponseTemplate::new(200).set_body_bytes(b"the gem".to_vec()), + ) + .await; + serve( + "/moved/a-1.gem", + ResponseTemplate::new(302).insert_header("location", "/gems/a-1.gem"), + ) + .await; + serve( + "/away/a-1.gem", + ResponseTemplate::new(302) + .insert_header("location", format!("{ELSEWHERE}/gems/a-1.gem").as_str()), + ) + .await; + // `/chain//`: redirect `i` of `n`, the last of which leads to + // the gem. + Mock::given(method("GET")) + .and(path_regex(r"^/chain/\d+/\d+$")) + .respond_with(|request: &Request| { + let numbers: Vec = request + .url + .path() + .split('/') + .filter_map(|part| part.parse().ok()) + .collect(); + let (hops, at) = (numbers[0], numbers[1]); + let next = if at < hops { + format!("/chain/{hops}/{}", at + 1) + } else { + "/gems/a-1.gem".to_string() + }; + ResponseTemplate::new(302).insert_header("location", next.as_str()) + }) + .mount(&server) + .await; + let client = SecureRegistryClient::new(); + let base = server.uri(); + assert!(base.starts_with("http://127.0.0.1:"), "{base}"); + + let shouted = base.replace("http://", "HTTP://"); + for served in [ + format!("{base}/gems/a-1.gem"), + format!("{base}/moved/a-1.gem"), + // The scheme in capitals: the same URL to the gate and the fetch. + format!("{shouted}/gems/a-1.gem"), + // Ten redirects, the limit: `/chain/10/1` … `/chain/10/10`, then + // the gem. + format!("{base}/chain/10/1"), + ] { + assert_eq!( + client.download(&served).await.unwrap(), + b"the gem", + "{served}" + ); + } + let why = client + .download(&format!("{base}/chain/11/1")) + .await + .unwrap_err(); + assert!(why.contains("too many redirects"), "{why}"); + let why = client + .download(&format!("{base}/away/a-1.gem")) + .await + .unwrap_err(); + assert!( + why.contains("refusing a redirect") && why.contains("0.0.0.0"), + "{why}" + ); + + // Refused before any request. + let asked_before = server.received_requests().await.unwrap().len(); + for url in [ + format!("{ELSEWHERE}/gems/a-1.gem"), + "http://user:hunter2@0.0.0.0:9/gems/a-1.gem".to_string(), + "ftp://127.0.0.1/gems/a-1.gem".to_string(), + base.replace("http://", ""), + ] { + let why = client.download(&url).await.unwrap_err(); + assert!( + why.contains("no request is made") && why.contains("is not an https URL"), + "{why}" + ); + assert!(!why.contains("hunter2"), "{why}"); + } + assert_eq!( + server.received_requests().await.unwrap().len(), + asked_before + ); + } + /// Every `download` error quotes its URL redacted: a refused scheme, an /// HTTP error status and a transport failure (reqwest's own text). #[tokio::test] diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5607dcfc8..317516802 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2020,7 +2020,11 @@ share must be identical. With no usable archive (`--offline` and nothing cached, or when the build from it fails, a gem RubyGems built is rebuilt from its installed tree instead, as in 5.1.0, and a precompiled gem is refused with `native_extensions_unsupported`: run `apply` once with network access, or put the source gem in that `cache/` directory. If you install from a -mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The JRuby (`-java`) build of a gem ships +mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The mirror must be reached over `https` +(plain `http` is accepted only for a mirror on the same machine, such as `http://localhost:9292`, +and such a request never goes through a proxy): the gem's build scripts run, so its archive and +checksum are not fetched over a connection someone else could rewrite. Credentials in the URL +are never printed. The JRuby (`-java`) build of a gem ships jars and is always refused for such a patch. A gem that builds a library into its own directory and loads it from there (an FFI gem such as