Repository navigation
Description
[agent] Found by the architecture refactor routine while reading the two gem merges new on main (#2497, #2499). main is at cd7c5c5.
The problem
A precompiled platform gem (nokogiri-1.18.9-x86_64-linux-gnu) that agent mode patched through the ruby gem's patch can stop working with socket-patch on the day the platform gem's own patch is published.
The patch of a platform gem is built from the patch of the ruby gem, so there is a window where only the ruby gem's patch is on offer (docs/ecosystems.md: "none is published for it yet, its patched gem is still being built"). In that window scan --mode agent patches the precompiled copy by a build of the source gem, and apply --check and vex attest it. The next scan after the platform gem's patch appears records that patch. When the ruby gem's patch changed a file the platform gem does not pack, then from that scan on, with no change by the user:
scanexits 1 (apply_failed, "File hash does not match expected value");apply --checkexits 1 and says "patch not applied (an installed copy is still unpatched) … Runsocket-patch apply";applyexits 1 with the same hash mismatch and names no remedy;vexexits 1 with no statement, for a copy it attestednot_affectedthe day before, and says the copies "still hold their original files … runsocket-patch apply";rollbackexits 1 ("holds neither the patched nor the original content").
The copy still runs the patched code, so nothing is exposed. The harm is a CI that goes red by itself, a VEX document that can no longer be produced, and two messages that send the user to a command that fails.
Such files are common in a native gem. The ruby gem of nokogiri 1.18.9 packs 55 files its x86_64-linux-gnu gem does not: 42 under gumbo-parser/src/ (the HTML5 parser's sources), 11 under patches/ and 2 under ports/archives/. A fix to the HTML5 parser changes one of the first, and a fix that replaces a libxml2 patch changes one of the second.
Evidence on main
The real flow. A stand-in patch API on loopback, the precompiled copy and the stand-in Ruby of tests/e2e_gem_native_ext_build.rs. Day 1 the API offers the ruby gem's patch alone; day 2 it also offers the patch of ?platform=x86_64-linux, which brings the C source and both .so files. Each day runs scan --mode agent --yes --json, then apply --check, vex, apply, rollback. Day 1 is exit 0, exit 0 and not_affected in every row.
| Day 1 by | Day 2 by | Beside the C source, the ruby gem's patch | Day 2 scan |
apply --check |
vex |
apply |
rollback |
|---|---|---|---|---|---|---|---|
main |
main |
changes patches/0001-base.patch, which the copy does not hold |
1 apply_failed |
1 not_applied |
1, no statement | 1 | 1 |
main |
main |
changes that file and adds patches/0100-CVE-test.patch |
1 | 1 | 1 | 1 | 1 |
| 5.2.0 | main |
the same two | 1 | 1 | 1 | 1 | 1 |
| 5.2.0 | 5.2.0 | the same two | 1 | 1 | 1 | 1 | 1 |
main |
main |
nothing else | 0 applied |
0 | not_affected |
0 | 0, the copy as installed |
| 5.2.0 | 5.2.0 | nothing else | 1 | 1 | 1 | 1 | 1 |
main |
main |
adds patches/0100-CVE-test.patch only |
0 applied |
0 | not_affected |
0 | 0, the added file stays |
Day 2 on main, second row:
$ socket-patch scan --mode agent --yes --json … # exit 1
{"action":"downloaded","purl":"pkg:gem/sp_native@1.0.0?platform=x86_64-linux"}
{"action":"failed","purl":"pkg:gem/sp_native@1.0.0?platform=x86_64-linux","errorCode":"apply_failed",
"error":"Cannot apply patch: lib/sp_native/3.4/sp_native.so - File hash does not match expected value"}
$ socket-patch apply --check # exit 1
Error: Patches are OUT OF SYNC:
pkg:gem/sp_native@1.0.0?platform=x86_64-linux: patch not applied (an installed copy is still unpatched)
Run `socket-patch apply` to regenerate them.
$ socket-patch vex --product pkg:generic/app@1 # exit 1
Error: No applied patches with vulnerability metadata to attest.
1 of the patched packages are not installed yet: the installed copies still hold their original files. … run `socket-patch apply` (agent-mode patches), then run `socket-patch vex` again.
$ socket-patch apply --offline # exit 1
Error: Failed to patch pkg:gem/sp_native@1.0.0?platform=x86_64-linux: Cannot apply patch: lib/sp_native/3.4/sp_native.so - File hash does not match expected value
$ socket-patch rollback --offline # exit 1
pkg:gem/sp_native@1.0.0?platform=x86_64-linux: Cannot roll back: lib/sp_native/3.4/sp_native.so - File holds neither the patched nor the original content. Cannot safely roll back.
Run `bundle pristine sp_native` (or `gem pristine sp_native`) to get the published files back, then roll back again.
A failing test. The test below, added to tests/e2e_gem_native_ext_build.rs, passes its first case (the ruby gem's record changes the C source only) and fails its second (the record of the second row) on main:
$ cargo test -p socket-patch-cli --test e2e_gem_native_ext_build -- probe_platform_record_after_a_ruby_record_graft
assertion `left == right` failed: the ruby gem's record adds build inputs: true: day 2 apply fails on the copy day 1 patched and attested:
"purl": "pkg:gem/sp_native@1.0.0?platform=x86_64-linux",
"errorCode": "apply_failed",
"error": "Cannot apply patch: lib/sp_native/3.4/sp_native.so - File hash does not match expected value",
"cause": "hash_mismatch"
left: 1
right: 0
Why
Once the manifest holds a record for the copy's own platform, that record is the copy's only one (own_platform_record, the contract), so the ruby gem's record, whose build the copy holds, is no longer read on it. The platform record brings the binary that build replaced, and finds neither of its contents there.
#2499 (dbde834) taught apply and rollback to put that binary back from the build's backup first, which is why the fifth row passes on main and the sixth fails on 5.2.0. It skips a backup that lists build inputs the earlier record changed and the copy did not hold (replaced_binaries, the contract), because putting the build back drops the list rollback reads. In the rows that fail the backup holds absentFiles: ["patches/0001-base.patch"]; a file the record adds is not listed. That rule was written for a build 5.2.0 made for the platform record itself. A build made for the ruby gem's record is the case it leaves failing.
The tool can undo that build. From the day-2 state of the second row:
$ socket-patch remove 'pkg:gem/sp_native@1.0.0?platform=ruby' --yes --offline # exit 0, the copy is as installed
$ socket-patch apply --offline # exit 0, the platform record applied
No message names that step.
The last row is the other side of the same gap. The put-back drops the build's marker and backup, and the file the ruby gem's record added has no reader left: that record is package_not_installed on the copy. rollback then exits 0, removes both records from the manifest, and leaves patches/0100-CVE-test.patch in the gem.
Planned fix
In the apply of a record that brings a precompiled copy its binaries: when the copy holds a build made for the ruby gem's record and the manifest still holds that record, roll that record back on the copy first, as remove does (the binary back, the build inputs it wrote into the copy removed, the sources restored), then apply the platform record whole. Keep #2499's conditions: nothing is undone unless the platform record then applies. Where it cannot be done (the ruby gem's record is gone, a file holds content neither record knows), fail with a message that names socket-patch remove <the ruby gem's purl> or gem pristine, and stop apply --check and vex from saying the copy is unpatched. rollback takes the same step. The test above becomes the regression test, with a case for the last row and a rollback arm. About 80 production lines in patch/gem_ext.rs.
A maintainer may prefer the other reading: while the copy holds the ruby gem's build, the ruby gem's record stays the copy's record, and the platform record waits for a fresh install. That changes the contract's "only record" sentence, so it wants a word.
Also seen
apply --forcefrom the day-2 state of the second row exits 0 and the copy then checks clean. Arollbackafter it exits 0, removes both records, and leaves bothpatches/files in the copy.- After the fifth row the ruby gem's record stays in the manifest as
package_not_installed, as the contract says.
Not run
A real Ruby and a real gem (the copy and the build are the suite's stand-ins); a platform record from the patch service; macOS and Windows.
The test
/// A precompiled copy patched through the ruby gem's record, then the
/// manifest gains the record of the copy's own platform, which brings its
/// binaries.
#[cfg(unix)]
#[test]
fn probe_platform_record_after_a_ruby_record_graft() {
for adds_build_inputs in [false, true] {
let case = format!("the ruby gem's record adds build inputs: {adds_build_inputs}");
let (_tmp, proj, gem_dir) = fake_precompiled_gem(true);
let socket = proj.join(".socket");
let ruby_key = format!("{PURL}?platform=ruby");
let own_key = format!("{PURL}?platform=x86_64-linux");
let (c1, c2) = (c_source(1), c_source(2));
// Day 1: the patch service offers the ruby gem's patch alone.
let mut entries: Vec<RecordFile<'_>> = vec[(C_KEY, Some(&c1), &c2)];
if adds_build_inputs {
entries.push(("patches/0001-base.patch", Some(BASE_PATCH), "base, fixed\n"));
entries.push(("patches/0100-CVE-test.patch", None, "the fix\n"));
}
write_record(&socket, &ruby_key, &entries);
let ruby = FakeRuby::new();
ruby.serve_source_gem(&c_source(1));
let run = |args: &[&str]| ruby.run(&proj, args, &[]);
let tree_before = walk_files(&proj.join("vendor"));
let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]);
assert_eq!(code, 0, "{case}: day 1 apply:\n{stdout}\n{stderr}");
let (code, stdout, _) = run(&["apply", "--check", "--json"]);
assert_eq!(code, 0, "{case}: day 1 check: {stdout}");
assert!(vex_attests(run), "{case}: day 1 vex attests");
// Day 2: the platform gem's patch is published, and a scan records
// it beside the ruby gem's.
let (p33, p34) = (prebuilt("3.3"), prebuilt("3.4"));
let own: Vec<RecordFile<'_>> = vec[
(C_KEY, Some(&c1), &c2),
("lib/sp_native/3.3/sp_native.so", Some(&p33), "\x7fELF patched for 3.3"),
("lib/sp_native/3.4/sp_native.so", Some(&p34), "\x7fELF patched for 3.4"),
];
let mut manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(socket.join("manifest.json")).unwrap())
.unwrap();
let mut files = serde_json::Map::new();
for (key, before, after) in &own {
let before = before.unwrap();
write_blob(&socket, &git_sha256(before.as_bytes()), before.as_bytes());
write_blob(&socket, &git_sha256(after.as_bytes()), after.as_bytes());
files.insert(
key.to_string(),
serde_json::json!({
"beforeHash": git_sha256(before.as_bytes()),
"afterHash": git_sha256(after.as_bytes()),
}),
);
}
let mut record = manifest["patches"][&ruby_key].clone();
record["uuid"] = serde_json::json!("29962996-2996-4996-8996-299629962996");
record["files"] = serde_json::Value::Object(files);
manifest["patches"][&own_key] = record;
std::fs::write(
socket.join("manifest.json"),
serde_json::to_string_pretty(&manifest).unwrap(),
)
.unwrap();
let (check, check_out, _) = run(&["apply", "--check", "--json"]);
let attests = vex_attests(run);
let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]);
let (rb, rb_out, rb_err) = run(&["rollback", "--json", "--offline"]);
let restored = tree_diff(&tree_before, &walk_files(&proj.join("vendor")));
eprintln!(
"PROBE {case}\n check: {check} {check_out}\n vex attests: {attests}\n apply: {code} \
{stdout}\n {stderr}\n rollback: {rb} {rb_out}\n {rb_err}\n tree vs day 0: \
{restored:?}\n 3.4: {:?}",
std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap()
);
assert_eq!(
code, 0,
"{case}: day 2 apply fails on the copy day 1 patched and attested:\n{stdout}\n{stderr}"
);
assert_eq!(rb, 0, "{case}: day 2 rollback:\n{rb_out}\n{rb_err}");
}
}The real flow
- The copy:
fake_precompiled_gem(true)of the suite (sp_native-1.0.0-x86_64-linux, a.sofor Ruby 3.3 and 3.4, the C source, the source gem in the home'scache/), and itsFakeRubyscript alone onPATH. - The API: a loopback server that answers
POST /v0/orgs/<org>/patches/batch,GET …/patches/by-package/<purl>andGET …/patches/view/<uuid>(files withblobContentandbeforeBlobContent). Day 1 it lists one patch underpkg:gem/sp_native@1.0.0?platform=ruby; day 2 it also lists one under?platform=x86_64-linuxwhose files areext/sp_native/sp_native.c,lib/sp_native/3.3/sp_native.soandlib/sp_native/3.4/sp_native.so. - The runs:
scan --mode agent --yes --json --api-url http://127.0.0.1:<port> --api-token <any> --org <org>, withSOCKET_RUBYGEMS_URL=http://127.0.0.1:9,SOCKET_TELEMETRY_DISABLED=1,SOCKET_NO_CONFIG=1and an emptyHOME. - 5.2.0:
npm i @socketsecurity/socket-patch@5.2.0. - nokogiri's file lists:
gem fetch nokogiri -v 1.18.9 --platform x86_64-linux-gnuand--platform ruby, then the names in eachdata.tar.gz.
Generated by Claude Code
Activity
refactor: L206 filed as #2512 (platform gem record)