Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

71 changes: 58 additions & 13 deletions crates/socket-patch-cli/src/commands/gem_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1108,8 +1108,11 @@ enum NoRecord {
NotServed,
}

/// What judges the installed copies a hosted unwind's archive check cannot
/// (#2092): those whose gem home keeps no readable `<home>/cache/<leaf>.gem`.
/// What judges the installed copies a hosted unwind's archive check cannot:
/// those whose gem home keeps no readable `<home>/cache/<leaf>.gem` (#2092),
/// and those of a build nothing gives the upstream sha256 of, so that its
/// archive says nothing (#2230: a gem from another remote, or `--offline`
/// or a registry error, under a lock without `CHECKSUMS`).
/// Nothing else tells such a copy from the patched build the hosted scan
/// may have replaced it with, and no later `bundle install` replaces it.
/// Each is judged on its own files, by the record of a patch its gem was
Expand Down Expand Up @@ -1157,8 +1160,11 @@ impl PinJudge<'_> {
}

/// The installed copies of `builds` (`(purl, leaf)`, the builds the
/// restored lock names for the pinned gems) with no readable archive in
/// their gem home: those that hold a pinned patch (stale), and those nothing
/// restored lock names for the pinned gems) that no archive judges:
/// one with no readable archive in its gem home, and one of a build
/// that is not in `by_archive` (the leaves the archive check has an
/// upstream sha256 for, or reports itself). Of those: the copies that
/// hold a pinned patch (stale), and those nothing
/// could judge, each with why (the reason completes "could not be
/// checked against the upstream gem (…)"). A copy is neither when a
/// record judged it and found files that are not its patch's, and no
Expand All @@ -1167,17 +1173,25 @@ impl PinJudge<'_> {
async fn probe(
&mut self,
builds: &[(String, String)],
by_archive: &BTreeSet<String>,
) -> (Vec<StaleGem>, Vec<(StaleGem, String)>) {
use socket_patch_core::vendor::file_sha256_hex;
use socket_patch_core::vex::verify::judge_installed_record;

let (mut stale, mut unjudged) = (Vec::new(), Vec::new());
for copy in installed_builds(self.common, builds).await {
// The same test as `stale_after_restore`'s: an archive it can
// hash is its to judge the copy by.
if file_sha256_hex(&copy.archive).await.is_some() {
// hash is its to judge the copy by, when it has the upstream
// sha256 to hold that archive against.
let archived = file_sha256_hex(&copy.archive).await.is_some();
if archived && by_archive.contains(&copy.leaf) {
continue;
}
let unjudged_by_archive = if archived {
"nothing gives the sha256 of its upstream gem"
} else {
"its gem home has no archive of it"
};
// Why the copy is not known to be free of a pinned patch: a pin
// with no record, or a record whose files could not be read.
let (mut patched, mut open) = (false, None);
Expand Down Expand Up @@ -1216,7 +1230,7 @@ impl PinJudge<'_> {
match (patched, open) {
(true, _) => stale.push(gem),
(false, Some(why)) => {
unjudged.push((gem, format!("its gem home has no archive of it and {why}")))
unjudged.push((gem, format!("{unjudged_by_archive} and {why}")))
}
(false, None) => {}
}
Expand Down Expand Up @@ -1484,11 +1498,13 @@ async fn refresh_restored(
if shas.is_empty() && unverified.is_empty() && judged.is_empty() && pinned.is_empty() {
return RestoreRefresh::default();
}
// A hosted unwind's copies with no archive to judge them by: stale
// when they hold a pinned patch, reported when no record says (#2092).
// A hosted unwind's copies that no archive judges (none in the gem
// home, #2092; or no upstream sha256 to hold it against, #2230): stale
// when they hold a pinned patch, reported when no record says.
let pinned_builds = build_leaves(&named, |purl| pinned.iter().any(|p| p == purl));
let by_archive: BTreeSet<String> = shas.keys().chain(unverified.keys()).cloned().collect();
let (pin_stale, no_record) = match &mut pin_judge {
Some(judge) => judge.probe(&pinned_builds).await,
Some(judge) => judge.probe(&pinned_builds, &by_archive).await,
None => Default::default(),
};
let pin_stale_any = !pin_stale.is_empty();
Expand Down Expand Up @@ -1543,7 +1559,7 @@ async fn refresh_restored(
let mut still = stale_after_restore(common, &named, &shas, &judged, scope).await;
// (A copy no record judged is not one the pass could change.)
if let Some(judge) = pin_judge.as_mut().filter(|_| pin_stale_any) {
still.extend(judge.probe(&pinned_builds).await.0);
still.extend(judge.probe(&pinned_builds, &by_archive).await.0);
}
still
} else {
Expand Down Expand Up @@ -2055,7 +2071,11 @@ mod tests {
vec!["uuid-a".to_string(), "uuid-b".to_string()],
)]);
// `--offline`: only the records seeded below are there to judge by.
let probe = |tmp: &tempfile::TempDir, fetched: Vec<(&str, Option<PatchRecord>)>| {
// `sha_known`: whether the archive check has the upstream sha256 of
// the build (a `CHECKSUMS` entry, or the registry's answer).
let probe_as = |tmp: &tempfile::TempDir,
fetched: Vec<(&str, Option<PatchRecord>)>,
sha_known: bool| {
let fetched = fetched
.into_iter()
.map(|(uuid, record)| (uuid, record.ok_or(NoRecord::NotServed)));
Expand All @@ -2078,11 +2098,16 @@ mod tests {
unreachable: false,
};
let builds = [(PURL.to_string(), "rack-1.0.0".to_string())];
let (stale, unjudged) = judge.probe(&builds).await;
let by_archive: BTreeSet<String> = sha_known
.then(|| "rack-1.0.0".to_string())
.into_iter()
.collect();
let (stale, unjudged) = judge.probe(&builds, &by_archive).await;
assert!(api.get().is_none(), "an offline probe builds no client");
(stale.len(), unjudged)
}
};
let probe = |tmp: &tempfile::TempDir, fetched| probe_as(tmp, fetched, true);
let (a, b) = (record("uuid-a", "patch a\n"), record("uuid-b", "patch b\n"));
let both = || vec![("uuid-a", Some(a.clone())), ("uuid-b", Some(b.clone()))];

Expand Down Expand Up @@ -2138,6 +2163,26 @@ mod tests {
let tmp = project("patch b\n", true);
let (stale, unjudged) = probe(&tmp, both()).await;
assert_eq!((stale, unjudged.len()), (0, 0));

// #2230: unless nothing gives the upstream sha256 to hold that
// archive against (a gem from a private mirror under a lock with
// no `CHECKSUMS`). The copy is then judged on its files like one
// with no archive: the patched build is stale, ...
let (stale, unjudged) = probe_as(&tmp, both(), false).await;
assert_eq!((stale, unjudged.len()), (1, 0));
// ... the upstream build is not, ...
let tmp = project("upstream\n", true);
let (stale, unjudged) = probe_as(&tmp, both(), false).await;
assert_eq!((stale, unjudged.len()), (0, 0));
// ... and one no record judges is reported, with a reason that
// does not say the archive is missing.
let (stale, unjudged) = probe_as(&tmp, vec![("uuid-b", Some(b.clone()))], false).await;
assert_eq!((stale, unjudged.len()), (0, 1));
assert_eq!(
unjudged[0].1,
"nothing gives the sha256 of its upstream gem and `--offline` is set, so its patch \
record was not fetched"
);
}

/// A project-local copy the refresh could not fix says why and names
Expand Down
125 changes: 125 additions & 0 deletions crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5546,6 +5546,131 @@ async fn gem_hosted_unwind_restores_an_install_whose_home_cache_was_pruned() {
}
}

/// #2230 against a real Bundler: the project's `Gemfile` names a private
/// gem server as its source, so the lock (with `CHECKSUMS`) resolves the gem
/// from that remote, not rubygems.org. The unwind refuses to guess the
/// upstream sha256 and names `SOCKET_RUBYGEMS_URL`; with the setting naming
/// that server it reads the checksum from the server's compact index, hands
/// the pre-scan pair back byte for byte and puts the upstream gem back, so
/// `bundle install` and `bundle pristine` both pass on the restored lock.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "host capstone: shells out to a real ruby/gem/bundler (CHECKSUMS lock: >= 2.6); \
the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"]
async fn gem_hosted_unwind_restores_a_gem_from_a_private_gem_server() {
let Some(fx) = redirect_scanned_project(
"mirror-unwind",
Spelling::Gemfile,
true,
true,
None,
Driver::ScanVex,
)
.await
else {
return;
};
let api = fx._server.uri();
let upstream = format!("{api}/upstream");
assert!(
String::from_utf8_lossy(&fx.pristine_lock).contains(&format!("remote: {upstream}/")),
"premise: the lock resolves the gem from the gem server"
);
for command in ["rollback", "remove"] {
let dir = stage_fresh_checkout(&fx, &format!("mirror-{command}"));
let install = bundle(&dir, &["install"]);
assert!(
install.status.success(),
"{command}: hosted install:\n{}",
String::from_utf8_lossy(&install.stderr)
);
let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb");
assert_eq!(
std::fs::read(&installed).unwrap(),
fx.patched,
"{command}: the patched gem is installed (test premise)"
);
let pair = || {
(
std::fs::read(dir.join(fx.gemfile_name)).unwrap(),
std::fs::read(dir.join(fx.lock_name)).unwrap(),
)
};
let hosted = pair();

let cwd = dir.to_str().expect("utf8 tmp path");
let mut argv = vec![command, PURL, "--json", "--cwd", cwd];
if command == "remove" {
argv.push("--yes");
}
argv.extend([
"--api-url",
&api,
"--org",
ORG,
"--api-token",
"fake",
"--patch-server-url",
&api,
]);
// The registry setting names another server: refused, nothing
// changed, and the refusal names the setting that works.
let elsewhere = format!("{api}/elsewhere");
let (code, stdout, stderr) =
run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &elsewhere)]);
assert_ne!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}");
assert!(
format!("{stdout}{stderr}").contains(&format!("`SOCKET_RUBYGEMS_URL={upstream}`")),
"{command}: the refusal names the setting:\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert!(
pair() == hosted,
"{command}: a refused unwind changes nothing"
);

