A Cargo [replace] key spelled the way `cargo pkgid` prints it is not read as the project's own replacement: apply exits 1 and a vendored scan fails

Ouverte Adaptée aux débutants
#2,306 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
2/5
Temps estimé
1-3 heures
Accessibilité débutants
84/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
rust
Domaine
cli, security

Piste de recherche

Commence par l’analyse existante de [replace] et le test cargo_and_go_preserve_user_overrides_and_recognize_socket_ownership dans patch/user_patches.rs ; l’issue comprend un test en échec couvrant les différentes écritures des identifiants de paquets Cargo. Lis le comportement signalé pour l’analyse des clés Cargo, puis lance le test ciblé de socket-patch-core. Le travail est terminé lorsque toutes les écritures valides protègent pkg:cargo/[email protected] et que les déclarations illisibles protègent chaque paquet Cargo, comme décrit.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

agent:triaged arch-audit bug priority:p2

[agent] Found by the architecture refactor routine (ledger discussion #2244, lead L47), on main at cfc870f.

Problem

A [replace] key in Cargo.toml is a package ID specification, and cargo takes several spellings of one. For fnv 1.0.7 from crates.io, cargo 1.97.0 builds the replacement under each of these keys:

"fnv:1.0.7"
"[email protected]"
"https://github.com/rust-lang/crates.io-index#[email protected]"
"registry+https://github.com/rust-lang/crates.io-index#fnv:1.0.7"
"registry+https://github.com/rust-lang/crates.io-index#[email protected]"      # what `cargo pkgid fnv` prints

The project-patch gate splits the key at its first :, so it reads only the first spelling as a replacement of [email protected]. For the other four the crate is not protected by the gate. It is caught later, by the readers of the replace = "fnv 1.0.7" line cargo writes into Cargo.lock, and reported as something else:

Command "fnv:1.0.7" "[email protected]"
apply, the crate's patch is the only one recorded skipped, user_patch_conflict, exit 0 Error: The targeted manifest patch matched no installed package, partialFailure, exit 1
apply, beside a patch that applies skipped, user_patch_conflict, exit 0 skipped, package_not_installed, exit 0; the warning says to run cargo fetch
scan --mode agent skipped, user_patch_conflict, exit 0 "not installed; run your package manager's install first, or socket-patch scan --mode vendored", exit 0
scan --mode vendored skipped, user_patch_conflict, exit 0 Error: Cannot vendor pkg:cargo/[email protected]: Cargo.lock resolves [email protected] from multiple sources (e.g. the registry plus a git fork), exit 1
scan --mode hosted skipped, user_patch_conflict, exit 0 skipped, redirect_unconfirmed, with a redirect_cargo_lock_pkg_ambiguous warning, exit 0
get <uuid> refused before any write, user_patch_conflict, exit 1 the record is written to .socket/manifest.json, then the apply fails, exit 1

No row patches the crate over the replacement. What is wrong is the exit code, the saved record and what the user is told. The agent-mode and hosted scans gave the right-hand result for all four spellings; the other rows ran with [email protected].

CLI_CONTRACT.md ("Existing project patches") lists [replace] as Cargo evidence and gives the left-hand column: a scan skips with user_patch_conflict; apply leaves the entry out, and "skips alone exit 0, so a postinstall apply never fails an install over them"; get and vendor "refuse selected conflicts with exit 1, status: error, error.code: user_patch_conflict, before their patch writes".

Who it hurts

  • A project with a recorded agent-mode patch for a crate that a developer then replaces with a fork, with the key written as cargo pkgid prints it. When that patch is the only one recorded, the CI step socket-patch apply starts to exit 1, and its message asks for cargo fetch, which cannot help.
  • A project in vendored mode: scan --mode vendored exits 1 over a crate the contract says it skips.

[replace] is deprecated in favor of [patch], and cargo still honors it, so few projects are in this state.

Evidence on main

The binary is built from cfc870f. cargo is 1.97.0, offline, with a CARGO_HOME of its own. The app prints fnv::FnvHasher::default().finish(): cbf29ce484222325 from the registry crate and 2222222222222222 from the fork in ../fnv-fork. The patch API is a local stand-in that serves one patch for pkg:cargo/[email protected].

A project with that patch recorded and applied, to which a developer adds the replacement:

$ tail -2 Cargo.toml
[replace]
"fnv:1.0.7" = { path = "../fnv-fork" }
$ cargo build --offline -q && ./target/debug/app
2222222222222222
$ socket-patch apply
No patches to apply.
Warning: pkg:cargo/[email protected]: protected by project patch/replacement metadata in <w>/app/Cargo.toml; leaving this package untouched. Merge the fixes manually, or …
                                                            (exit 0)
$ socket-patch apply --json | jq -c '.status, [.events[] | [.action, .errorCode]]'
"success"
[["skipped","user_patch_conflict"]]
$ tail -2 Cargo.toml
[replace]
"[email protected]" = { path = "../fnv-fork" }
$ cargo build --offline -q && ./target/debug/app
2222222222222222
$ socket-patch apply
Error: The targeted manifest patch matched no installed package:
  - pkg:cargo/[email protected]
Check that the packages are installed and --cwd points to the right directory.
Cargo crates are patched in the registry cache: run `cargo fetch` first so every locked crate is unpacked there, then re-run apply. A crate Cargo.lock takes from a path, git or [patch] source is never patched there: cargo does not build that copy.

Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk
                                                            (exit 1)
$ socket-patch apply --json | jq -c '.status, [.events[] | [.action, .errorCode]]'
"partialFailure"
[["skipped","package_not_installed"]]

A project with no patch recorded yet, "[email protected]":

$ socket-patch scan --mode agent
Found 1 package (1 cargo)
Note: 1 package from project lockfiles is not yet installed (lockfile-only).
  [skip] pkg:cargo/[email protected] (not installed; run your package manager's install first, or `socket-patch scan --mode vendored` to vendor it from the lockfile)
No patches selected.
                                                            (exit 0)
$ socket-patch scan --mode vendored
Found 1 package (1 cargo)
Error: Cannot vendor pkg:cargo/[email protected]: Cargo.lock resolves `[email protected]` from multiple sources (e.g. the registry plus a git fork); detaching the registry entry would corrupt the full package-id references in the lock's dependencies arrays, so this crate cannot be vendored in this project
Vendored 0 packages; 1 failed.
                                                            (exit 1)
$ socket-patch get cccccccc-0000-4000-8000-000000000001
Found patch for pkg:cargo/[email protected] [FREE] fixes CVE-2026-0001 (HIGH)
Patch saved to ./.socket/manifest.json
  Added: 1
Error: The targeted manifest patch matched no installed package:
…                                                           (exit 1)

The same three commands with "fnv:1.0.7":

$ socket-patch scan --mode agent
Note: skipped 1 package covered by this project's own patches (Cargo.toml): [email protected].
  --allow-patch-conflicts patches it too.
1 package is protected by this project's own patches and was not scanned. Pass --allow-patch-conflicts to scan it anyway.
                                                            (exit 0)
$ socket-patch scan --mode vendored          # the same three lines
                                                            (exit 0)
$ socket-patch get cccccccc-0000-4000-8000-000000000001
Found patch for pkg:cargo/[email protected] [FREE] fixes CVE-2026-0001 (HIGH)
Error: pkg:cargo/[email protected]: protected by project patch/replacement metadata in <w>/app/Cargo.toml; leaving this package untouched. Merge the fixes manually, or explicitly accept the conflict risk with --allow-patch-conflicts
                                                            (exit 1; no .socket/ is written)

Cargo rejects the other spellings I tried ("fnv:1.0", "fnv@=1.0.7", "crates-io:fnv:1.0.7"): "replacements must specify a valid semver version to replace".

Cause

cargo (core patch/user_patches.rs, lines 1148 to 1155) reads each [replace] key with key.split_once(':'). [email protected] has no colon, so its name is [email protected] with no version. A key that starts with a URL gets the name https or registry+https. The one test of the table uses 'old:1.0.0' (cargo_and_go_preserve_user_overrides_and_recognize_socket_ownership).

Whatever the spelling, cargo records the replacement in Cargo.lock (replace = "fnv 1.0.7" on the registry entry). Two readers see it there: the crawler's lock model (LockedPackage.replace, core formats/cargo/mod.rs, line 210), which is why the crate reads as "not installed", and the vendored lock editor (core vendor/cargo_lock.rs, line 304).

The failing test

Beside the existing test in core patch/user_patches.rs:

#[tokio::test]
async fn a_cargo_replace_key_in_any_package_id_spelling_protects_its_crate() {
    let mut missed = Vec::new();
    for key in [
        "fnv:1.0.7",
        "[email protected]",
        "https://github.com/rust-lang/crates.io-index#[email protected]",
        "registry+https://github.com/rust-lang/crates.io-index#fnv:1.0.7",
    ] {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "Cargo.toml",
            &format!("[replace]\n\"{key}\" = {{ path = \"../fnv-fork\" }}\n"),
        );
        let index = UserPatchIndex::discover(tmp.path()).await;
        if index.conflicts("pkg:cargo/[email protected]").is_empty() {
            missed.push(key);
        }
    }
    assert!(missed.is_empty(), "not protected: {missed:?}");
}
$ cargo test -p socket-patch-core --lib -- a_cargo_replace_key_in_any
test patch::user_patches::tests::a_cargo_replace_key_in_any_package_id_spelling_protects_its_crate ... FAILED

not protected: ["[email protected]", "https://github.com/rust-lang/crates.io-index#[email protected]", "registry+https://github.com/rust-lang/crates.io-index#fnv:1.0.7"]

The fifth spelling in the list at the top, the one cargo pkgid prints, ran through the binary instead: cargo builds the fork, and the agent-mode scan answers package_not_installed.

Planned fix

Read the key as cargo does: the part after the last # when there is one, then the name and the version on either side of the last @ or :. A key that does not come apart that way protects every Cargo package, as an unreadable declaration does, instead of none. The test above goes in with the fix. No output shape changes: the three spellings get the result the first one has today.


Generated by Claude Code

Langage dominant
Rust
Étoiles
9
Forks
2
Merge moyen
1 j 8 h
PR mergées (30 j)
313

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de SocketDev/socket-patch

Toutes les issues de SocketDev/socket-patch

Issues similaires

Plus d'issues Rust

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.