Skip to main content

deps_cargo/
sparse.rs

1//! Generic sparse-index registry client.
2//!
3//! Implements Cargo's sparse index wire protocol (RFC 2789), shared by crates.io itself
4//! and any alternate/private registry declared through `.cargo/config.toml`. Extracted
5//! from `registry.rs` so [`crate::registry::CratesIoRegistry`] and the alternate-registry
6//! router (`CargoRegistry`) both delegate to one implementation instead of duplicating the
7//! index-path computation, JSON-lines parsing, and crate-name safety gate.
8//!
9//! # Examples
10//!
11//! ```no_run
12//! use deps_cargo::config::RegistryIndex;
13//! use deps_cargo::sparse::SparseIndexClient;
14//! use deps_core::HttpCache;
15//! use deps_core::net_policy::{OperatorRegistries, RegistryAccessPolicy};
16//! use std::sync::Arc;
17//!
18//! #[tokio::main]
19//! async fn main() {
20//!     let cache = Arc::new(HttpCache::new());
21//!     let policy = RegistryAccessPolicy::default();
22//!     let index = RegistryIndex::declared("https://index.crates.io", &OperatorRegistries::default(), &policy).unwrap();
23//!     let client = SparseIndexClient::new(index, cache, "sparse index");
24//!
25//!     let versions = client.get_versions("serde").await.unwrap();
26//!     println!("Latest serde: {}", versions[0].num);
27//! }
28//! ```
29
30use crate::config::{RegistryIndex, RegistryTrust};
31use crate::types::CargoVersion;
32use deps_core::{
33    DepsError, HttpCache, RegistryEndpoint, Result,
34    cache::{CredentialHeader, RequestAuth},
35    lsp_helpers::warn_rejected_value,
36    net_policy::TrustedPrefix,
37};
38use semver::{Version, VersionReq};
39use serde::Deserialize;
40use std::collections::HashMap;
41use std::sync::Arc;
42
43/// Whether `name`'s character set matches crates.io's crate-name charset (ASCII
44/// alphanumeric, `-`, `_`), non-empty — stricter than
45/// [`deps_core::is_safe_package_name`], which permits `/`, `@`, `.`, `:`, `~` to
46/// accommodate other ecosystems' scoped/namespaced names. Deliberately carries no
47/// length bound of its own: [`is_safe_crate_name`] layers this crate's 128-byte
48/// URL-safety cap on top, while `deps_cargo::formatter::CargoFormatter`'s
49/// `validate_package_name` layers its own, stricter, diagnostic-accuracy length
50/// check on top instead — bundling a length bound into this predicate would make
51/// the latter unable to distinguish "bad charset" from "too long" for a name that
52/// is both charset-valid and longer than crates.io's real limit (#382 follow-up).
53pub(crate) fn is_safe_crate_name_charset(name: &str) -> bool {
54    !name.is_empty()
55        && name
56            .chars()
57            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
58}
59
60/// Whether `name` is safe to splice into a sparse-index request URL:
61/// [`is_safe_crate_name_charset`] plus a 128-byte length bound. [`sparse_index_path`]
62/// performs no per-character encoding at all before splicing `name` into the request
63/// URL (unlike every other ecosystem crate, which `urlencoding::encode`s each
64/// segment): a `name` containing `/` or `.` is used as-is to build directory
65/// components, so a crafted name like `../../etc/passwd` can inject arbitrary path
66/// segments, not just the narrower exact-`.`/`..` case #341/#349/#357/#361 covered
67/// (#365 S1). The 128-byte bound exists only to keep a pathological request URL
68/// bounded — it is not crates.io's real publish-time length limit, so callers that
69/// need an accurate "too long" diagnostic (see `is_safe_crate_name_charset`'s docs)
70/// must not reuse this function for that purpose.
71pub(crate) fn is_safe_crate_name(name: &str) -> bool {
72    is_safe_crate_name_charset(name) && name.len() <= 128
73}
74
75/// Rejects a `name` outside crates.io's crate-name charset before it would reach
76/// [`sparse_index_path`], as `DepsError::PackageNotFound`.
77fn reject_unsafe_crate_name(name: &str, registry_display_name: &'static str) -> Result<()> {
78    if !is_safe_crate_name(name) {
79        warn_rejected_value("is_safe_crate_name", "sparse index request URL", name);
80        return Err(DepsError::not_found_locally(name, registry_display_name));
81    }
82    Ok(())
83}
84
85/// Converts a crate name to its sparse index path.
86///
87/// Based on Cargo RFC 2789 specification:
88/// - 1 char: "1/{name}"
89/// - 2 chars: "2/{name}"
90/// - 3 chars: "3/{first_char}/{name}"
91/// - 4+ chars: "{first_2}/{next_2}/{name}"
92///
93/// Path segments are computed from the crate name's **character** count and
94/// positions, not byte length/offsets — crate names may contain multi-byte
95/// UTF-8 characters, and byte-index slicing could land mid-character and panic.
96/// An empty name has no length-based segment and returns the empty string.
97///
98/// Callers must additionally run [`reject_unsafe_crate_name`] first: this function performs
99/// no charset/encoding validation of `name` at all, so an unchecked `name` (any character,
100/// including `.`/`..` or an embedded `/`) reaches this unfiltered and can inject arbitrary
101/// path segments once spliced into the request URL (#365 S1) — the char-safe indexing above
102/// only prevents a panic (#376), it does not validate `name`.
103fn sparse_index_path(name: &str) -> String {
104    let name_lower = name.to_lowercase();
105    let chars: Vec<char> = name_lower.chars().collect();
106
107    // Each arm's indexing is safe by construction: the `3` arm only runs when
108    // `chars.len() == 3`, and `_` only when `chars.len() >= 4` (0/1/2/3 handled above).
109    #[allow(clippy::indexing_slicing)]
110    match chars.len() {
111        0 => name_lower,
112        1 => {
113            let mut path = String::with_capacity(2 + name_lower.len());
114            path.push_str("1/");
115            path.push_str(&name_lower);
116            path
117        }
118        2 => {
119            let mut path = String::with_capacity(2 + name_lower.len());
120            path.push_str("2/");
121            path.push_str(&name_lower);
122            path
123        }
124        3 => {
125            let mut path = String::with_capacity(4 + name_lower.len());
126            path.push_str("3/");
127            path.push(chars[0]);
128            path.push('/');
129            path.push_str(&name_lower);
130            path
131        }
132        _ => {
133            let mut path = String::with_capacity(6 + name_lower.len());
134            path.extend(chars[0..2].iter());
135            path.push('/');
136            path.extend(chars[2..4].iter());
137            path.push('/');
138            path.push_str(&name_lower);
139            path
140        }
141    }
142}
143
144/// Builds the sparse index request URL for a crate's version metadata, against
145/// `base_url` (no trailing slash assumed either way). Callers must run
146/// [`reject_unsafe_crate_name`] first — [`sparse_index_path`] performs no encoding or
147/// rejection of `name` at all, so an unchecked `name` (any character, including `.`/`..`
148/// or an embedded `/`) reaches this unfiltered.
149fn sparse_index_url(base_url: &str, name: &str) -> String {
150    let path = sparse_index_path(name);
151    let base = base_url.trim_end_matches('/');
152    let mut url = String::with_capacity(base.len() + 1 + path.len());
153    url.push_str(base);
154    url.push('/');
155    url.push_str(&path);
156    url
157}
158
159/// Entry in the sparse index (one line of newline-delimited JSON).
160#[derive(Deserialize)]
161struct IndexEntry {
162    #[serde(rename = "vers")]
163    version: String,
164    #[serde(default)]
165    yanked: bool,
166    #[serde(default)]
167    features: HashMap<String, Vec<String>>,
168    /// Publish timestamp (RFC 3339, e.g. `"2026-07-18T23:05:13Z"`).
169    ///
170    /// Absent on index entries older than the sparse index's rollout of this
171    /// field; `#[serde(default)]` keeps such lines parseable.
172    #[serde(default)]
173    pubtime: Option<String>,
174}
175
176/// Parses newline-delimited JSON from a sparse index.
177fn parse_index_json(data: &[u8]) -> Result<Vec<CargoVersion>> {
178    let content =
179        std::str::from_utf8(data).map_err(|e| DepsError::parse_error("sparse index", &e))?;
180
181    // Cache each parsed Version alongside its CargoVersion to avoid re-parsing for the sort.
182    let mut versions_with_parsed: Vec<(CargoVersion, Version)> = content
183        .lines()
184        .filter(|line| !line.trim().is_empty())
185        .filter_map(|line| {
186            let entry: IndexEntry = deps_core::parse_json_checked(line.as_bytes()).ok()?;
187            let parsed = entry.version.parse::<Version>().ok()?;
188            let published_at = entry
189                .pubtime
190                .as_deref()
191                .and_then(deps_core::PublishTime::parse_rfc3339);
192            Some((
193                CargoVersion {
194                    num: entry.version.into(),
195                    yanked: entry.yanked,
196                    features: entry.features,
197                    published_at,
198                },
199                parsed,
200            ))
201        })
202        .collect();
203
204    // Newest first.
205    versions_with_parsed.sort_unstable_by(|a, b| b.1.cmp(&a.1));
206
207    Ok(versions_with_parsed.into_iter().map(|(v, _)| v).collect())
208}
209
210/// Client for one sparse-index registry — crates.io's own index or an alternate/private
211/// one resolved from `.cargo/config.toml`.
212///
213/// Owns `base_url`/`sparse_index_path`/`parse_index_json` (moved from the pre-existing
214/// crates.io-only client, not reimplemented), so every registry speaking this protocol
215/// shares one parser and one crate-name safety gate.
216#[derive(Clone)]
217pub struct SparseIndexClient {
218    base: TrustedPrefix,
219    cache: Arc<HttpCache>,
220    /// How requests leave this client, decided once from the [`RegistryIndex`] it was built from
221    /// so the request path and [`Self::endpoint`]'s egress cannot disagree.
222    transport: IndexTransport,
223    /// Display name used in [`deps_core::DepsError::PackageNotFound`] messages.
224    registry_display_name: &'static str,
225    /// The endpoint [`Self::endpoint`] reports, computed on first use (the fingerprint hashes
226    /// URL text, which the gate would otherwise redo for every lookup).
227    endpoint: deps_core::CachedEndpoint,
228}
229
230/// The transport [`SparseIndexClient::fetch`] sends a request through.
231///
232/// A credential exists only on [`Self::TrustedOrigin`], whose index the URL-alone rule
233/// classified Trusted (see [`RegistryIndex`]), so a credential on a workspace-declared index is
234/// not representable. The `Authorization` value is formatted once at construction and held
235/// [`deps_core::secret::Redacted`] from then on (issue #672).
236#[derive(Clone)]
237enum IndexTransport {
238    /// A credentialed request over an origin-confined transport, so the header cannot survive a
239    /// cross-origin redirect.
240    TrustedOrigin(deps_core::secret::AuthorizationValue),
241    /// An anonymous request to a Trusted index, over the system-proxy Baseline egress.
242    System,
243    /// An anonymous request to a workspace-declared index, over the guarded egress whose
244    /// connect-time address is scrutinized by the live workspace-registry policy.
245    Workspace,
246}
247
248impl IndexTransport {
249    fn for_index(index: &RegistryIndex) -> Self {
250        match (index.credential(), index.trust()) {
251            (Some(token), _) => {
252                Self::TrustedOrigin(deps_core::secret::cargo_token_header(token.as_redacted()))
253            }
254            (None, RegistryTrust::Trusted) => Self::System,
255            (None, RegistryTrust::WorkspaceDeclared) => Self::Workspace,
256        }
257    }
258}
259
260impl SparseIndexClient {
261    /// The network path this client's requests travel: its index base through the egress its
262    /// transport uses (system proxy for trusted indexes, the guarded direct path for
263    /// workspace-declared ones).
264    #[must_use]
265    pub fn endpoint(&self) -> RegistryEndpoint {
266        self.endpoint
267            .get_or_compute(|| RegistryEndpoint::base(self.base.as_url(), self.trust().egress()))
268    }
269
270    /// Creates a client for `index`, which it consumes whole: its URL, its trust and its
271    /// credential (if any) are all decided by the [`RegistryIndex`] it is built from.
272    /// `registry_display_name` appears in not-found error messages.
273    ///
274    /// Takes a validated [`RegistryIndex`], not a bare `String` (plan-1b §1.2, critic S2): the
275    /// URL-alone classification is the *only* way to obtain a fetchable index, so this client
276    /// cannot be built with a URL that skipped it.
277    pub fn new(
278        index: RegistryIndex,
279        cache: Arc<HttpCache>,
280        registry_display_name: &'static str,
281    ) -> Self {
282        Self {
283            transport: IndexTransport::for_index(&index),
284            base: index.trusted_prefix(),
285            cache,
286            registry_display_name,
287            endpoint: deps_core::CachedEndpoint::default(),
288        }
289    }
290
291    /// The [`RegistryTrust`] tier this client's index was classified under.
292    #[must_use]
293    pub(crate) const fn trust(&self) -> RegistryTrust {
294        match self.transport {
295            IndexTransport::TrustedOrigin(_) | IndexTransport::System => RegistryTrust::Trusted,
296            IndexTransport::Workspace => RegistryTrust::WorkspaceDeclared,
297        }
298    }
299
300    /// Whether this client attaches a credential to its requests. Test/diagnostic-only: private
301    /// fields are not visible from `registry.rs`, a sibling module, so `crate::registry`'s C3
302    /// fold test needs this accessor to assert a credential was dropped, alongside
303    /// [`Self::trust`].
304    #[cfg(test)]
305    pub(crate) const fn has_auth(&self) -> bool {
306        matches!(self.transport, IndexTransport::TrustedOrigin(_))
307    }
308
309    /// Fetches all versions for a crate from the sparse index.
310    ///
311    /// Returns versions sorted newest-first. Includes yanked versions.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error if:
316    /// - HTTP request fails
317    /// - Response body is invalid UTF-8
318    /// - JSON parsing fails
319    ///
320    /// # Examples
321    ///
322    /// ```no_run
323    /// # use deps_cargo::sparse::SparseIndexClient;
324    /// # use deps_core::HttpCache;
325    /// # use std::sync::Arc;
326    /// # #[tokio::main]
327    /// # async fn main() {
328    /// let cache = Arc::new(HttpCache::new());
329    /// let policy = deps_core::net_policy::RegistryAccessPolicy::default();
330    /// let index = deps_cargo::config::RegistryIndex::declared(
331    ///     "https://index.crates.io",
332    ///     &deps_core::net_policy::OperatorRegistries::default(),
333    ///     &policy,
334    /// ).unwrap();
335    /// let client = SparseIndexClient::new(index, cache, "sparse index");
336    ///
337    /// let versions = client.get_versions("serde").await.unwrap();
338    /// assert!(!versions.is_empty());
339    /// # }
340    /// ```
341    #[tracing::instrument(skip_all, fields(package = %deps_core::net_policy::redact_declaration_key(name)), level = "debug")]
342    pub async fn get_versions(&self, name: &str) -> Result<Vec<CargoVersion>> {
343        reject_unsafe_crate_name(name, self.registry_display_name)?;
344        let url = sparse_index_url(self.base.as_str(), name);
345        let data = self.fetch(&url).await?;
346        parse_index_json(&data)
347    }
348
349    /// Finds the latest version matching the given semver requirement.
350    ///
351    /// Only returns non-yanked versions.
352    ///
353    /// # Errors
354    ///
355    /// Returns an error if:
356    /// - Version requirement string is invalid semver
357    /// - HTTP request fails
358    #[tracing::instrument(skip_all, fields(package = %deps_core::net_policy::redact_declaration_key(name), version = ?req_str), level = "debug")]
359    pub async fn get_latest_matching(
360        &self,
361        name: &str,
362        req_str: &str,
363    ) -> Result<Option<CargoVersion>> {
364        let versions = self.get_versions(name).await?;
365
366        let req = req_str
367            .parse::<VersionReq>()
368            .map_err(|e| DepsError::InvalidVersionReq(e.to_string()))?;
369
370        Ok(versions.into_iter().find(|v| {
371            let version = v.num.as_str().parse::<Version>().ok();
372            version.is_some_and(|ver| req.matches(&ver) && !v.yanked)
373        }))
374    }
375
376    /// Routes the request through the transport [`Self::transport`] selects — the sole call site
377    /// deciding between [`deps_core::HttpCache::get_cached`],
378    /// [`deps_core::HttpCache::get_cached_trusted_origin`], and (issue #455)
379    /// [`deps_core::HttpCache::get_cached_workspace`], so the two
380    /// [`Self::get_versions`]/pagination-free shape of this client never duplicates that
381    /// branch.
382    ///
383    /// # Errors
384    ///
385    /// Same as [`Self::get_versions`].
386    async fn fetch(&self, url: &str) -> Result<bytes::Bytes> {
387        match &self.transport {
388            IndexTransport::TrustedOrigin(header_value) => {
389                let auth = RequestAuth::credential(
390                    CredentialHeader::Authorization(header_value),
391                    &self.base,
392                );
393                self.cache
394                    .get_cached_trusted_origin(url, &self.base, auth, None)
395                    .await
396            }
397            IndexTransport::System => self.cache.get_cached(url).await,
398            IndexTransport::Workspace => self.cache.get_cached_workspace(url).await,
399        }
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use crate::config::{AuthToken, CargoOperator};
407    use deps_core::EgressTier;
408    use deps_core::net_policy::{OperatorRegistries, RegistryAccessPolicy};
409    use std::assert_matches;
410
411    /// Wraps `raw` into a Trusted [`RegistryIndex`] for test call sites, so a test's own choice
412    /// of URL (including a loopback mockito URL) is never blocked — the classification itself is
413    /// unit-tested directly in `config.rs`, not re-exercised here.
414    fn test_index(raw: &str) -> RegistryIndex {
415        RegistryIndex::for_test(raw, RegistryTrust::Trusted)
416    }
417
418    /// Like [`test_index`], but [`RegistryTrust::WorkspaceDeclared`] — for issue #455's C2
419    /// routing tests, which need a `WorkspaceDeclared` index specifically.
420    fn test_workspace_index(raw: &str) -> RegistryIndex {
421        RegistryIndex::for_test(raw, RegistryTrust::WorkspaceDeclared)
422    }
423
424    /// Cargo's transport egress is exactly the core trust's egress (spec 084): the credential
425    /// decision never changes which egress a trust uses.
426    #[test]
427    fn test_transport_egress_equals_the_core_trust_egress() {
428        for (index, transport_egress) in [
429            (test_index("https://a.example"), EgressTier::Baseline),
430            (
431                RegistryIndex::credentialed_for_test("https://a.example", "cargo-token"),
432                EgressTier::Baseline,
433            ),
434            (
435                test_workspace_index("https://a.example"),
436                EgressTier::Guarded,
437            ),
438        ] {
439            let trust = index.trust();
440            let client = SparseIndexClient::new(index, Arc::new(HttpCache::new()), "t");
441            let expected = match client.transport {
442                IndexTransport::TrustedOrigin(_) | IndexTransport::System => EgressTier::Baseline,
443                IndexTransport::Workspace => EgressTier::Guarded,
444            };
445            assert_eq!(expected, transport_egress);
446            assert_eq!(trust.egress(), transport_egress);
447            assert_eq!(
448                client.endpoint(),
449                RegistryEndpoint::base(client.base.as_url(), transport_egress)
450            );
451        }
452    }
453
454    /// Live-network smoke test against the real crates.io sparse index. Restored
455    /// (review finding #8) after being dropped, undisclosed, during the extraction of
456    /// this module out of `registry.rs`. `#[ignore]`d: not run in CI, only on demand.
457    #[tokio::test]
458    #[ignore = "requires network access"]
459    async fn test_fetch_real_serde_versions() {
460        let cache = Arc::new(HttpCache::new());
461        let client = SparseIndexClient::new(test_index("https://index.crates.io"), cache, "test");
462        let versions = client.get_versions("serde").await.unwrap();
463
464        assert!(!versions.is_empty());
465        assert!(versions.iter().any(|v| v.num.as_str().starts_with("1.")));
466    }
467
468    /// Live-network smoke test against the real crates.io sparse index. Restored
469    /// (review finding #8), same provenance as `test_fetch_real_serde_versions` above.
470    #[tokio::test]
471    #[ignore = "requires network access"]
472    async fn test_get_latest_matching_real() {
473        let cache = Arc::new(HttpCache::new());
474        let client = SparseIndexClient::new(test_index("https://index.crates.io"), cache, "test");
475        let latest = client.get_latest_matching("serde", "^1.0").await.unwrap();
476
477        assert!(latest.is_some());
478        let version = latest.unwrap();
479        assert!(version.num.as_str().starts_with("1."));
480        assert!(!version.yanked);
481    }
482
483    #[test]
484    fn test_sparse_index_path() {
485        assert_eq!(sparse_index_path("a"), "1/a");
486        assert_eq!(sparse_index_path("ab"), "2/ab");
487        assert_eq!(sparse_index_path("abc"), "3/a/abc");
488        assert_eq!(sparse_index_path("serde"), "se/rd/serde");
489        assert_eq!(sparse_index_path("tokio"), "to/ki/tokio");
490    }
491
492    #[test]
493    fn test_sparse_index_path_uppercase() {
494        assert_eq!(sparse_index_path("SERDE"), "se/rd/serde");
495    }
496
497    #[test]
498    fn test_reject_unsafe_crate_name_rejects_bare_dot_dot() {
499        assert!(reject_unsafe_crate_name("..", "crates.io").is_err());
500    }
501
502    #[test]
503    fn test_reject_unsafe_crate_name_rejects_bare_dot() {
504        assert!(reject_unsafe_crate_name(".", "crates.io").is_err());
505    }
506
507    #[test]
508    fn test_reject_unsafe_crate_name_rejects_embedded_slash() {
509        // S1 (impl-critic): `sparse_index_path` performs no per-character encoding, so a
510        // `/` anywhere in `name` (not just a bare `.`/`..`) can inject path segments once
511        // spliced into the request URL.
512        assert!(reject_unsafe_crate_name("../../etc/passwd", "crates.io").is_err());
513    }
514
515    #[test]
516    fn test_reject_unsafe_crate_name_accepts_normal_names() {
517        assert!(reject_unsafe_crate_name("serde", "crates.io").is_ok());
518        assert!(reject_unsafe_crate_name("serde_derive", "crates.io").is_ok());
519        assert!(reject_unsafe_crate_name("actix-web", "crates.io").is_ok());
520    }
521
522    /// #376: `sparse_index_path`'s byte-index slicing (`name_lower[0..2]` etc.) panics on a
523    /// non-ASCII crate name, since those indices can land mid-codepoint. `is_safe_crate_name`'s
524    /// ASCII-alphanumeric-only allowlist blocks any non-ASCII input before it reaches that
525    /// code, closing the panic as a side effect of the charset check — asserted directly here
526    /// so a future narrowing of the allowlist's *intent* (without touching this exact
527    /// assertion) can't silently reopen the panic with nothing to catch it.
528    #[test]
529    fn test_reject_unsafe_crate_name_rejects_non_ascii() {
530        assert!(reject_unsafe_crate_name("日本", "crates.io").is_err());
531    }
532
533    /// Demonstrates the vulnerability `reject_unsafe_crate_name` exists to prevent:
534    /// `sparse_index_url` alone (with no caller-side guard) builds a URL that, once parsed,
535    /// has escaped the sparse index root entirely.
536    #[test]
537    fn test_sparse_index_url_bare_dot_dot_normalizes_above_root() {
538        let url = sparse_index_url("https://index.crates.io", "..");
539        let parsed = url::Url::parse(&url).unwrap();
540        assert_eq!(parsed.path(), "/", "parsed path: {}", parsed.path());
541    }
542
543    /// Demonstrates the broader S1 vulnerability: an embedded `/` (not just a bare
544    /// `.`/`..`) lets `sparse_index_url` alone build a URL whose path escapes to an
545    /// attacker-influenced location, since no character in `name` is encoded.
546    #[test]
547    fn test_sparse_index_url_embedded_slash_escapes_root() {
548        let url = sparse_index_url("https://index.crates.io", "../../etc/passwd");
549        let parsed = url::Url::parse(&url).unwrap();
550        assert_eq!(
551            parsed.path(),
552            "/etc/passwd",
553            "parsed path: {}",
554            parsed.path()
555        );
556    }
557
558    /// #365 regression sweep: exercises the real production `reject_unsafe_crate_name`
559    /// gate and `sparse_index_url` sink together against the shared adversarial input set.
560    /// Every entry is rejected by the charset-only gate before reaching the sink (none of
561    /// `ADVERSARIAL_URL_SEGMENTS` is pure ASCII-alphanumeric/`-`/`_`), so this is a vacuous
562    /// but still forward-looking regression guard: it would start exercising the
563    /// host/prefix/survival assertions the moment the gate's charset is ever loosened.
564    #[test]
565    fn test_sparse_index_url_dot_segment_sweep() {
566        deps_core::test_util::assert_dot_segment_gated_or_contained(
567            |seg| {
568                reject_unsafe_crate_name(seg, "crates.io")
569                    .ok()
570                    .map(|()| sparse_index_url("https://index.crates.io", seg))
571            },
572            "index.crates.io",
573            "/",
574        );
575    }
576
577    #[test]
578    fn test_sparse_index_url_trims_trailing_slash_on_base() {
579        let with_slash = sparse_index_url("https://index.mycorp.dev/", "serde");
580        let without_slash = sparse_index_url("https://index.mycorp.dev", "serde");
581        assert_eq!(with_slash, without_slash);
582        assert_eq!(with_slash, "https://index.mycorp.dev/se/rd/serde");
583    }
584
585    #[test]
586    fn test_parse_index_json() {
587        let json = r#"{"name":"serde","vers":"1.0.0","yanked":false,"features":{},"deps":[]}
588{"name":"serde","vers":"1.0.1","yanked":false,"features":{"derive":["serde_derive"]},"deps":[]}"#;
589
590        let versions = parse_index_json(json.as_bytes()).unwrap();
591        assert_eq!(versions.len(), 2);
592        assert_eq!(versions[0].num, "1.0.1");
593        assert_eq!(versions[1].num, "1.0.0");
594        assert!(!versions[0].yanked);
595    }
596
597    #[test]
598    fn test_parse_index_json_with_yanked() {
599        let json = r#"{"name":"test","vers":"0.1.0","yanked":true,"features":{},"deps":[]}
600{"name":"test","vers":"0.2.0","yanked":false,"features":{},"deps":[]}"#;
601
602        let versions = parse_index_json(json.as_bytes()).unwrap();
603        assert_eq!(versions.len(), 2);
604        assert!(versions[1].yanked);
605        assert!(!versions[0].yanked);
606    }
607
608    #[test]
609    fn test_parse_index_json_empty() {
610        let json = "";
611        let versions = parse_index_json(json.as_bytes()).unwrap();
612        assert_eq!(versions.len(), 0);
613    }
614
615    #[test]
616    fn test_parse_index_json_blank_lines() {
617        let json = "\n\n\n";
618        let versions = parse_index_json(json.as_bytes()).unwrap();
619        assert_eq!(versions.len(), 0);
620    }
621
622    #[test]
623    fn test_parse_index_json_invalid_version() {
624        let json = r#"{"name":"test","vers":"invalid","yanked":false,"features":{},"deps":[]}"#;
625        let versions = parse_index_json(json.as_bytes()).unwrap();
626        assert_eq!(versions.len(), 0);
627    }
628
629    #[test]
630    fn test_parse_index_json_mixed_valid_invalid() {
631        let json = r#"{"name":"test","vers":"1.0.0","yanked":false,"features":{},"deps":[]}
632{"name":"test","vers":"invalid","yanked":false,"features":{},"deps":[]}
633{"name":"test","vers":"2.0.0","yanked":false,"features":{},"deps":[]}"#;
634
635        let versions = parse_index_json(json.as_bytes()).unwrap();
636        assert_eq!(versions.len(), 2);
637        assert_eq!(versions[0].num, "2.0.0");
638        assert_eq!(versions[1].num, "1.0.0");
639    }
640
641    #[test]
642    fn test_parse_index_json_with_pubtime() {
643        let json = r#"{"name":"test","vers":"1.0.0","yanked":false,"features":{},"deps":[],"pubtime":"2026-07-18T23:05:13Z"}"#;
644
645        let versions = parse_index_json(json.as_bytes()).unwrap();
646        assert_eq!(versions.len(), 1);
647        assert_eq!(
648            versions[0].published_at,
649            Some(deps_core::PublishTime::parse_rfc3339("2026-07-18T23:05:13Z").unwrap())
650        );
651    }
652
653    #[test]
654    fn test_parse_index_json_without_pubtime() {
655        let json = r#"{"name":"test","vers":"1.0.0","yanked":false,"features":{},"deps":[]}"#;
656
657        let versions = parse_index_json(json.as_bytes()).unwrap();
658        assert_eq!(versions.len(), 1);
659        assert!(versions[0].published_at.is_none());
660    }
661
662    #[test]
663    fn test_parse_index_json_with_malformed_pubtime() {
664        let json = r#"{"name":"test","vers":"1.0.0","yanked":false,"features":{},"deps":[],"pubtime":"not-a-timestamp"}"#;
665
666        let versions = parse_index_json(json.as_bytes()).unwrap();
667        assert_eq!(versions.len(), 1);
668        assert!(
669            versions[0].published_at.is_none(),
670            "malformed pubtime degrades to None, not an error"
671        );
672    }
673
674    #[test]
675    fn test_parse_index_json_with_features() {
676        let json = r#"{"name":"test","vers":"1.0.0","yanked":false,"features":{"default":["std"],"std":[]},"deps":[]}"#;
677
678        let versions = parse_index_json(json.as_bytes()).unwrap();
679        assert_eq!(versions.len(), 1);
680        assert_eq!(versions[0].features.len(), 2);
681        assert!(versions[0].features.contains_key("default"));
682        assert!(versions[0].features.contains_key("std"));
683    }
684
685    #[test]
686    fn test_parse_index_json_nesting_at_max_depth_accepted() {
687        let depth = deps_core::MAX_JSON_NESTING_DEPTH;
688        let json = format!(
689            r#"{{"vers":"1.0.0","extra":{}1{}}}"#,
690            "[".repeat(depth - 1),
691            "]".repeat(depth - 1)
692        );
693        let versions = parse_index_json(json.as_bytes()).unwrap();
694        assert_eq!(versions.len(), 1);
695    }
696
697    #[test]
698    fn test_parse_index_json_nesting_over_max_depth_line_skipped() {
699        let depth = deps_core::MAX_JSON_NESTING_DEPTH + 1;
700        let json = format!(
701            r#"{{"vers":"1.0.0","extra":{}1{}}}"#,
702            "[".repeat(depth),
703            "]".repeat(depth)
704        );
705        let versions = parse_index_json(json.as_bytes()).unwrap();
706        assert_eq!(versions.len(), 0);
707    }
708
709    #[test]
710    fn test_sparse_index_path_single_char() {
711        assert_eq!(sparse_index_path("x"), "1/x");
712        assert_eq!(sparse_index_path("z"), "1/z");
713    }
714
715    #[test]
716    fn test_sparse_index_path_two_chars() {
717        assert_eq!(sparse_index_path("xy"), "2/xy");
718        assert_eq!(sparse_index_path("ab"), "2/ab");
719    }
720
721    #[test]
722    fn test_sparse_index_path_three_chars() {
723        assert_eq!(sparse_index_path("xyz"), "3/x/xyz");
724        assert_eq!(sparse_index_path("foo"), "3/f/foo");
725    }
726
727    #[test]
728    fn test_sparse_index_path_long_name() {
729        assert_eq!(
730            sparse_index_path("very-long-crate-name"),
731            "ve/ry/very-long-crate-name"
732        );
733    }
734
735    #[test]
736    fn test_sparse_index_path_numbers() {
737        assert_eq!(sparse_index_path("1234"), "12/34/1234");
738    }
739
740    #[test]
741    fn test_sparse_index_path_mixed_case() {
742        assert_eq!(sparse_index_path("MyPackage"), "my/pa/mypackage");
743        assert_eq!(sparse_index_path("UPPERCASE"), "up/pe/uppercase");
744    }
745
746    #[test]
747    fn test_sparse_index_path_multibyte_one_char() {
748        // "本" is 1 char / 3 bytes: byte-index slicing would panic here.
749        assert_eq!(sparse_index_path("本"), "1/本");
750    }
751
752    #[test]
753    fn test_sparse_index_path_multibyte_two_chars() {
754        // "日本" is 2 chars / 6 bytes.
755        assert_eq!(sparse_index_path("日本"), "2/日本");
756    }
757
758    #[test]
759    fn test_sparse_index_path_multibyte_three_chars() {
760        // "日本語" is 3 chars / 9 bytes. The old byte-length-keyed match would
761        // have routed this to the 4+ arm's `name_lower[0..2]`, panicking at
762        // byte index 2 (mid-character), not the 3-char arm.
763        assert_eq!(sparse_index_path("日本語"), "3/日/日本語");
764    }
765
766    #[test]
767    fn test_sparse_index_path_multibyte_four_plus_chars() {
768        // "日本ab" is 4 chars with multi-byte characters in the first two.
769        assert_eq!(sparse_index_path("日本ab"), "日本/ab/日本ab");
770    }
771
772    #[test]
773    fn test_sparse_index_path_empty_name() {
774        // 0 chars falls into the "4+" arm's slicing range; must not panic.
775        assert_eq!(sparse_index_path(""), "");
776    }
777
778    #[tokio::test]
779    async fn test_get_versions_rejects_bare_dot_dot_as_not_found() {
780        let client = SparseIndexClient::new(
781            test_index("https://index.crates.io"),
782            Arc::new(HttpCache::new()),
783            "test",
784        );
785        let err = client.get_versions("..").await.unwrap_err();
786        assert_matches!(err, DepsError::PackageNotFound { .. });
787    }
788
789    #[tokio::test]
790    async fn test_get_versions_rejects_embedded_slash_as_not_found() {
791        let client = SparseIndexClient::new(
792            test_index("https://index.crates.io"),
793            Arc::new(HttpCache::new()),
794            "test",
795        );
796        let err = client.get_versions("../../etc/passwd").await.unwrap_err();
797        assert_matches!(err, DepsError::PackageNotFound { .. });
798    }
799
800    #[tokio::test]
801    async fn test_get_versions_from_mocked_sparse_index() {
802        let mut server = mockito::Server::new_async().await;
803        let _m = server
804            .mock("GET", "/se/rd/serde")
805            .with_status(200)
806            .with_body(r#"{"name":"serde","vers":"1.0.0","yanked":false,"features":{},"deps":[]}"#)
807            .create_async()
808            .await;
809
810        let client = SparseIndexClient::new(
811            test_index(&server.url()),
812            Arc::new(HttpCache::new()),
813            "test",
814        );
815        let versions = client.get_versions("serde").await.unwrap();
816        assert_eq!(versions.len(), 1);
817        assert_eq!(versions[0].num, "1.0.0");
818    }
819
820    #[tokio::test]
821    async fn test_get_versions_with_auth_sends_authorization_header() {
822        let mut server = mockito::Server::new_async().await;
823        let _m = server
824            .mock("GET", "/se/rd/serde")
825            .match_header("authorization", "secret-token")
826            .with_status(200)
827            .with_body(r#"{"name":"serde","vers":"1.0.0","yanked":false,"features":{},"deps":[]}"#)
828            .create_async()
829            .await;
830
831        let client = SparseIndexClient::new(
832            RegistryIndex::credentialed_for_test(&server.url(), "secret-token"),
833            Arc::new(HttpCache::new()),
834            "my-corp",
835        );
836        let versions = client.get_versions("serde").await.unwrap();
837        assert_eq!(versions.len(), 1);
838    }
839
840    /// #1855: a credential bound to one operator URL is never sent to another URL, so a
841    /// workspace-declared index goes out anonymously over the workspace transport.
842    #[tokio::test]
843    async fn test_credential_for_another_url_is_never_sent() {
844        let mut server = mockito::Server::new_async().await;
845        let mock = server
846            .mock("GET", "/se/rd/serde")
847            .match_header("authorization", mockito::Matcher::Missing)
848            .with_status(200)
849            .with_body(r#"{"name":"serde","vers":"1.0.0","yanked":false,"features":{},"deps":[]}"#)
850            .expect(1)
851            .create_async()
852            .await;
853
854        let other = "https://operator.example/index";
855        let mut operator = CargoOperator::declaring(OperatorRegistries::declared_in(
856            &deps_core::config_trust::OperatorPath::for_test("/test/.cargo/config.toml"),
857            [other],
858        ));
859        operator.bind(
860            crate::config::strip_sparse_prefix(other),
861            AuthToken::new("secret-token".to_string()),
862        );
863        let index = RegistryIndex::declared_bound(
864            crate::config::strip_sparse_prefix(&server.url()),
865            &operator,
866            &RegistryAccessPolicy::new(deps_core::net_policy::WorkspaceRegistryAccess::All),
867        )
868        .unwrap();
869        assert_eq!(index.trust(), RegistryTrust::WorkspaceDeclared);
870        assert!(!index.has_credential());
871
872        let client = SparseIndexClient::new(index, Arc::new(HttpCache::new()), "workspace index");
873        assert!(!client.has_auth());
874        client.get_versions("serde").await.unwrap();
875        mock.assert_async().await;
876    }
877
878    // Issue #455, test-plan item 9 (C2 routing): a successful `(None, WorkspaceDeclared)` fetch
879    // lands under the workspace cache-key namespace, not the baseline one — proven via the
880    // public `peek_cached` API (which only ever reads the baseline namespace) rather than by
881    // reaching into `HttpCache`'s private fields.
882    #[tokio::test]
883    async fn test_fetch_routes_workspace_declared_through_workspace_cache_namespace() {
884        let mut server = mockito::Server::new_async().await;
885        let _m = server
886            .mock("GET", "/se/rd/serde")
887            .with_status(200)
888            .with_body(r#"{"name":"serde","vers":"1.0.0","yanked":false,"features":{},"deps":[]}"#)
889            .create_async()
890            .await;
891
892        let cache = Arc::new(HttpCache::new());
893        let client = SparseIndexClient::new(
894            test_workspace_index(&server.url()),
895            Arc::clone(&cache),
896            "test",
897        );
898        let versions = client.get_versions("serde").await.unwrap();
899        assert_eq!(versions.len(), 1);
900
901        let index_url = format!("{}/se/rd/serde", server.url());
902        assert!(
903            cache.peek_cached(&index_url).is_none(),
904            "a WorkspaceDeclared fetch must not land under the baseline (peek_cached-visible) \
905             cache-key namespace"
906        );
907    }
908
909    #[tokio::test]
910    async fn test_get_latest_matching_via_sparse_client() {
911        let mut server = mockito::Server::new_async().await;
912        let _m = server
913            .mock("GET", "/se/rd/serde")
914            .with_status(200)
915            .with_body(
916                "{\"name\":\"serde\",\"vers\":\"1.0.0\",\"yanked\":false,\"features\":{},\"deps\":[]}\n\
917                 {\"name\":\"serde\",\"vers\":\"2.0.0\",\"yanked\":false,\"features\":{},\"deps\":[]}",
918            )
919            .create_async()
920            .await;
921
922        let client = SparseIndexClient::new(
923            test_index(&server.url()),
924            Arc::new(HttpCache::new()),
925            "test",
926        );
927        let latest = client.get_latest_matching("serde", "^1.0").await.unwrap();
928        assert_eq!(latest.unwrap().num, "1.0.0");
929    }
930}