let (code, stdout, stderr) =
run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]);
let env: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
panic!("{command}: not JSON: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}")
});
assert_eq!(code, 0, "{command}: {env}\nstderr:\n{stderr}");
let (gemfile, lock) = pair();
assert_eq!(
String::from_utf8_lossy(&gemfile),
String::from_utf8_lossy(&fx.pristine_gemfile),
"{command}: the Gemfile is the pre-scan one"
);
assert_eq!(
String::from_utf8_lossy(&lock),
String::from_utf8_lossy(&fx.pristine_lock),
"{command}: the lock is the pre-scan one"
);
assert_eq!(
std::fs::read(&installed).unwrap(),
orig_lib().into_bytes(),
"{command}: the installed gem is the upstream one again: {env}"
);
assert!(
!env.to_string().contains("upstream_gem_stale_install"),
"{command}: {env}"
);
// The restored project installs and reinstalls as it is.
for args in [&["install"][..], &["pristine"][..]] {
let run = bundle(&dir, args);
assert!(
run.status.success(),
"{command}: bundle {args:?} after the unwind:\n{}\n{}",
String::from_utf8_lossy(&run.stdout),
String::from_utf8_lossy(&run.stderr)
);
assert_eq!(
std::fs::read(&installed).unwrap(),
orig_lib().into_bytes(),
"{command}: bundle {args:?} keeps the upstream bytes"
);
}
}
}

/// A warm project: the pre-redirect pair installed from the mock upstream
/// into the project's `vendor/bundle`, as on a developer machine or a CI
/// job with a restored bundle cache.
Expand Down
Loading
Loading