Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

183 changes: 181 additions & 2 deletions crates/socket-patch-core/src/formats/cargo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.<table>]` 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.<table>]` 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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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}"
);
}
}
}
27 changes: 9 additions & 18 deletions crates/socket-patch-core/src/patch/redirect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -2533,22 +2533,6 @@ fn cargo_manifest_package_id(
Some((name.to_string(), version.to_string()))
}

/// Whether a Cargo.lock `source` (or a `[patch.<url>]` 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+…/<patch uuid>/index/`) — an earlier generation's pin, which a
/// re-run legitimately repoints.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
8 changes: 3 additions & 5 deletions crates/socket-patch-core/src/vendor/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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")));
}
}
Expand Down Expand Up @@ -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}`"
),
));
}
Expand Down
30 changes: 11 additions & 19 deletions crates/socket-patch-core/src/vendor/cargo_manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,13 @@ pub const CARGO_TOML: &str = "Cargo.toml";
/// (`<name>-socket-<first 8 hex of the uuid>`).
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.<source>]` 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.<source>]` 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.<source>]` 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.<url>]` keys of a document that spell crates.io by URL.
pub fn crates_io_url_alias_tables(doc: &DocumentMut) -> Vec<String> {
Expand Down Expand Up @@ -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<ManifestPatchEntry> {
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(),
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading