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
16 changes: 10 additions & 6 deletions crates/socket-patch-cli/src/commands/scan/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ pub(crate) struct LockfileSupplement {
/// packages included), kept so the hosted-wiring probes reuse it instead
/// of re-parsing every project lockfile. Empty for global scans.
pub(crate) entries: Vec<LockfileEntry>,
/// The gems the Bundler lock resolves only as precompiled platform
/// builds, as `pkg:gem/<name>@<version>`. `entries` leaves them out,
/// in every mode, and the lock names them all the same: with
/// `entries` they are what the project's lockfiles resolve.
pub(crate) platform_gems: Vec<String>,
/// npm layouts the lockfile inventory REFUSED (Plug'n'Play loaders).
/// Scan surfaces these as refusal warnings: under PnP the installed-tree
/// crawl is empty too, so otherwise the project scans as a silent no-op.
Expand Down Expand Up @@ -76,20 +81,19 @@ pub(crate) async fn lockfile_supplement(
let locks = ctx.locks().await;
out.unsupported = locks.unsupported.clone();
let entries = &locks.entries;
let platform_gems = if hosted {
ctx.gem_platform_only_purls().await
} else {
Vec::new()
};
let platform_gems = ctx.gem_platform_only_purls().await;
if entries.is_empty() && platform_gems.is_empty() {
return out;
}
// Only a hosted supplement names a platform-only gem that has no
// installed copy (see above).
let resolved = entries
.iter()
.map(|entry| entry.purl.as_str())
.chain(platform_gems.iter().map(String::as_str));
.chain(platform_gems.iter().filter(|_| hosted).map(String::as_str));
(out.packages, out.purls) = lockfile_only_packages(resolved, crawled, only, &common.cwd);
out.entries = entries.clone();
out.platform_gems = platform_gems;
out
}

Expand Down
23 changes: 13 additions & 10 deletions crates/socket-patch-cli/src/commands/scan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3796,16 +3796,19 @@ async fn scan_project(
// not use (another project's gem in a shared gem home, an extraneous
// `node_modules` entry): the mode reports it, and the report does not
// count it as left to patch. A requirements file may pin only the
// direct dependencies, so PyPI packages always count.
let locked: HashSet<PurlKey> = lockfile_only
.entries
.iter()
.map(|entry| PurlKey::new(&entry.purl))
.collect();
let complete_locks: HashSet<Ecosystem> = lockfile_only
.entries
.iter()
.filter_map(|entry| Ecosystem::from_purl(&entry.purl))
// direct dependencies, so PyPI packages always count. The lockfile
// inventory leaves out a gem the Bundler lock holds only as
// precompiled platform builds; the lock names it too.
let locked_purls = || {
lockfile_only
.entries
.iter()
.map(|entry| entry.purl.as_str())
.chain(lockfile_only.platform_gems.iter().map(String::as_str))
};
let locked: HashSet<PurlKey> = locked_purls().map(PurlKey::new).collect();
let complete_locks: HashSet<Ecosystem> = locked_purls()
.filter_map(Ecosystem::from_purl)
.filter(|eco| *eco != Ecosystem::Pypi)
.collect();
let in_project = |purl: &str| {
Expand Down
121 changes: 120 additions & 1 deletion crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
use std::path::{Path, PathBuf};

use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes;
use wiremock::matchers::{method, path, path_regex};
use wiremock::matchers::{body_string_contains, method, path, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[path = "common/mod.rs"]
Expand Down Expand Up @@ -2813,6 +2813,125 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() {
}
}

/// A lock that names the gem only as platform builds, beside a plain
/// gem, and a patch without a patched build for every locked platform:
/// the run refuses the gem. The lock still resolves it, so the closing
/// totals count its advisory as left to patch, in hosted mode (which
/// reads the gem from the lock alone) and in vendored mode (which reads
/// the installed platform copy).
#[tokio::test(flavor = "multi_thread")]
async fn refused_platform_gem_is_counted_as_left_to_patch() {
const LEFT: &str =
"\n1 vulnerability left to patch: 1 is in packages this run did not patch.\n";
let arm_sha = sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM));
for mode in ["hosted", "vendored"] {
let server = MockServer::start().await;
// The lookup names the advisory the patch fixes, as the service
// does (the totals count advisories), and only for a run that
// asks about the gem.
Mock::given(method("POST"))
.and(path(format!("/v0/orgs/{ORG}/patches/batch")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"packages": [],
"canAccessPaidPatches": false,
})))
.with_priority(2)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path(format!("/v0/orgs/{ORG}/patches/batch")))
.and(body_string_contains(DEP))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"packages": [{
"purl": PURL,
"patches": [{
"uuid": UUID, "purl": PURL, "tier": "free",
"cveIds": [], "ghsaIds": [GHSA], "severity": "high",
"title": "gem stale-install fixture"
}]
}],
"canAccessPaidPatches": false,
})))
.with_priority(1)
.mount(&server)
.await;
mount_api_with(
&server,
None,
&sha256_of(&real_gem(PATCHED_LIB)),
&[(PLATFORM, arm_sha.clone())],
)
.await;
let tmp = tempfile::tempdir().unwrap();
let proj = tmp.path().join("proj");
std::fs::create_dir_all(&proj).unwrap();
let gemfile = format!(
"source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\ngem \
\"plain-probe-gem\", \"1.0.0\"\n"
);
// The plain gem makes the lock one that lists ruby-platform gems
// too, as every real lock does (nokogiri beside racc).
let lock = platform_lock(&"1".repeat(64), &"2".repeat(64))
.replace(" specs:\n", " specs:\n plain-probe-gem (1.0.0)\n")
.replace(
"DEPENDENCIES\n",
"DEPENDENCIES\n plain-probe-gem (= 1.0.0)\n",
);
assert!(
lock.contains(" plain-probe-gem (1.0.0)\n")
&& !lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")),
"the lock holds a plain gem, and {DEP} as platform builds only:\n{lock}"
);
std::fs::write(proj.join("Gemfile"), &gemfile).unwrap();
std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap();
if mode == "vendored" {
install_real_gem_for(&project_home(&proj), UPSTREAM_LIB, PLATFORM);
}

let uri = server.uri();
let (code, stdout, stderr) = common::run_with_env(
&proj,
&[
"scan",
"--mode",
mode,
"--yes",
"--cwd",
proj.to_str().unwrap(),
"--api-url",
uri.as_str(),
"--patch-server-url",
uri.as_str(),
"--org",
ORG,
"--api-token",
"fake",
],
&[],
);
assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}");
// The premise: the run refused the gem for a platform the patch
// has no build for.
let refusal = match mode {
"hosted" => format!("no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`"),
_ => format!("the patch service has no prebuilt platform gem of `{DEP}`"),
};
assert!(
stderr.contains(&refusal),
"{mode}: the run refuses the gem\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert_eq!(
std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(),
lock,
"{mode}: the lock is untouched"
);
assert!(
stdout.ends_with(LEFT),
"{mode}: the refused gem is left to patch\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
}
}

/// Human output of the run that refreshes: one progress line per kind,
/// no warning, and the committed archive in the files to commit.
#[tokio::test(flavor = "multi_thread")]
Expand Down
Loading