Repository navigation
Description
[agent] Filed by the scheduled architecture refactor routine. Register: L153, L154.
Kind: bug (a hazard fixed for one ecosystem, live in two others that have the same shared cache).
Problem
Agent mode patches a package where the build tool keeps it. For Cargo, Maven and NuGet that is a cache the whole machine shares and that the tool never cleans: $CARGO_HOME/registry/src, the Maven local repository (~/.m2/repository) and NuGet's global packages folder. A project that stops using a version leaves its copy there, still patched, and every other project on the machine that resolves that version builds against it. The manifest record holds the only before-blob that can restore the copy.
For Cargo this was fixed in one change (dcded7a, #1305), in the two places where a record is dropped while the copy stays patched:
scan --prune/--syncafter the lock moved off the version (Agent-mode cargoscan --sync/--prunedrops the manifest entry of a crate the lock no longer resolves but leaves its shared registry-cache copy patched, sorollbackcan't restore it (regression from #1205) #1278): the record is kept, with acargo_cache_patch_keptwarning that namesrollback <purl>;rollback/removeaftervendortook the package over (Cargo rollback after an agent→vendored takeover leaves the shared registry cache patched, reports success, and deletes the revert blobs #336): the cache copy is restored before the record goes.
PyPI got the first of the two later (fc18188, #2170, pypi_installed_patch_kept). The helper both call says why it stops there (ecosystem_dispatch.rs L37-L44): "Cargo is the one ecosystem whose patched copy outlives the project's use of it". That is not so. Maven's and NuGet's project crawls are scoped the same way Cargo's is (to what the poms reach, and to what obj/project.assets.json names), their caches are as shared, and neither has either keep. On main:
- After a version bump,
scan --sync/scan --prunedrops the record and deletes the blobs of the old version, with exit 0 and no warning. The old copy stays in the cache, patched. - After
vendortakes over a Maven patch that agent mode applied,rollbackandremove <purl>drop the record and delete the blobs, with exit 0. The jar in the local repository stays patched.
After either, nothing knows about the patched copy: rollback says "No patches in this project; nothing to roll back", and a second project on the machine that uses that version builds and runs the patched file with no .socket/ state and no list entry. The only way back is to delete the version's directory from the cache by hand, and nothing says so.
Evidence on main (d987721)
1. The prune, files only
The built binary and a stand-in patch API that knows no patch. Each project holds one agent-mode record whose cache copy is patched (apply --check: "Patches are in sync (1 patch checked)"), and has then moved to the next version, with both versions in the cache as the real tool leaves them:
| Project | Cache | scan --mode agent --sync |
Record, blobs | Old copy |
|---|---|---|---|---|
Cargo, itoa 1.0.11 → 1.0.12 (control) |
$CARGO_HOME/registry/src |
GC: kept pkg:cargo/itoa@1.0.11: the project no longer resolves it, but its copy in the shared Cargo registry cache is still patched …, naming socket-patch rollback pkg:cargo/itoa@1.0.11 |
kept, 2 | patched, restorable |
NuGet, Newtonsoft.Json 13.0.3 → 13.0.4 |
NUGET_PACKAGES |
GC: pruned 1 manifest entry and removed 2 orphan files (76 B). exit 0 |
gone, 0 | patched |
Maven, com.example:victim 1.0 → 1.1 |
MAVEN_REPO_LOCAL |
the same line, exit 0 | gone, 0 | patched |
Bundler with a shared gem home, octopoller 0.2.0 → 0.3.0 |
GEM_HOME |
nothing pruned ("Found 2 packages": the crawl lists every installed version) | kept, 2 | patched, restorable |
Gradle with mavenLocal(), com.example:victim 1.0 → 1.1 |
MAVEN_REPO_LOCAL |
nothing pruned ("Found 2 packages": the crawl walks the whole repository) | kept, 2 | patched, restorable |
Gradle, the same move, with and without a gradle.lockfile |
GRADLE_USER_HOME's files-2.1 |
nothing pruned ("Found 2 packages") | kept, 2 | patched, restorable |
scan --prune gives the same as --sync; under --json it is "status": "success" with a removed event (details.manifest: true), "gc": {"removedBlobs": 2, …} and no warnings. scan --sync --dry-run says [dry-run] GC would prune 1 manifest entry and remove 2 orphan files.
Without the prune the record does its job: in the same bumped projects rollback, rollback <purl>, remove <purl> and remove <uuid> restore the old copy in the cache and then drop the record (NuGet, Maven and Cargo alike). After the prune, for NuGet and Maven:
$ socket-patch rollback
No patches in this project; nothing to roll back.
$ socket-patch rollback -g
No patches in this project; nothing to roll back.
$ socket-patch apply --check
No patches to check.
1, with the real tools
Maven 3.9.11, commons-codec 1.15 from Maven Central, a stand-in patch API with one patch for it (it adds a marker entry to the jar):
$ mvn dependency:build-classpath # resolves commons-codec 1.15 into the local repository
$ socket-patch scan --mode agent
Patched 1 package, fixing 1 vulnerability (1 high).
$ socket-patch apply --check
Patches are in sync (1 patch checked).
$ sed -i 's#<version>1.15</version>#<version>1.16.0</version>#' pom.xml && mvn dependency:build-classpath
$ ls <repo>/commons-codec/commons-codec
1.15 1.16.0 …
$ socket-patch scan --sync
Found 1 package (1 maven)
No patches available for installed packages.
GC: pruned 1 manifest entry and removed 2 orphan files (691.14 KB).
$ socket-patch rollback
No patches in this project; nothing to roll back.
$ unzip -l <repo>/commons-codec/commons-codec/1.15/commons-codec-1.15.jar | grep -c SOCKET-PATCHED
1
A second project that depends on commons-codec 1.15, same local repository: mvn -o dependency:build-classpath puts that jar on its classpath, and an online mvn -U dependency:resolve leaves it as it is. The jar's .sha1 beside it holds the patched jar's digest (the apply rewrote it, as docs/ecosystems.md says), so Maven's own file agrees with the patched jar. In that project list says "No patches in this project" and apply --check "No patch manifest found".
.NET SDK 8.0.428 (the SDK image, no network, a folder feed with a package Victim at 1.0.0 and 1.1.0; the patch replaces lib/net8.0/Victim.dll with a build that prints PATCHED):
$ dotnet restore && dotnet run # Victim 1.0.0
vulnerable
$ socket-patch apply --offline
Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk
$ dotnet run
PATCHED
$ sed -i 's/Version="1.0.0"/Version="1.1.0"/' app.csproj && dotnet restore && dotnet run
vulnerable
$ ls $NUGET_PACKAGES/victim
1.0.0 1.1.0
$ socket-patch scan --sync
Found 1 package (1 nuget)
No patches available for installed packages.
GC: pruned 1 manifest entry and removed 2 orphan files (8.00 KB).
$ socket-patch rollback
No patches in this project; nothing to roll back.
$ cd ../sibling && dotnet restore && dotnet run # another project on Victim 1.0.0
PATCHED
$ socket-patch list
No patches in this project. Run `socket-patch scan`.
2. rollback / remove after vendor
The Maven reactor fixture of tests/vendor_jvm_cli.rs (fixture(root, Shape::Reactor, …)) with a record that replaces the jar whole, so the agent-mode apply runs from the blobs. Each row starts from apply --offline ("1 of 1 targeted patch applied", then apply --check: in sync) followed by vendor ("Vendored 1 package."):
| Then | Says | Record, blobs | Jar in the local repository |
|---|---|---|---|
rollback --yes |
Reverted vendoring for pkg:maven/org.example/foo@1.0, Removed 1 patch from manifest, Freed 616 B of unused blobs and archives, Note: 1 unwired package keeps its patched bytes in installed trees until the next package-manager install. exit 0 |
gone, 0 | patched |
remove <purl> --yes |
Reverted vendoring …, Removed 1 patch from manifest, Removed 4 unused blobs exit 0 |
gone, 0 | patched |
vendor --revert, then rollback --yes (control) |
Reverted 1 vendored package., then Rolled back 1 package |
gone, 0 | original |
After the first two, rollback says "No patches in this project; nothing to roll back." The note's "until the next package-manager install" does not hold for a local repository: Maven does not fetch a release it already has (the mvn -U run above).
Failing tests
NuGet, appended to crates/socket-patch-cli/tests/e2e_nuget.rs
/// The NuGet twin of `sync_keeps_entry_whose_shared_cache_copy_is_still_patched`
/// (e2e_cargo.rs, #1278): the project crawl looks up only the packages
/// `obj/project.assets.json` names, so a patched package the project moved
/// away from is "not crawled". Its copy in the global packages folder is
/// one NuGet never deletes and every project on the machine restores from,
/// and the record holds the only before-blob that can restore it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sync_keeps_entry_whose_global_packages_copy_is_still_patched() {
let server = start_proxy().await;
let proxy_url = server.uri();
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
let packages = dir.path().join("nuget-packages");
let orig: &[u8] = b"the vulnerable assembly\n";
let patched: &[u8] = b"the patched assembly!!!\n";
let dll = "lib/net6.0/Newtonsoft.Json.dll";
// 13.0.3 holds the agent-mode patch; the project has moved to 13.0.4.
for (version, bytes) in [("13.0.3", patched), ("13.0.4", orig)] {
let pkg = packages.join("newtonsoft.json").join(version);
std::fs::create_dir_all(pkg.join("lib/net6.0")).unwrap();
std::fs::write(pkg.join("newtonsoft.json.nuspec"), "<package/>").unwrap();
std::fs::write(pkg.join(dll), bytes).unwrap();
}
std::fs::create_dir_all(project.join("obj")).unwrap();
std::fs::write(project.join("app.csproj"), "<Project Sdk=\"Microsoft.NET.Sdk\" />").unwrap();
let assets = serde_json::json!({
"version": 3, "targets": {},
"libraries": {"Newtonsoft.Json/13.0.4": {"type": "package", "path": "newtonsoft.json/13.0.4"}},
"packageFolders": {packages.to_str().unwrap(): {}},
});
std::fs::write(project.join("obj/project.assets.json"), assets.to_string()).unwrap();
let socket = project.join(".socket");
let hash = common::oracle::git_sha256;
std::fs::create_dir_all(socket.join("blobs")).unwrap();
std::fs::write(socket.join("blobs").join(hash(orig)), orig).unwrap();
std::fs::write(socket.join("blobs").join(hash(patched)), patched).unwrap();
let purl = "pkg:nuget/Newtonsoft.Json@13.0.3";
let manifest = serde_json::json!({"patches": {purl: {
"uuid": "20000008-0000-4008-8008-000000000008",
"exportedAt": "2026-01-01T00:00:00Z",
"files": {format!("package/{dll}"): {"beforeHash": hash(orig), "afterHash": hash(patched)}},
"vulnerabilities": {}, "description": "fixture", "license": "MIT", "tier": "free",
}}});
std::fs::write(socket.join("manifest.json"), manifest.to_string()).unwrap();
let cwd = project.to_str().unwrap();
let out = run(
&["scan", "--json", "--sync", "--yes", "--cwd", cwd],
&project,
&packages,
&proxy_url,
)
.await;
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "scan --sync must exit 0:\n{stdout}");
let old_copy = packages.join("newtonsoft.json/13.0.3").join(dll);
assert_eq!(
std::fs::read(&old_copy).unwrap(),
patched,
"the scan does not restore the copy"
);
let m: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(socket.join("manifest.json")).unwrap())
.unwrap();
assert!(
m["patches"].get(purl).is_some(),
"the record of a copy that is still patched was pruned: nothing can restore \
{} now\nmanifest: {m:#}\nscan: {stdout}",
old_copy.display()
);
assert!(
socket.join("blobs").join(hash(orig)).exists(),
"the before-blob that restores the copy was swept"
);
}Maven, appended to crates/socket-patch-cli/tests/e2e_maven.rs
/// The Maven twin of `sync_keeps_entry_whose_shared_cache_copy_is_still_patched`
/// (e2e_cargo.rs, #1278): the project crawl keeps only what the project's
/// poms reach, so a patched artifact the pom moved away from is "not
/// crawled". Its jar in the local repository is one Maven never deletes and
/// every build on the machine resolves, and the record holds the only
/// before-blob that can restore it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sync_keeps_entry_whose_local_repository_jar_is_still_patched() {
let server = start_proxy().await;
let proxy_url = server.uri();
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
let m2 = dir.path().join("m2-repo");
let orig: &[u8] = b"the vulnerable jar\n";
let patched: &[u8] = b"the patched jar!!!\n";
// 1.0 holds the agent-mode patch; the pom has moved to 1.1.
for (version, bytes) in [("1.0", patched), ("1.1", orig)] {
let d = m2.join("com/example/victim").join(version);
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join(format!("victim-{version}.jar")), bytes).unwrap();
std::fs::write(
d.join(format!("victim-{version}.pom")),
format!("<project><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>victim</artifactId><version>{version}</version></project>"),
)
.unwrap();
}
std::fs::create_dir_all(&project).unwrap();
std::fs::write(
project.join("pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>app</artifactId><version>1.0</version><dependencies>\n <dependency><groupId>com.example</groupId><artifactId>victim</artifactId><version>1.1</version></dependency>\n</dependencies></project>\n",
)
.unwrap();
let socket = project.join(".socket");
let hash = common::oracle::git_sha256;
std::fs::create_dir_all(socket.join("blobs")).unwrap();
std::fs::write(socket.join("blobs").join(hash(orig)), orig).unwrap();
std::fs::write(socket.join("blobs").join(hash(patched)), patched).unwrap();
let purl = "pkg:maven/com.example/victim@1.0";
let manifest = serde_json::json!({"patches": {purl: {
"uuid": "20000008-0000-4008-8008-000000000009",
"exportedAt": "2026-01-01T00:00:00Z",
"files": {"package/victim-1.0.jar": {"beforeHash": hash(orig), "afterHash": hash(patched)}},
"vulnerabilities": {}, "description": "fixture", "license": "MIT", "tier": "free",
}}});
std::fs::write(socket.join("manifest.json"), manifest.to_string()).unwrap();
let cwd = project.to_str().unwrap();
let out = run(
&["scan", "--json", "--sync", "--yes", "--cwd", cwd],
&project,
&m2,
&proxy_url,
)
.await;
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "scan --sync must exit 0:\n{stdout}");
let old_jar = m2.join("com/example/victim/1.0/victim-1.0.jar");
assert_eq!(
std::fs::read(&old_jar).unwrap(),
patched,
"the scan does not restore the jar"
);
let m: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(socket.join("manifest.json")).unwrap())
.unwrap();
assert!(
m["patches"].get(purl).is_some(),
"the record of a jar that is still patched was pruned: nothing can restore \
{} now\nmanifest: {m:#}\nscan: {stdout}",
old_jar.display()
);
assert!(
socket.join("blobs").join(hash(orig)).exists(),
"the before-blob that restores the jar was swept"
);
}The undo after vendor, appended to crates/socket-patch-cli/tests/vendor_jvm_cli.rs
/// The Maven twin of #336 (Cargo): `vendor` takes over a patch that agent
/// mode wrote into the jar of the local repository, which every build on
/// the machine resolves and nothing deletes. The undo of the vendoring
/// must not drop the record, with the only before-blob, while that jar
/// still holds the patch: either the jar is restored or the record stays.
#[test]
fn undo_after_vendor_does_not_orphan_the_jar_an_agent_apply_patched() {
let foo = purl("foo");
let undos: [Vec<&str>; 2] = [
vec["rollback", "--yes", "--offline"],
vec["remove", &foo, "--yes", "--offline"],
];
for undo in undos {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]);
// A record that replaces the jar file whole, so the agent-mode
// apply runs offline, from the blobs alone.
let m2_jar = root.join("m2/org/example/foo/1.0/foo-1.0.jar");
let before = std::fs::read(&m2_jar).unwrap();
let after = jar(b"NOTICE foo\nPATCHED\n");
for blob in [&before, &after] {
std::fs::write(
root.join("proj/.socket/blobs").join(git_sha256(blob)),
blob,
)
.unwrap();
}
let manifest_path = root.join("proj/.socket/manifest.json");
let mut manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
manifest["patches"][&foo]["files"] = serde_json::json!({ "package/foo-1.0.jar": {
"beforeHash": git_sha256(&before),
"afterHash": git_sha256(&after),
} });
std::fs::write(&manifest_path, manifest.to_string()).unwrap();
ok(root, &["apply", "--offline"]);
assert_eq!(std::fs::read(&m2_jar).unwrap(), after, "agent mode patches in place");
ok(root, &["vendor"]);
let (code, env) = socket(root, &undo);
assert_eq!(code, Some(0), "{undo:?}: {env}");
let manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
let restored = std::fs::read(&m2_jar).unwrap() == before;
let recorded = manifest["patches"].get(&foo).is_some();
assert!(
restored || recorded,
"{undo:?} dropped the record and left {} patched: nothing can restore it now\n{env}",
m2_jar.display()
);
}
}$ cargo test -p socket-patch-cli --no-fail-fast --test e2e_nuget --test e2e_maven -- sync_keeps_entry
test sync_keeps_entry_whose_local_repository_jar_is_still_patched ... FAILED
the record of a jar that is still patched was pruned: nothing can restore <tmp>/m2-repo/com/example/victim/1.0/victim-1.0.jar now
test sync_keeps_entry_whose_global_packages_copy_is_still_patched ... FAILED
the record of a copy that is still patched was pruned: nothing can restore <tmp>/nuget-packages/newtonsoft.json/13.0.3/lib/net6.0/Newtonsoft.Json.dll now
$ cargo test -p socket-patch-cli --test vendor_jvm_cli -- undo_after_vendor
test undo_after_vendor_does_not_orphan_the_jar_an_agent_apply_patched ... FAILED
["rollback", "--yes", "--offline"] dropped the record and left <tmp>/m2/org/example/foo/1.0/foo-1.0.jar patched: nothing can restore it now
The Cargo twin of the first two, sync_keeps_entry_whose_shared_cache_copy_is_still_patched in tests/e2e_cargo.rs, passes. The third passes whether the fix restores the jar (as #336's does for Cargo) or keeps the record.
Where
- The prune and its two keeps: scan/gc.rs L338-L341, and the preview's copy at L666-L669.
detect_prunable(L900-L916) reads "not in the crawl" as "gone". - The helpers, one per ecosystem: ecosystem_dispatch.rs L32-L108.
rollback's exception for a vendored purl, Cargo only: [rollback.rs L3450-L3472](https://github.com/SocketDev/socket-patch/blob/d98772148e4fffb56fa53e9f867e10e1286bb089/crates/socket-patch-cli/src/commands/rollback.rs#L3450-L3472).- The contract's
--pruneparagraph names the Cargo and PyPI exemptions and gives their reason ("the entry holds the only blobs that can restore that copy"): CLI_CONTRACT.md L489. docs/ecosystems.md says agent mode "writes into shared caches" for Maven and NuGet (L33-L43) and that "the Maven local repository is shared by every project on the machine" (L1974-L1976). - The earlier fixes:
git log -S'cargo_cache_patch_kept'gives dcded7a (Fix cargo shared-cache patch orphaned on takeover/prune (#336, #1278) #1305, for Cargo rollback after an agent→vendored takeover leaves the shared registry cache patched, reports success, and deletes the revert blobs #336 and Agent-mode cargoscan --sync/--prunedrops the manifest entry of a crate the lock no longer resolves but leaves its shared registry-cache copy patched, sorollbackcan't restore it (regression from #1205) #1278);git log -S'pypi_installed_patch_kept'gives fc18188 (Scan only a no-venv Python project's own packages, not the whole machine's #2170). The Maven crawl was scoped to the poms in 08e54b2 (Fix project-mode Maven crawl listing all of ~/.m2 (#265) #1361), the same day as the Cargo fix.
Planned fix
One rule in place of the per-ecosystem ones: before a record leaves the manifest while its package is outside the run's crawl (the prune) or owned by the vendor ledger (rollback, remove), look its purl up the way rollback <purl> does and ask whether a copy still holds the patch.
- The prune keeps such a record, with its blobs and a warning that names
socket-patch rollback <purl>, for every ecosystem. Cargo's and PyPI's lookups become that rule's per-ecosystem lookups and keep their warning codes; Maven and NuGet get the same sentence under a code of their own (maven_cache_patch_kept,nuget_cache_patch_kept; an additive warning, exit code unchanged). The preview and the wet pass share one function. rollbackandremoveof a vendored purl restore such a copy before the record goes, as they do for a crate.CLI_CONTRACT.mdL489 and the comment that calls Cargo "the one ecosystem" say what the code then does.
Related: #1926 (the two "may still hold the patch" rules drifted) is in the same helper; #2468 is the same loss across scopes.
Not run: a real Gradle (the Gradle rows are files only), sbt, and the Coursier and Ivy caches; the second part for NuGet (a vendored NuGet package is restored into the same global packages folder, and #2453 is open on that code) and for a PyPI project that installs into a shared interpreter; a record that rewrites members of a jar (for those agent mode swaps in the patch service's build of the jar, which needs the service; the prune reads the purl only); a dependency that is dropped where others remain; Windows and macOS. Go is not in the table: over a patched module-cache copy a project apply --check asks for a go.mod replace and a patched copy, so a project's agent mode does not patch the module cache.
Generated by Claude Code
Activity
refactor: L153, L154 filed as #2472