Skip to content
Merged
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
27 changes: 18 additions & 9 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

262 changes: 218 additions & 44 deletions crates/socket-patch-cli/src/commands/gem_refresh.rs

Large diffs are not rendered by default.

87 changes: 84 additions & 3 deletions crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<String>::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.
Expand Down Expand Up @@ -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() {
Expand All @@ -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");
Expand Down Expand Up @@ -1895,14 +1932,28 @@ 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"]);
}
}
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
Expand Down Expand Up @@ -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() {
Expand All @@ -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",
Expand All @@ -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<String> = proxy
.received_requests()
.await
.unwrap()
.iter()
.map(|request| request.url.to_string())
.collect();
assert_eq!(
through_proxy,
Vec::<String>::new(),
"a loopback request went through the proxy"
);
let asked: Vec<String> = server
.received_requests()
Expand Down
173 changes: 171 additions & 2 deletions crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading