Skip to main content

deps_cargo/
config.rs

1//! `.cargo/config.toml` discovery and `[registries.*]`/`[source.*]` resolution.
2//!
3//! Resolves a Cargo `registry = "<alias>"` dependency's alias into a concrete, fetchable
4//! sparse index URL by reading the same `.cargo/config.toml` hierarchy (and
5//! `$CARGO_HOME/config.toml`) Cargo itself consults, plus the
6//! `CARGO_REGISTRIES_<NAME>_INDEX`/`_TOKEN` environment variable overrides Cargo
7//! documents. Also resolves a `[source.crates-io] replace-with` chain into a mirror index
8//! for plain (`Registry`-sourced) dependencies (spec FR-005/006/007).
9//!
10//! # Security model (read before touching this module)
11//!
12//! A workspace's own `Cargo.toml`/`.cargo/config.toml` is attacker-controlled the moment a
13//! hostile repository is cloned and opened — this LSP parses on file open, before any build
14//! ever runs. Two related threats this module closes, each by its own decision:
15//!
16//! - **Egress** (where a request may go, #443). Every index URL is classified by the shared
17//!   URL-alone rule, [`OperatorRegistries::classify`]: a URL equal to one the operator declared
18//!   (`$CARGO_HOME/config.toml`, or a `CARGO_REGISTRIES_<ALIAS>_INDEX` variable) is
19//!   [`RegistryTrust::Trusted`] and skips the workspace policy; any other URL is
20//!   [`RegistryTrust::WorkspaceDeclared`] and is checked against the live
21//!   [`deps_core::net_policy::RegistryAccessPolicy`]. The never-a-registry floor applies to both,
22//!   so a `$CARGO_HOME` registry on a loopback or link-local host is rejected. Provenance plays no
23//!   part: a workspace alias that names an operator URL gets the operator URL's trust.
24//! - **Credential exfiltration.** A credential is a separate decision and lives inside
25//!   [`RegistryIndex`] as `IndexAccess::Credentialed`, which exists only for an index that
26//!   classified Trusted. It is bound to a *URL the operator declared*: the same URL gets the same
27//!   credential whichever alias or manifest field names it, so the result never depends on
28//!   registration order, and no other URL ever gets one. Enforced **structurally**:
29//!   - `parse_workspace_registries_raw` has no return type capable of expressing a token.
30//!   - Only `parse_cargo_home_registries_raw` and the `CARGO_REGISTRIES_<ALIAS>_TOKEN` lookup
31//!     produce an `AuthToken`, and `cargo_operator_with_env` binds each to the URL its alias
32//!     declares. An index receives a credential only through `RegistryIndex::declared_bound`,
33//!     from that binding, and only when the URL classified Trusted.
34//!   - No constructor takes a [`Provenance`] or a [`RegistryTrust`]: a caller cannot assert trust,
35//!     only present a URL to the operator set. [`Provenance`] is diagnostics only.
36//!   - A request carrying a credential travels over an origin-confined transport, so a redirect
37//!     cannot move the header to another origin.
38//!
39//! See spec `specs/023-cargo-custom-registries/spec.md` FR-008/FR-009, spec 084 and the
40//! design review handoffs cited there for the rounds of critique the credential boundary
41//! survived.
42
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45use std::sync::Arc;
46use toml_span::value::Table;
47
48use deps_core::config_trust::{
49    EnvPath, OperatorEnvName, OperatorEnvValue, OperatorEnvVar, OperatorPath,
50};
51use deps_core::native_cooldown::{
52    NativeCooldown, NativeCooldownSource, NativeLimit, NativeTimeSpan, RegistryAlias,
53    TimeSpanValue, parse_time_span,
54};
55use deps_core::net_policy::{
56    BlockedHost, DeclaredRegistry, EnvSource, IndexUrlError, OperatorRegistries, ProcessEnv,
57    RedactedUrl, RegistryAccessPolicy, RegistryRejectionClassifier, RegistryRejectionReason,
58    RegistryUrlKind, TrustedConstantRegistryUrl, TrustedPrefix, ValidatedRegistryUrl,
59};
60use deps_core::{DEFAULT_MAX_CACHED_FILES, EcosystemId, MtimeFileCache};
61
62/// A registry bearer-token credential, redacted everywhere except the one call site that
63/// formats it into an `Authorization` header.
64///
65/// Constructible only from within this module (see the module-level security-model docs) —
66/// no other code path in this crate has the means to produce one. A thin wrapper over
67/// [`deps_core::secret::Redacted`] rather than a bare type alias: `Debug` prints
68/// `AuthToken(***)`, not `Redacted(***)`, so a panic message or log line still names which
69/// credential leaked its type.
70#[derive(Clone, PartialEq, Eq)]
71pub(crate) struct AuthToken(deps_core::secret::Redacted);
72
73impl AuthToken {
74    /// Wraps `token`. Kept `pub(crate)`: the module-level security-model docs above are the
75    /// enforcement, and a token only ever reaches an index through `RegistryIndex::declared_bound`.
76    pub(crate) fn new(token: String) -> Self {
77        Self(deps_core::secret::Redacted::new(token))
78    }
79
80    /// The wrapped secret, for building the `Authorization` value.
81    pub(crate) const fn as_redacted(&self) -> &deps_core::secret::Redacted {
82        &self.0
83    }
84
85    /// The raw token value, for asserting on it in tests.
86    #[cfg(test)]
87    pub(crate) fn expose_secret(&self) -> &str {
88        self.0.expose_secret()
89    }
90}
91
92impl std::fmt::Debug for AuthToken {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str("AuthToken(***)")
95    }
96}
97
98impl std::fmt::Display for AuthToken {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.write_str("***")
101    }
102}
103
104/// Where a [`ResolvedRegistryEntry`] came from.
105///
106/// **Diagnostics and logging only.** Nothing decides egress or a credential from it: the
107/// egress decision is the URL-alone rule ([`OperatorRegistries::classify`]) and a credential is
108/// held by the [`RegistryIndex`] itself (see the module-level docs). A change that starts
109/// branching on this to decide either reintroduces the vulnerability class this design closed.
110///
111/// **Exhaustive** (issue #769): a closed 2-variant `CargoHome`/`Workspace` split.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Provenance {
114    /// Resolved from `$CARGO_HOME/config.toml` or a `CARGO_REGISTRIES_*` environment
115    /// variable — the user's own trusted environment, not something a cloned repository
116    /// controls.
117    CargoHome,
118    /// Resolved from a `.cargo/config.toml` found while walking up from the opened
119    /// manifest's directory — a file a repository being opened can fully control.
120    Workspace,
121}
122
123/// Cargo's registry trust is the core [`RegistryTrust`]: the same URL-alone rule as Go, npm,
124/// NuGet and Swift decides it, and it decides egress only. Whether a credential is sent is a
125/// separate decision held by [`RegistryIndex`] (#1855).
126pub use deps_core::net_policy::RegistryTrust;
127
128/// The less-trusted of `a` and `b` — `WorkspaceDeclared` if either is, `Trusted` only if both
129/// are.
130///
131/// Used by [`crate::registry::CargoRegistry::register_alternate`] (issue #455, C3) to fold a
132/// re-registration of the same index URL to the stricter of its old and new trust tier.
133pub(crate) const fn stricter(a: RegistryTrust, b: RegistryTrust) -> RegistryTrust {
134    match (a, b) {
135        (RegistryTrust::WorkspaceDeclared, _) | (_, RegistryTrust::WorkspaceDeclared) => {
136            RegistryTrust::WorkspaceDeclared
137        }
138        (RegistryTrust::Trusted, RegistryTrust::Trusted) => RegistryTrust::Trusted,
139    }
140}
141
142/// The `sparse+` protocol prefix Cargo allows on an index URL.
143const SPARSE_PREFIX: &str = "sparse+";
144
145/// An index URL text with its optional `sparse+` prefix removed.
146///
147/// Only [`strip_sparse_prefix`] makes one, and every consumer takes this type, so a value is
148/// stripped exactly once and the operator set and the classifier always see the same text (a
149/// second strip of `sparse+sparse+https://…` would classify a different URL than was declared).
150#[derive(Debug, Clone, Copy)]
151pub(crate) struct StrippedIndexUrl<'a>(&'a str);
152
153impl<'a> StrippedIndexUrl<'a> {
154    pub(crate) const fn as_str(self) -> &'a str {
155        self.0
156    }
157}
158
159/// `raw` without a leading `sparse+`.
160pub(crate) fn strip_sparse_prefix(raw: &str) -> StrippedIndexUrl<'_> {
161    StrippedIndexUrl(raw.strip_prefix(SPARSE_PREFIX).unwrap_or(raw))
162}
163
164/// [`RegistryUrlKind`] marker selecting Cargo's validation rules for an index URL.
165pub enum CargoIndexKind {}
166
167impl deps_core::net_policy::private::Sealed for CargoIndexKind {}
168
169impl RegistryUrlKind for CargoIndexKind {
170    const ECOSYSTEM: EcosystemId = EcosystemId::Cargo;
171    const REJECT_QUERY_FRAGMENT: bool = false;
172    type Error = RegistryIndexError;
173}
174
175impl TrustedConstantRegistryUrl for CargoIndexKind {}
176
177/// Why a candidate index URL failed [`RegistryIndex::declared`]'s validation.
178///
179/// An alias of the shared [`deps_core::net_policy::IndexUrlError`] — see that type's docs
180/// for the variants and their wording.
181pub use deps_core::net_policy::IndexUrlError as RegistryIndexError;
182
183/// A credential for a registry index the operator declared.
184///
185/// Its only constructor takes the classification of the index it is for and returns it only for
186/// [`RegistryTrust::Trusted`], so a credential for a workspace-declared index cannot be built.
187#[derive(Clone, PartialEq, Eq)]
188struct OperatorCredential(AuthToken);
189
190impl OperatorCredential {
191    fn for_trusted(
192        token: AuthToken,
193        classified: &DeclaredRegistry<CargoIndexKind>,
194    ) -> Option<Self> {
195        match classified.trust() {
196            RegistryTrust::Trusted => Some(Self(token)),
197            RegistryTrust::WorkspaceDeclared => None,
198        }
199    }
200}
201
202impl std::fmt::Debug for OperatorCredential {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        f.write_str("OperatorCredential(***)")
205    }
206}
207
208/// How requests against a [`RegistryIndex`] authenticate.
209///
210/// `Credentialed` implies [`RegistryTrust::Trusted`]: its only constructor is
211/// [`OperatorCredential::for_trusted`]. `Anonymous` carries the URL-alone classification.
212#[derive(Debug, Clone, PartialEq, Eq)]
213enum IndexAccess {
214    Credentialed(OperatorCredential),
215    Anonymous(RegistryTrust),
216}
217
218/// A validated, `sparse+`-prefix-stripped sparse-index URL.
219///
220/// `https` scheme, no userinfo, and (for a [`RegistryTrust::WorkspaceDeclared`] candidate) a host
221/// the live [`deps_core::net_policy::RegistryAccessPolicy`] allows. Validated at construction so
222/// an invalid or unsafe URL (`http://`, a scheme other than `sparse+https`, a `user:pass@`
223/// component, or a workspace-declared host the policy blocks) can never reach a network call —
224/// this is SSRF-adjacent input, since a workspace file controls a network destination (spec
225/// NFR-002, plan-1b §1.1-§1.2).
226///
227/// Carries its own credential, if it has one: egress trust and credential are two decisions,
228/// and the credential exists only for a URL the operator declared (see the module docs).
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct RegistryIndex {
231    url: ValidatedRegistryUrl<CargoIndexKind>,
232    base: TrustedPrefix,
233    access: IndexAccess,
234}
235
236/// Everything the operator declared for Cargo: the registry URLs, and the credentials bound to
237/// them by URL equality.
238///
239/// Built from `$CARGO_HOME/config.toml` and the `CARGO_REGISTRIES_*` variables of the whole
240/// process environment, never from the manifest being parsed, so it is the same for every
241/// manifest and every alias order. A credential is looked up by the classified URL of an index,
242/// whichever alias or manifest field named it.
243#[derive(Default)]
244pub(crate) struct CargoOperator {
245    registries: OperatorRegistries,
246    credentials: HashMap<String, AuthToken>,
247}
248
249impl std::fmt::Debug for CargoOperator {
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        f.debug_struct("CargoOperator")
252            .field("registries", &self.registries)
253            .field("credentials", &self.credentials.len())
254            .finish()
255    }
256}
257
258impl CargoOperator {
259    /// An operator that declares `registries` and binds no credential.
260    pub(crate) fn declaring(registries: OperatorRegistries) -> Self {
261        Self {
262            registries,
263            credentials: HashMap::new(),
264        }
265    }
266
267    /// Binds `token` to the URL `stripped` when the operator declares it and it passes the
268    /// never-a-registry floor. The first binding of a URL wins, so callers bind in a fixed order.
269    pub(crate) fn bind(&mut self, stripped: StrippedIndexUrl<'_>, token: AuthToken) {
270        let text = stripped.as_str();
271        let policy = RegistryAccessPolicy::default();
272        if let Ok(classified) = self
273            .registries
274            .classify::<CargoIndexKind>(text, text, &policy)
275        {
276            self.credentials
277                .entry(classified.as_str().to_string())
278                .or_insert(token);
279        }
280    }
281}
282
283impl RegistryIndex {
284    fn from_classified(
285        classified: DeclaredRegistry<CargoIndexKind>,
286        credential: Option<&AuthToken>,
287    ) -> Result<Self, RegistryIndexError> {
288        let base = TrustedPrefix::parse(classified.as_str())
289            .map_err(|_| IndexUrlError::InvalidUrl(RedactedUrl::new(classified.as_str())))?;
290        let access = match credential
291            .and_then(|token| OperatorCredential::for_trusted(token.clone(), &classified))
292        {
293            Some(credential) => IndexAccess::Credentialed(credential),
294            None => IndexAccess::Anonymous(classified.trust()),
295        };
296        Ok(Self {
297            url: classified.url().clone(),
298            base,
299            access,
300        })
301    }
302
303    /// Validates and classifies `raw` — a `registry-index` manifest value, a
304    /// `.cargo/config.toml` `[registries.<name>].index` value, or a `[source.<name>]
305    /// registry` value, either optionally prefixed with `sparse+` — with no credential.
306    ///
307    /// A URL equal to one in `operator` is [`RegistryTrust::Trusted`] and skips the workspace
308    /// policy; any other URL is checked against `policy`. The never-a-registry floor applies to
309    /// both.
310    ///
311    /// # Errors
312    ///
313    /// Returns [`RegistryIndexError`] if `raw` does not parse as a URL, is not `https`,
314    /// carries a userinfo component, resolves to a host class that is never a registry, or (for
315    /// a workspace-declared URL) to a host class the current policy blocks.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use deps_cargo::config::{RegistryIndex, RegistryTrust};
321    /// use deps_core::net_policy::{OperatorRegistries, RegistryAccessPolicy};
322    ///
323    /// let policy = RegistryAccessPolicy::default();
324    /// let none = OperatorRegistries::default();
325    /// let index = RegistryIndex::declared("sparse+https://index.mycorp.dev", &none, &policy)
326    ///     .unwrap();
327    /// assert_eq!(index.trust(), RegistryTrust::WorkspaceDeclared);
328    /// assert!(RegistryIndex::declared("http://index.mycorp.dev", &none, &policy).is_err());
329    /// assert!(
330    ///     RegistryIndex::declared("https://user:pass@index.mycorp.dev", &none, &policy).is_err()
331    /// );
332    /// ```
333    pub fn declared(
334        raw: &str,
335        operator: &OperatorRegistries,
336        policy: &RegistryAccessPolicy,
337    ) -> Result<Self, RegistryIndexError> {
338        let stripped = strip_sparse_prefix(raw).as_str();
339        Self::from_classified(
340            operator.classify::<CargoIndexKind>(stripped, stripped, policy)?,
341            None,
342        )
343    }
344
345    /// [`Self::declared`] against the full [`CargoOperator`], for a value whose `sparse+` prefix
346    /// is already stripped: an index the operator declared also gets the credential the operator
347    /// bound to its URL, whichever alias or manifest field named it.
348    pub(crate) fn declared_bound(
349        stripped: StrippedIndexUrl<'_>,
350        operator: &CargoOperator,
351        policy: &RegistryAccessPolicy,
352    ) -> Result<Self, RegistryIndexError> {
353        let text = stripped.as_str();
354        let classified = operator
355            .registries
356            .classify::<CargoIndexKind>(text, text, policy)?;
357        let credential = operator.credentials.get(classified.as_str());
358        Self::from_classified(classified, credential)
359    }
360
361    /// Wraps a compile-time-known-safe literal (e.g. crates.io's own sparse index base), which
362    /// is [`RegistryTrust::Trusted`] without an operator file vouching for it.
363    ///
364    /// `pub(crate)` — for a literal known at compile time, not a workspace-provenance value.
365    ///
366    /// # Panics
367    ///
368    /// Panics if `raw` fails validation. Covered by a unit test so this panic is unreachable in
369    /// practice.
370    #[must_use]
371    pub(crate) fn builtin(raw: &'static str) -> Self {
372        DeclaredRegistry::<CargoIndexKind>::trusted_constant(raw)
373            .and_then(|classified| Self::from_classified(classified, None))
374            .unwrap_or_else(|error| {
375                panic!("builtin registry index {raw:?} failed validation: {error}")
376            })
377    }
378
379    /// The normalized URL, never carrying a trailing `/`.
380    #[must_use]
381    pub fn as_str(&self) -> &str {
382        self.url.as_str()
383    }
384
385    /// This index as a [`TrustedPrefix`] (no re-parse).
386    #[must_use]
387    pub(crate) fn trusted_prefix(&self) -> TrustedPrefix {
388        self.base.clone()
389    }
390
391    /// The [`RegistryTrust`] the URL-alone rule gave this index.
392    #[must_use]
393    pub const fn trust(&self) -> RegistryTrust {
394        match self.access {
395            IndexAccess::Credentialed(_) => RegistryTrust::Trusted,
396            IndexAccess::Anonymous(trust) => trust,
397        }
398    }
399
400    /// Whether requests against this index carry a credential. The credential itself is never
401    /// exposed outside the crate.
402    #[must_use]
403    pub const fn has_credential(&self) -> bool {
404        matches!(self.access, IndexAccess::Credentialed(_))
405    }
406
407    /// The credential, when the index has one.
408    pub(crate) const fn credential(&self) -> Option<&AuthToken> {
409        match &self.access {
410            IndexAccess::Credentialed(credential) => Some(&credential.0),
411            IndexAccess::Anonymous(_) => None,
412        }
413    }
414
415    /// Test-only: an anonymous index of the given trust, built through the same classification
416    /// path as production (an operator set holding `raw` for [`RegistryTrust::Trusted`]).
417    ///
418    /// # Panics
419    ///
420    /// Panics if `raw` fails validation.
421    #[cfg(any(test, feature = "test-util"))]
422    #[must_use]
423    pub fn for_test(raw: &str, trust: RegistryTrust) -> Self {
424        let operator = Self::test_operator(raw, trust, None);
425        Self::declared_bound(strip_sparse_prefix(raw), &operator, &Self::test_policy())
426            .unwrap_or_else(|error| panic!("test index {raw:?} failed validation: {error}"))
427    }
428
429    /// Test-only: [`Self::for_test`] for a Trusted index that carries `token`.
430    ///
431    /// # Panics
432    ///
433    /// Panics if `raw` fails validation.
434    #[cfg(any(test, feature = "test-util"))]
435    #[must_use]
436    pub fn credentialed_for_test(raw: &str, token: &str) -> Self {
437        let operator = Self::test_operator(raw, RegistryTrust::Trusted, Some(token));
438        Self::declared_bound(strip_sparse_prefix(raw), &operator, &Self::test_policy())
439            .unwrap_or_else(|error| panic!("test index {raw:?} failed validation: {error}"))
440    }
441
442    #[cfg(any(test, feature = "test-util"))]
443    fn test_policy() -> RegistryAccessPolicy {
444        RegistryAccessPolicy::new(deps_core::net_policy::WorkspaceRegistryAccess::All)
445    }
446
447    #[cfg(any(test, feature = "test-util"))]
448    fn test_operator(raw: &str, trust: RegistryTrust, token: Option<&str>) -> CargoOperator {
449        let stripped = strip_sparse_prefix(raw);
450        let mut operator = match trust {
451            RegistryTrust::Trusted => CargoOperator::declaring(OperatorRegistries::declared_in(
452                &OperatorPath::for_test("/test/.cargo/config.toml"),
453                [stripped.as_str()],
454            )),
455            RegistryTrust::WorkspaceDeclared => CargoOperator::default(),
456        };
457        if let Some(token) = token {
458            operator.bind(stripped, AuthToken::new(token.to_string()));
459        }
460        operator
461    }
462}
463
464impl std::fmt::Display for RegistryIndex {
465    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        f.write_str(self.as_str())
467    }
468}
469
470/// One resolved `[registries.<name>]` entry.
471///
472/// Output-only: constructed internally by this module's own resolution logic, never by
473/// external code — no constructor is provided.
474#[non_exhaustive]
475#[derive(Debug, Clone)]
476pub struct ResolvedRegistryEntry {
477    /// The validated, fetchable index. Carries its own credential, if it has one.
478    pub index: RegistryIndex,
479    /// Where this entry was resolved from. Diagnostics/logging only.
480    pub provenance: Provenance,
481}
482
483/// The merged, resolved view of a workspace's `.cargo/config.toml` hierarchy plus
484/// `$CARGO_HOME/config.toml`, for the aliases a manifest actually referenced.
485///
486/// Built by [`resolve`] — this type itself is a plain lookup table with no resolution
487/// logic of its own, so a caller holding one can check [`Self::get`] without needing to
488/// know anything about tiers, precedence, or the environment.
489#[derive(Debug, Default)]
490pub struct CargoConfig {
491    registries: HashMap<String, ResolvedRegistryEntry>,
492    /// Aliases whose resolution failed, paired with why (issue #1468 item 4). Previously two
493    /// disjoint `HashMap<String, _>`s (`blocked`/`rejected`) — resolution only ever inserts
494    /// one or the other for a given alias, never both, but that "at most one" invariant was
495    /// only a convention encoded in call order (`blocked_class` checked before
496    /// `rejected_reason` at every caller); [`UnresolvedIndex`] makes it a structural
497    /// impossibility instead, since a single map slot can only ever hold one variant.
498    unresolved: HashMap<String, UnresolvedIndex>,
499}
500
501/// Why a `.cargo/config.toml`/`$CARGO_HOME` alias failed to resolve to a usable registry
502/// index — see [`CargoConfig::blocked_class`]/[`CargoConfig::rejected_reason`].
503#[derive(Debug, Clone, Copy)]
504enum UnresolvedIndex {
505    /// The current [`deps_core::net_policy::RegistryAccessPolicy`] blocked the candidate
506    /// host (spec #443, plan-1b §1.7) — as opposed to "no matching config entry" or any
507    /// other validation failure. Surfaced by `crate::parser::resolve_alternate_registries`
508    /// as a positional diagnostic on the offending dependency's line.
509    Blocked(BlockedHost),
510    /// The `.cargo/config.toml` `[registries.<name>] index = ...` entry failed validation
511    /// for a reason other than a policy-blocked host (#1453, mirrors [`Self::Blocked`]) —
512    /// an invalid URL, a non-https scheme, or embedded userinfo. Surfaced the same way
513    /// [`Self::Blocked`] is.
514    Rejected(RegistryRejectionReason),
515}
516
517impl UnresolvedIndex {
518    /// The cause a failed validation is surfaced as, if it is surfaced at all.
519    fn from_error(error: &RegistryIndexError) -> Option<Self> {
520        match error {
521            RegistryIndexError::BlockedHost { block } => Some(Self::Blocked(*block)),
522            other => other.rejection_reason().into_reason().map(Self::Rejected),
523        }
524    }
525}
526
527impl CargoConfig {
528    /// The resolved entry for `alias`, if it resolved successfully.
529    #[must_use]
530    pub fn get(&self, alias: &str) -> Option<&ResolvedRegistryEntry> {
531        self.registries.get(alias)
532    }
533
534    /// The host class that blocked `alias`'s resolution, if that (and specifically that) is
535    /// why it did not resolve.
536    #[must_use]
537    pub(crate) fn blocked_class(&self, alias: &str) -> Option<BlockedHost> {
538        match self.unresolved.get(alias) {
539            Some(UnresolvedIndex::Blocked(host)) => Some(*host),
540            Some(UnresolvedIndex::Rejected(_)) | None => None,
541        }
542    }
543
544    /// [`Self::blocked_class`]'s counterpart for every rejection reason other than a
545    /// policy-blocked host (#1453) — why `alias`'s `[registries.<name>] index = ...` entry
546    /// failed validation, if that (and specifically that) is why it did not resolve.
547    #[must_use]
548    pub(crate) fn rejected_reason(&self, alias: &str) -> Option<RegistryRejectionReason> {
549        match self.unresolved.get(alias) {
550            Some(UnresolvedIndex::Rejected(reason)) => Some(*reason),
551            Some(UnresolvedIndex::Blocked(_)) | None => None,
552        }
553    }
554}
555
556/// Where a `[source.crates-io] replace-with` chain resolved to, for plain (`Registry`-sourced)
557/// dependencies (spec FR-005/FR-006/FR-007).
558#[non_exhaustive]
559#[derive(Debug, Clone, PartialEq)]
560pub enum SourceReplacement {
561    /// No `[source]` override applies — no `[source.crates-io]` table, a `directory`/
562    /// `local-registry`/non-sparse-git terminal (FR-006), a cyclic/unbounded chain
563    /// (FR-007), or a terminal that failed [`RegistryIndex::declared`]'s validation/policy gate.
564    /// Plain dependencies keep resolving against crates.io, unchanged from today.
565    None,
566    /// The chain terminated at a `sparse+https://` index (FR-005).
567    SparseMirror {
568        /// The validated, fetchable mirror index. It carries a credential only when every link
569        /// of the chain is an operator link (plan-1b §1.4's "coupled trust trap" guard): a
570        /// single workspace-tier link anywhere in the chain leaves it anonymous, even if the
571        /// terminal itself is a `$CARGO_HOME` `[registries]` entry carrying a token.
572        index: RegistryIndex,
573    },
574}
575
576/// A raw (unvalidated) `[source.<name>]` table entry, as parsed from one config file —
577/// unvalidated because validation ([`RegistryIndex::declared`]'s policy gate, in particular)
578/// must run per parse against the live policy, never cached (plan-1b §1.5(b)).
579#[derive(Debug, Clone, PartialEq, Eq)]
580struct SourceEntry {
581    /// The table's own kind, if it declares one recognizable by [`classify_source_kind`].
582    /// `None` for a table with neither a `registry`/`directory`/`local-registry`/`git`
583    /// field nor (therefore) any classification — e.g. a bare `[source.crates-io]
584    /// replace-with = "..."` table, which has no kind of its own.
585    kind: Option<SourceKind>,
586    /// This table's own `replace-with` value, if any.
587    replace_with: Option<String>,
588}
589
590/// The kind of source a `[source.<name>]` table declares — classified purely by the
591/// `sparse+` prefix on a `registry` value (spec FR-005/FR-006), never carrying an
592/// [`RegistryTrust`] of its own: trust is derived from the [`CachedTier`] the containing file
593/// belongs to at merge time, not tagged per entry (plan-1b §1.4/§1.5(c) — the same
594/// "per-entry tag a later reader must get right" hazard §1.5(c) already eliminated for
595/// `[registries]` entries).
596#[derive(Debug, Clone, PartialEq, Eq)]
597enum SourceKind {
598    /// `registry = "sparse+https://…"` — a terminal FR-005 candidate.
599    SparseRegistry {
600        /// The raw (unvalidated, `sparse+`-prefixed) index value.
601        raw: String,
602    },
603    /// `registry = "<bare https git index>"`, `directory = "…"`, `git = "…"`, or
604    /// `local-registry = "…"` — a terminal that keeps resolving plain dependencies against
605    /// crates.io, unchanged (FR-006/US-003).
606    NonSparse,
607}
608
609/// Classifies a `[source.<name>]` table's own kind, per [`SourceKind`]'s doc.
610fn classify_source_kind(entry: &Table<'_>) -> Option<SourceKind> {
611    if let Some(registry) = entry.get("registry").and_then(|v| v.as_str()) {
612        return Some(if registry.starts_with("sparse+") {
613            SourceKind::SparseRegistry {
614                raw: registry.to_string(),
615            }
616        } else {
617            SourceKind::NonSparse
618        });
619    }
620    let has_non_sparse_field = ["directory", "local-registry", "git"]
621        .iter()
622        .any(|field| entry.get(*field).and_then(|v| v.as_str()).is_some());
623    if has_non_sparse_field {
624        return Some(SourceKind::NonSparse);
625    }
626    None
627}
628
629/// Upper bound on the number of `[source.<name>]` tables read from a single config file
630/// (M6): the nesting-depth guard already bounds table *depth*, not table *count*, so this
631/// exists to bound that separately-unbounded dimension. `visited`-set cycle detection
632/// already bounds chain-following iteration on top of this.
633const MAX_SOURCE_ENTRIES: usize = 256;
634
635/// Parses one config file's `[source.<name>]` tables into raw (unvalidated) entries.
636///
637/// Shared by both tiers — a `[source]` table carries no token concept of its own (unlike
638/// `[registries]`), so there is nothing tier-specific about this extraction; the tier only
639/// matters when this file's [`SourceEntry`]s are later merged into a chain-resolution walk
640/// (see [`resolve_source_chain`]).
641fn parse_source_entries_raw(content: &str) -> HashMap<String, SourceEntry> {
642    let mut out = HashMap::new();
643    let doc = match deps_core::parse_toml_checked(content) {
644        Ok(doc) => doc,
645        Err(deps_core::CheckedTomlError::NestingTooDeep { .. }) => {
646            tracing::warn!("skipping [source] tables: nesting depth exceeds maximum");
647            return out;
648        }
649        Err(deps_core::CheckedTomlError::Syntax(_)) => return out,
650    };
651    let Some(sources) = doc
652        .as_table()
653        .and_then(|t| t.get("source"))
654        .and_then(|v| v.as_table())
655    else {
656        return out;
657    };
658    for (key, value) in sources {
659        if out.len() >= MAX_SOURCE_ENTRIES {
660            tracing::warn!(
661                cap = MAX_SOURCE_ENTRIES,
662                "[source] table count exceeds maximum; ignoring remaining entries"
663            );
664            break;
665        }
666        let Some(entry_table) = value.as_table() else {
667            continue;
668        };
669        let kind = classify_source_kind(entry_table);
670        let replace_with = entry_table
671            .get("replace-with")
672            .and_then(|v| v.as_str())
673            .map(String::from);
674        out.insert(key.name.to_string(), SourceEntry { kind, replace_with });
675    }
676    out
677}
678
679/// Parses a table value's `index` field into a raw (unvalidated) string, warning and
680/// returning `None` only when the field is missing or not a string — actual URL validation
681/// happens per parse in [`RegistryIndex::declared`], never here (plan-1b §1.5(b)): caching a
682/// validated `RegistryIndex` would go stale across a `didChangeConfiguration` policy change.
683fn parse_raw_index_field(entry: &Table<'_>) -> Option<String> {
684    entry
685        .get("index")
686        .and_then(|v| v.as_str())
687        .map(String::from)
688}
689
690/// Parses a workspace-declared `.cargo/config.toml`'s `[registries.<name>]` table into
691/// alias -> raw index string entries.
692///
693/// **No `token` field exists anywhere in this function's return type.** This is the
694/// structural half of the auth-provenance guarantee described in the module docs — a
695/// workspace-tier [`CachedTier::Workspace`] cannot represent a token at all, so no later
696/// reader can populate one for a workspace-sourced entry even by mistake (plan-1b §1.5(c)).
697fn parse_workspace_registries_raw(content: &str) -> HashMap<String, String> {
698    let mut out = HashMap::new();
699    let doc = match deps_core::parse_toml_checked(content) {
700        Ok(doc) => doc,
701        Err(deps_core::CheckedTomlError::NestingTooDeep { .. }) => {
702            tracing::warn!("skipping .cargo/config.toml: nesting depth exceeds maximum");
703            return out;
704        }
705        Err(deps_core::CheckedTomlError::Syntax(_)) => return out,
706    };
707    let Some(registries) = doc
708        .as_table()
709        .and_then(|t| t.get("registries"))
710        .and_then(|v| v.as_table())
711    else {
712        return out;
713    };
714    for (key, value) in registries {
715        let Some(entry) = value.as_table() else {
716            continue;
717        };
718        if let Some(raw_index) = parse_raw_index_field(entry) {
719            out.insert(key.name.to_string(), raw_index);
720        }
721    }
722    out
723}
724
725/// Parses `$CARGO_HOME/config.toml`'s `[registries.<name>]` table into alias -> (raw index,
726/// token) entries — the one function in this module permitted to construct a populated
727/// [`AuthToken`], since its input is, by construction, always `$CARGO_HOME`-sourced.
728fn parse_cargo_home_registries_raw(content: &str) -> HashMap<String, (String, Option<AuthToken>)> {
729    let mut out = HashMap::new();
730    let doc = match deps_core::parse_toml_checked(content) {
731        Ok(doc) => doc,
732        Err(deps_core::CheckedTomlError::NestingTooDeep { .. }) => {
733            tracing::warn!("skipping $CARGO_HOME/config.toml: nesting depth exceeds maximum");
734            return out;
735        }
736        Err(deps_core::CheckedTomlError::Syntax(_)) => return out,
737    };
738    let Some(registries) = doc
739        .as_table()
740        .and_then(|t| t.get("registries"))
741        .and_then(|v| v.as_table())
742    else {
743        return out;
744    };
745    for (key, value) in registries {
746        let Some(entry) = value.as_table() else {
747            continue;
748        };
749        let Some(raw_index) = parse_raw_index_field(entry) else {
750            continue;
751        };
752        let token = entry
753            .get("token")
754            .and_then(|v| v.as_str())
755            .map(|t| AuthToken::new(t.to_string()));
756        out.insert(key.name.to_string(), (raw_index, token));
757    }
758    out
759}
760
761/// Cargo's env-var naming convention for a registry setting: uppercase the alias and
762/// replace every `-` with `_` (Cargo does the same substitution, which is exactly why two
763/// spellings of "the same" alias can collide — see spec FR-015).
764fn env_var_name(alias: &str, suffix: &'static str) -> OperatorEnvName {
765    OperatorEnvName::prefixed(ENV_REGISTRY_PREFIX, alias, suffix)
766}
767
768/// One tier's raw registries table, plus the raw `[source]` tables from the same file —
769/// cached per config-file path by [`deps_core::MtimeFileCache`], keyed on mtime for
770/// invalidation (plan-1b §1.5(a)).
771///
772/// **Absence is never cached** (N5): only a file that existed, was a regular file, and
773/// parsed successfully gets an entry — a `.cargo/config.toml` created after the cache was
774/// first populated is picked up on the very next parse with no extra bookkeeping, since the
775/// ancestor walk re-checks existence every parse regardless.
776#[derive(Debug)]
777struct ParsedConfigFile {
778    tier: CachedTier,
779    sources: HashMap<String, SourceEntry>,
780    native: NativeConfigFile,
781}
782
783/// Which tier a [`ParsedConfigFile`] belongs to, chosen once — by the same
784/// canonicalized-path comparison against `$CARGO_HOME/config.toml` that already decides
785/// precedence in [`resolve`] — rather than becoming a per-entry tag later code must read
786/// correctly (plan-1b §1.5(c)).
787///
788/// The `Workspace` variant's map is `HashMap<String, String>`, with **no token field
789/// anywhere in its type** — [`parse_workspace_registries_raw`] keeps the guarantee its doc
790/// comment already claims: a function whose body has no code path that could populate one.
791#[derive(Debug)]
792enum CachedTier {
793    /// A `.cargo/config.toml` found by the ancestor walk. Alias -> raw index string.
794    Workspace(HashMap<String, String>),
795    /// `$CARGO_HOME/config.toml`. Alias -> (raw index string, token).
796    CargoHome(HashMap<String, (String, Option<AuthToken>)>),
797}
798
799/// What one config file says about a single publish-age key.
800#[derive(Debug, Clone, Copy)]
801enum RawNativeValue {
802    /// A valid non-zero span.
803    Window(NativeTimeSpan),
804    /// A zero value: the window is explicitly off at this key.
805    Disabled,
806    /// A malformed, overflowing or non-string value: treated as if the key were absent.
807    Invalid,
808}
809
810/// The publish-age keys of one `.cargo/config.toml` (`registry.global-min-publish-age`,
811/// `registries.<name>.min-publish-age`, `resolver.incompatible-publish-age`), parsed once per
812/// cached file together with the one-shot warning for its invalid values.
813///
814/// The warning is emitted by [`Self::warn_invalid_once`] from the read path, not at parse
815/// time, so a file read only with the window ignored never logs.
816#[derive(Debug, Default)]
817struct NativeConfigFile {
818    global: Option<RawNativeValue>,
819    per_registry: HashMap<String, RawNativeValue>,
820    allow_incompatible: Option<bool>,
821    invalid_keys: Vec<String>,
822    warned: std::sync::atomic::AtomicBool,
823}
824
825impl NativeConfigFile {
826    fn parse(content: &str) -> Self {
827        let mut file = Self::default();
828        let Ok(doc) = deps_core::parse_toml_checked(content) else {
829            return file;
830        };
831        let Some(root) = doc.as_table() else {
832            return file;
833        };
834        if let Some(registry) = root.get("registry").and_then(|v| v.as_table()) {
835            file.global = file.read_span(registry, "global-min-publish-age", "registry.");
836        }
837        if let Some(registries) = root.get("registries").and_then(|v| v.as_table()) {
838            for (alias, entry) in registries {
839                let Some(entry) = entry.as_table() else {
840                    continue;
841                };
842                let prefix = format!(
843                    "registries.{}.",
844                    deps_core::redact::sanitize_invisible(&alias.name)
845                );
846                if let Some(value) = file.read_span(entry, "min-publish-age", &prefix) {
847                    file.per_registry.insert(alias.name.to_string(), value);
848                }
849            }
850        }
851        // Only `allow` disables the window; anything else reads as `deny`.
852        if let Some(mode) = root
853            .get("resolver")
854            .and_then(|v| v.as_table())
855            .and_then(|resolver| resolver.get("incompatible-publish-age"))
856        {
857            match mode.as_str() {
858                Some("allow") => file.allow_incompatible = Some(true),
859                Some("deny") => file.allow_incompatible = Some(false),
860                Some(_) | None => file
861                    .invalid_keys
862                    .push("resolver.incompatible-publish-age".to_owned()),
863            }
864        }
865        file
866    }
867
868    fn read_span(&mut self, table: &Table<'_>, key: &str, prefix: &str) -> Option<RawNativeValue> {
869        let value = table.get(key)?;
870        Some(match value.as_str().map(parse_time_span) {
871            Some(Ok(TimeSpanValue::Span(span))) => RawNativeValue::Window(span),
872            Some(Ok(TimeSpanValue::Disabled)) => RawNativeValue::Disabled,
873            Some(Err(_)) | None => {
874                self.invalid_keys.push(format!("{prefix}{key}"));
875                RawNativeValue::Invalid
876            }
877        })
878    }
879
880    /// Emits one warning for the whole file, naming it, the number of malformed keys and the
881    /// first few, so a hostile config cannot flood the log.
882    fn warn_invalid_once(&self, path: &Path) {
883        const MAX_NAMED_KEYS: usize = 5;
884        if self.invalid_keys.is_empty() {
885            return;
886        }
887        if self.warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
888            return;
889        }
890        let keys = self
891            .invalid_keys
892            .iter()
893            .take(MAX_NAMED_KEYS)
894            .map(String::as_str)
895            .collect::<Vec<_>>()
896            .join(", ");
897        tracing::warn!(
898            path = %path.display(),
899            count = self.invalid_keys.len(),
900            %keys,
901            "ignoring malformed Cargo publish-age settings; no window applies from them"
902        );
903    }
904}
905
906/// Which publish-age setting scope a dependency falls under.
907#[derive(Debug, Clone, PartialEq, Eq, Hash)]
908pub(crate) enum NativeScope {
909    /// A plain registry dependency, or one whose crates.io source is replaced by a mirror:
910    /// `registries.crates-io.min-publish-age`, then the global key. Cargo keys the lookup on the
911    /// package's original source id (`resolver/version_prefs.rs`, `min_age`), so a replacement
912    /// keeps the `crates-io` key.
913    CratesIo,
914    /// `registry = "<alias>"`: `registries.<alias>.min-publish-age`, then the global key.
915    Alias(String),
916    /// A literal `registry-index`: only the global key (the index has no name to key on).
917    LiteralIndex,
918}
919
920impl NativeScope {
921    fn registry_key(&self) -> Option<&str> {
922        match self {
923            Self::CratesIo => Some("crates-io"),
924            Self::Alias(alias) => Some(alias),
925            Self::LiteralIndex => None,
926        }
927    }
928}
929
930/// Resolves the publish-age window for `scope` from `config_paths` (closest-first, already
931/// limited to the repository boundary by the caller).
932///
933/// Follows Cargo's per-key config merge: the closest file declaring a valid value for a key
934/// wins; the scope's own registry key beats the global key; a zero value at the winning key
935/// turns the window off; `resolver.incompatible-publish-age = "allow"` turns it off outright.
936/// An invalid value counts as absent, so a nearer malformed value falls through to the next valid
937/// one in a farther file (Cargo itself would reject the config), and is reported in one warning
938/// per cached file. A malformed `incompatible-publish-age` reads as the `deny` default.
939pub(crate) fn resolve_native_cooldown(
940    scope: &NativeScope,
941    config_paths: &[PathBuf],
942    config_cache: &ConfigFileCache,
943) -> Option<NativeCooldown> {
944    let files: Vec<Arc<ParsedConfigFile>> = config_paths
945        .iter()
946        .filter_map(|path| {
947            let file = config_cache.get_or_parse_workspace(path)?;
948            file.native.warn_invalid_once(path);
949            Some(file)
950        })
951        .collect();
952    if files
953        .iter()
954        .find_map(|file| file.native.allow_incompatible)
955        .unwrap_or(false)
956    {
957        return None;
958    }
959    let first_valid = |lookup: &dyn Fn(&NativeConfigFile) -> Option<RawNativeValue>| {
960        files.iter().find_map(|file| {
961            lookup(&file.native).filter(|value| !matches!(value, RawNativeValue::Invalid))
962        })
963    };
964    if let Some(alias) = scope.registry_key().and_then(RegistryAlias::new)
965        && let Some(value) = first_valid(&|file| file.per_registry.get(alias.as_str()).copied())
966    {
967        return match value {
968            RawNativeValue::Window(span) => Some(NativeCooldown::new(
969                NativeLimit::MinAge(span),
970                NativeCooldownSource::CargoRegistry { alias },
971            )),
972            RawNativeValue::Disabled | RawNativeValue::Invalid => None,
973        };
974    }
975    match first_valid(&|file| file.global)? {
976        RawNativeValue::Window(span) => Some(NativeCooldown::new(
977            NativeLimit::MinAge(span),
978            NativeCooldownSource::CargoGlobal,
979        )),
980        RawNativeValue::Disabled | RawNativeValue::Invalid => None,
981    }
982}
983
984/// Per-config-file memoization for `.cargo/config.toml`/`$CARGO_HOME/config.toml` parsing
985/// (spec NFR-005, plan-1b §1.5).
986///
987/// Caches **raw**, unvalidated tables — alias filtering, env overrides,
988/// [`RegistryIndex::declared`] validation, and `[source]` chain walking all run **per parse**
989/// against these cached tables, never cached themselves. This is what keeps a policy change
990/// (`didChangeConfiguration`), a newly-referenced alias, or an env-var change taking effect
991/// immediately without any cache invalidation of their own.
992///
993/// Owned by `crate::parser::CargoParseContext` and shared across every document this
994/// ecosystem parses, so hundreds of workspace members sharing one `.cargo/config.toml`
995/// collapse to a single cached entry. A thin newtype over [`deps_core::MtimeFileCache`] —
996/// the mtime-gated caching mechanism itself lives there, shared with `deps-npm`.
997#[derive(Debug)]
998pub struct ConfigFileCache(MtimeFileCache<ParsedConfigFile>);
999
1000impl Default for ConfigFileCache {
1001    fn default() -> Self {
1002        Self::new()
1003    }
1004}
1005
1006impl ConfigFileCache {
1007    /// Creates an empty cache.
1008    #[must_use]
1009    pub fn new() -> Self {
1010        Self(MtimeFileCache::new(
1011            DEFAULT_MAX_CACHED_FILES,
1012            "cargo config",
1013        ))
1014    }
1015
1016    /// Returns `path`'s parsed workspace-tier contents, from cache if `path`'s mtime is
1017    /// unchanged, else re-reading and re-parsing.
1018    fn get_or_parse_workspace(&self, path: &Path) -> Option<Arc<ParsedConfigFile>> {
1019        self.0.get_or_parse(path, |content| ParsedConfigFile {
1020            tier: CachedTier::Workspace(parse_workspace_registries_raw(content)),
1021            sources: parse_source_entries_raw(content),
1022            native: NativeConfigFile::parse(content),
1023        })
1024    }
1025
1026    /// [`Self::get_or_parse_workspace`], but for `$CARGO_HOME/config.toml`.
1027    fn get_or_parse_cargo_home(&self, path: &Path) -> Option<Arc<ParsedConfigFile>> {
1028        self.0.get_or_parse(path, |content| ParsedConfigFile {
1029            tier: CachedTier::CargoHome(parse_cargo_home_registries_raw(content)),
1030            sources: parse_source_entries_raw(content),
1031            native: NativeConfigFile::parse(content),
1032        })
1033    }
1034}
1035
1036/// `$CARGO_HOME/config.toml`'s path, or `None` if `$CARGO_HOME` is unset or relative.
1037///
1038/// Deliberately reads only the `CARGO_HOME` environment variable — no fallback to
1039/// `$HOME`/`%USERPROFILE%` when it is unset (spec FR-004), and no `dirs`/`home` crate
1040/// dependency added to compute one. A relative `CARGO_HOME` would resolve against a directory a
1041/// repository can influence, so it names no operator-owned location and is ignored.
1042#[must_use]
1043pub fn cargo_home_config_path() -> Option<OperatorPath> {
1044    cargo_home_config_path_with_env(&ProcessEnv)
1045}
1046
1047/// [`cargo_home_config_path`], but reading the environment through `env` instead of the process
1048/// environment — lets tests inject a fake environment instead of mutating the real
1049/// (`unsafe`-only, since Rust 2024) process environment.
1050pub(crate) fn cargo_home_config_path_with_env(
1051    env: &(impl EnvSource + ?Sized),
1052) -> Option<OperatorPath> {
1053    match OperatorPath::from_env(env, OperatorEnvVar::CargoHome) {
1054        EnvPath::Path(home) => Some(home.join("config.toml")),
1055        EnvPath::Unset => None,
1056        EnvPath::Ignored => {
1057            tracing::warn!("ignoring a relative CARGO_HOME: it names no operator-owned location");
1058            None
1059        }
1060    }
1061}
1062
1063/// The loaded, per-file tiers a [`resolve`] call operates against — workspace tiers
1064/// closest-first, plus the (at most one) `$CARGO_HOME` tier, both already excluding the
1065/// canonicalized-path duplicate case (see [`resolve_with_env`]'s doc).
1066struct LoadedTiers {
1067    workspace: Vec<Arc<ParsedConfigFile>>,
1068    cargo_home: Option<Arc<ParsedConfigFile>>,
1069}
1070
1071fn load_tiers(
1072    workspace_config_paths: &[PathBuf],
1073    cargo_home_config_path: Option<&OperatorPath>,
1074    config_cache: &ConfigFileCache,
1075) -> LoadedTiers {
1076    let cargo_home_path = cargo_home_config_path.map(OperatorPath::as_path);
1077    // Under the default layout, `~/.cargo/config.toml` is also found by the workspace-tier
1078    // walk — uncompared, it'd double-count as workspace-tier, winning over the real
1079    // `$CARGO_HOME` tier and silently dropping its token. Canonicalizing also catches a
1080    // symlinked `$CARGO_HOME`.
1081    let cargo_home_canonical = cargo_home_path.and_then(|p| std::fs::canonicalize(p).ok());
1082
1083    let workspace = workspace_config_paths
1084        .iter()
1085        .filter(|path| {
1086            std::fs::canonicalize(path).ok().as_deref() != cargo_home_canonical.as_deref()
1087        })
1088        .filter_map(|path| config_cache.get_or_parse_workspace(path))
1089        .collect();
1090
1091    let cargo_home = cargo_home_path.and_then(|path| config_cache.get_or_parse_cargo_home(path));
1092
1093    LoadedTiers {
1094        workspace,
1095        cargo_home,
1096    }
1097}
1098
1099/// Resolves `referenced_aliases` against the `.cargo/config.toml` hierarchy and
1100/// `$CARGO_HOME/config.toml`.
1101///
1102/// Separately resolves the `[source.crates-io] replace-with` chain (if any) for plain
1103/// dependencies.
1104///
1105/// `referenced_aliases` is every distinct `registry = "<alias>"` value this manifest's
1106/// dependencies declared; `workspace_config_paths` and `cargo_home_config_path` come from
1107/// `crate::parser`'s merged ancestor walk (closest-first); `config_cache` memoizes each
1108/// distinct config file's raw contents (spec NFR-005); `policy` gates every
1109/// [`RegistryTrust::WorkspaceDeclared`] [`RegistryIndex`] this call constructs.
1110///
1111/// # Trust
1112///
1113/// The operator set is every index URL `$CARGO_HOME/config.toml` declares (`[registries]` and
1114/// `[source]` sparse terminals) plus the value of every `CARGO_REGISTRIES_<ALIAS>_INDEX`
1115/// variable of the process environment, independent of which aliases this manifest references.
1116/// Every index, whichever file or field named it, is classified against that set by
1117/// [`OperatorRegistries::classify`]. A credential is bound to a URL the operator declared and
1118/// follows that URL, so the result never depends on alias or registration order.
1119///
1120/// # Precedence
1121///
1122/// For one alias (or the `[source]` chain): the closest workspace `.cargo/config.toml`
1123/// entry wins outright — if it resolves, the `$CARGO_HOME` tier (config file and
1124/// environment variables alike) is never consulted for that alias at all. This is a
1125/// deliberate divergence from Cargo's own env-beats-all-config-files precedence: an
1126/// environment variable can never redirect an alias a workspace file has shadowed (spec
1127/// FR-009/US-004) — see the module-level security-model docs.
1128///
1129/// # Examples
1130///
1131/// ```
1132/// use deps_cargo::config::{ConfigFileCache, SourceReplacement, resolve};
1133/// use deps_core::net_policy::RegistryAccessPolicy;
1134/// use std::collections::HashSet;
1135///
1136/// let aliases: HashSet<String> = std::iter::once("unconfigured".to_string()).collect();
1137/// let cache = ConfigFileCache::new();
1138/// let policy = RegistryAccessPolicy::default();
1139/// let (config, source_replacement) = resolve(&aliases, &[], None, &cache, &policy);
1140/// assert!(config.get("unconfigured").is_none());
1141/// assert_eq!(source_replacement, SourceReplacement::None);
1142/// ```
1143#[must_use]
1144pub fn resolve(
1145    referenced_aliases: &HashSet<String>,
1146    workspace_config_paths: &[PathBuf],
1147    cargo_home_config_path: Option<&OperatorPath>,
1148    config_cache: &ConfigFileCache,
1149    policy: &RegistryAccessPolicy,
1150) -> (CargoConfig, SourceReplacement) {
1151    resolve_with_env(
1152        referenced_aliases,
1153        workspace_config_paths,
1154        cargo_home_config_path,
1155        config_cache,
1156        policy,
1157        &ProcessEnv,
1158    )
1159}
1160
1161/// [`resolve`], but reading environment variables through `env` instead of the process
1162/// environment — lets tests inject a fake environment instead of mutating the real process
1163/// environment (this workspace forbids `unsafe`, and Rust 2024 made
1164/// `std::env::set_var`/`remove_var` `unsafe fn`s, so a test cannot do that mutation at
1165/// all). Production callers always go through [`resolve`].
1166pub(crate) fn resolve_with_env(
1167    referenced_aliases: &HashSet<String>,
1168    workspace_config_paths: &[PathBuf],
1169    cargo_home_config_path: Option<&OperatorPath>,
1170    config_cache: &ConfigFileCache,
1171    policy: &RegistryAccessPolicy,
1172    env: &(impl EnvSource + ?Sized),
1173) -> (CargoConfig, SourceReplacement) {
1174    let tiers = load_tiers(workspace_config_paths, cargo_home_config_path, config_cache);
1175    let operator = cargo_operator_with_env(cargo_home_config_path, config_cache, env);
1176
1177    let env_collided = env_collided_aliases(referenced_aliases);
1178    let env_indexes = read_env_indexes(referenced_aliases, &env_collided, env);
1179
1180    let registries =
1181        resolve_registries(referenced_aliases, &tiers, &operator, &env_indexes, policy);
1182    let source_replacement = resolve_source_chain(&tiers, &operator, policy);
1183
1184    (registries, source_replacement)
1185}
1186
1187const ENV_REGISTRY_PREFIX: &str = "CARGO_REGISTRIES_";
1188const ENV_INDEX_SUFFIX: &str = "_INDEX";
1189const ENV_TOKEN_SUFFIX: &str = "_TOKEN";
1190
1191/// Text of an index value for the operator set: the same `sparse+` removal the classifier uses.
1192fn stripped_text(raw: &str) -> &str {
1193    strip_sparse_prefix(raw).as_str()
1194}
1195
1196fn cargo_index_urls(raw: &str) -> Vec<&str> {
1197    vec![stripped_text(raw)]
1198}
1199
1200/// Builds the [`CargoOperator`]: every URL declared by `$CARGO_HOME/config.toml` and by a
1201/// `CARGO_REGISTRIES_*_INDEX` variable, and the credentials bound to them. Independent of any
1202/// manifest, so every manifest of a process classifies a URL the same way.
1203///
1204/// A token is bound to the URL its alias (or variable) declares, with the environment token
1205/// beating the file token; where two aliases give one URL different tokens, the alias that sorts
1206/// first wins, so the result is deterministic.
1207pub(crate) fn cargo_operator_with_env(
1208    cargo_home_config_path: Option<&OperatorPath>,
1209    config_cache: &ConfigFileCache,
1210    env: &(impl EnvSource + ?Sized),
1211) -> CargoOperator {
1212    let file = cargo_home_config_path.and_then(|path| {
1213        config_cache
1214            .get_or_parse_cargo_home(path.as_path())
1215            .map(|file| (path, file))
1216    });
1217
1218    let env_index_vars = OperatorEnvName::discovered(env, ENV_REGISTRY_PREFIX, ENV_INDEX_SUFFIX);
1219
1220    let mut registries = match &file {
1221        Some((path, file)) => {
1222            OperatorRegistries::declared_in(path, cargo_home_index_values(file).map(stripped_text))
1223        }
1224        None => OperatorRegistries::default(),
1225    };
1226    for index_var in &env_index_vars {
1227        if let Some(value) = OperatorEnvValue::read(env, index_var) {
1228            registries.extend(OperatorRegistries::declared_by_env(
1229                &value,
1230                cargo_index_urls,
1231            ));
1232        }
1233    }
1234    let mut operator = CargoOperator::declaring(registries);
1235
1236    let mut covered_env_vars = HashSet::new();
1237    if let Some((_, file)) = &file
1238        && let CachedTier::CargoHome(map) = &file.tier
1239    {
1240        let mut aliases: Vec<&String> = map.keys().collect();
1241        aliases.sort();
1242        for alias in aliases {
1243            let Some((raw_index, file_token)) = map.get(alias) else {
1244                continue;
1245            };
1246            let index_var = env_var_name(alias, "INDEX");
1247            let token =
1248                env_token(env, &env_var_name(alias, "TOKEN")).or_else(|| file_token.clone());
1249            if let Some(token) = token {
1250                if let Some(env_index) = OperatorEnvValue::read(env, &index_var) {
1251                    operator.bind(strip_sparse_prefix(env_index.as_str()), token.clone());
1252                }
1253                operator.bind(strip_sparse_prefix(raw_index), token);
1254            }
1255            covered_env_vars.insert(index_var);
1256        }
1257    }
1258    for index_var in &env_index_vars {
1259        if covered_env_vars.contains(index_var) {
1260            continue;
1261        }
1262        let Some(token_var) = index_var.with_suffix_replaced(ENV_INDEX_SUFFIX, ENV_TOKEN_SUFFIX)
1263        else {
1264            continue;
1265        };
1266        if let (Some(raw_index), Some(token)) = (
1267            OperatorEnvValue::read(env, index_var),
1268            env_token(env, &token_var),
1269        ) {
1270            operator.bind(strip_sparse_prefix(raw_index.as_str()), token);
1271        }
1272    }
1273    operator
1274}
1275
1276/// Aliases whose derived `CARGO_REGISTRIES_*` variable name collides with another referenced
1277/// alias's (FR-015): two spellings deriving the same env-var name (e.g. "my-corp"/"my_corp")
1278/// must not let either pick up an override meant for the other. Detected once over the whole
1279/// set — a per-alias check would have nothing to compare against.
1280fn env_collided_aliases(referenced_aliases: &HashSet<String>) -> HashSet<&str> {
1281    let mut env_name_to_aliases: HashMap<OperatorEnvName, Vec<&String>> = HashMap::new();
1282    for alias in referenced_aliases {
1283        env_name_to_aliases
1284            .entry(env_var_name(alias, "INDEX"))
1285            .or_default()
1286            .push(alias);
1287    }
1288    env_name_to_aliases
1289        .values()
1290        .filter(|aliases| aliases.len() > 1)
1291        .flat_map(|aliases| {
1292            let names: Vec<&str> = aliases.iter().map(|s| s.as_str()).collect();
1293            // Same as `resolve_alternate_registries`' unresolved-alias WARN (#536): `alias` may
1294            // itself carry `user:pass@` userinfo or a query-string credential, so redact with
1295            // `RedactedUrl` (not `redact_userinfo` alone, which keeps the query — #767).
1296            let redacted: Vec<RedactedUrl> =
1297                names.iter().map(|name| RedactedUrl::new(name)).collect();
1298            tracing::warn!(
1299                aliases = ?redacted,
1300                "two aliases derive the same CARGO_REGISTRIES_*_INDEX/_TOKEN environment \
1301                 variable name; ignoring the environment override for all of them"
1302            );
1303            names
1304        })
1305        .collect()
1306}
1307
1308/// The raw `CARGO_REGISTRIES_<ALIAS>_INDEX` value of every referenced alias that did not
1309/// collide, keyed by alias.
1310fn read_env_indexes(
1311    referenced_aliases: &HashSet<String>,
1312    env_collided: &HashSet<&str>,
1313    env: &(impl EnvSource + ?Sized),
1314) -> HashMap<String, OperatorEnvValue> {
1315    referenced_aliases
1316        .iter()
1317        .filter(|alias| !env_collided.contains(alias.as_str()))
1318        .filter_map(|alias| {
1319            OperatorEnvValue::read(env, &env_var_name(alias, "INDEX"))
1320                .map(|value| (alias.clone(), value))
1321        })
1322        .collect()
1323}
1324
1325/// The registry token in environment variable `name`, when set and valid Unicode.
1326fn env_token(env: &(impl EnvSource + ?Sized), name: &OperatorEnvName) -> Option<AuthToken> {
1327    env.var_os(name.as_str())
1328        .and_then(|value| value.into_string().ok())
1329        .map(AuthToken::new)
1330}
1331
1332/// Every index URL a `$CARGO_HOME` config file declares: its `[registries]` entries and its
1333/// `[source]` tables that end at a `sparse+` registry.
1334fn cargo_home_index_values(file: &ParsedConfigFile) -> impl Iterator<Item = &str> {
1335    let registries = match &file.tier {
1336        CachedTier::CargoHome(map) => Some(map.values().map(|(raw, _token)| raw.as_str())),
1337        CachedTier::Workspace(_) => None,
1338    };
1339    let sources = file.sources.values().filter_map(|entry| match &entry.kind {
1340        Some(SourceKind::SparseRegistry { raw }) => Some(raw.as_str()),
1341        Some(SourceKind::NonSparse) | None => None,
1342    });
1343    registries.into_iter().flatten().chain(sources)
1344}
1345
1346fn resolve_registries(
1347    referenced_aliases: &HashSet<String>,
1348    tiers: &LoadedTiers,
1349    operator: &CargoOperator,
1350    env_indexes: &HashMap<String, OperatorEnvValue>,
1351    policy: &RegistryAccessPolicy,
1352) -> CargoConfig {
1353    let mut registries = HashMap::new();
1354    let mut unresolved = HashMap::new();
1355    for alias in referenced_aliases {
1356        if let Some(raw_index) = tiers.workspace.iter().find_map(|file| match &file.tier {
1357            CachedTier::Workspace(map) => map.get(alias),
1358            CachedTier::CargoHome(_) => None,
1359        }) {
1360            match RegistryIndex::declared_bound(strip_sparse_prefix(raw_index), operator, policy) {
1361                Ok(index) => {
1362                    registries.insert(
1363                        alias.clone(),
1364                        ResolvedRegistryEntry {
1365                            index,
1366                            provenance: Provenance::Workspace,
1367                        },
1368                    );
1369                }
1370                Err(error) => {
1371                    if let Some(cause) = UnresolvedIndex::from_error(&error) {
1372                        unresolved.insert(alias.clone(), cause);
1373                    }
1374                    tracing::warn!(alias, %error, "registry index failed validation");
1375                }
1376            }
1377            continue;
1378        }
1379
1380        match resolve_cargo_home_tier(
1381            alias,
1382            tiers.cargo_home.as_deref(),
1383            env_indexes.get(alias).map(OperatorEnvValue::as_str),
1384            operator,
1385            policy,
1386        ) {
1387            CargoHomeResolution::Resolved(entry) => {
1388                registries.insert(alias.clone(), entry);
1389            }
1390            CargoHomeResolution::Unresolved(cause) => {
1391                unresolved.insert(alias.clone(), cause);
1392            }
1393            CargoHomeResolution::Absent => {}
1394        }
1395    }
1396
1397    CargoConfig {
1398        registries,
1399        unresolved,
1400    }
1401}
1402
1403/// Outcome of [`resolve_cargo_home_tier`].
1404enum CargoHomeResolution {
1405    /// Resolved to a usable index (possibly with a credential).
1406    Resolved(ResolvedRegistryEntry),
1407    /// A `CARGO_REGISTRIES_*_INDEX` override or `$CARGO_HOME/config.toml` entry existed but
1408    /// failed validation (#1453 S1). The operator's own URLs skip the workspace policy, so a
1409    /// [`UnresolvedIndex::Blocked`] here can only be the never-a-registry floor; the other
1410    /// rejections (`InvalidUrl`/`NotHttps`/`UserInfoPresent`) apply too. This tier used to drop
1411    /// such an entry silently with only a `tracing::warn!`, exactly the #1453 shape for a
1412    /// workspace-tier entry.
1413    Unresolved(UnresolvedIndex),
1414    /// No entry at all — the ordinary "alias not configured in this tier" outcome.
1415    Absent,
1416}
1417
1418/// Resolves one alias against the `$CARGO_HOME` tier: the environment-variable index override
1419/// `env_index` first (when one was read for this alias), then `$CARGO_HOME/config.toml`'s own
1420/// entry.
1421fn resolve_cargo_home_tier(
1422    alias: &str,
1423    cargo_home_file: Option<&ParsedConfigFile>,
1424    env_index: Option<&str>,
1425    operator: &CargoOperator,
1426    policy: &RegistryAccessPolicy,
1427) -> CargoHomeResolution {
1428    let cargo_home_map = cargo_home_file.and_then(|file| match &file.tier {
1429        CachedTier::CargoHome(map) => Some(map),
1430        CachedTier::Workspace(_) => None,
1431    });
1432
1433    // #1453 S1: an invalid env override still falls through to the file tier exactly as
1434    // before — only remembered here so its failure can be reported if the file tier also
1435    // yields nothing usable (a valid file-tier entry silently wins, matching the pre-#1453
1436    // "env override failed, fall back" behavior).
1437    let mut env_failure = None;
1438    if let Some(index_override) = env_index {
1439        match RegistryIndex::declared_bound(strip_sparse_prefix(index_override), operator, policy) {
1440            Ok(index) => {
1441                return CargoHomeResolution::Resolved(ResolvedRegistryEntry {
1442                    index,
1443                    provenance: Provenance::CargoHome,
1444                });
1445            }
1446            Err(error) => {
1447                tracing::warn!(alias, %error, "CARGO_REGISTRIES_*_INDEX environment override failed validation");
1448                env_failure = UnresolvedIndex::from_error(&error);
1449            }
1450        }
1451    }
1452
1453    let Some((raw_index, _token)) = cargo_home_map.and_then(|map| map.get(alias)) else {
1454        return env_failure.map_or(CargoHomeResolution::Absent, CargoHomeResolution::Unresolved);
1455    };
1456    match RegistryIndex::declared_bound(strip_sparse_prefix(raw_index), operator, policy) {
1457        Ok(index) => CargoHomeResolution::Resolved(ResolvedRegistryEntry {
1458            index,
1459            provenance: Provenance::CargoHome,
1460        }),
1461        Err(error) => {
1462            tracing::warn!(alias, %error, "registry index failed validation");
1463            // #1453 code-review finding 3: when the env override *and* the file-tier entry
1464            // are both invalid, prefer the env override's own reason — it was the first
1465            // (and, per this function's own precedence, the intended) value for this alias;
1466            // reporting the file-tier's unrelated failure instead would misattribute why the
1467            // env override the user actually set didn't take effect.
1468            env_failure
1469                .or_else(|| UnresolvedIndex::from_error(&error))
1470                .map_or(CargoHomeResolution::Absent, CargoHomeResolution::Unresolved)
1471        }
1472    }
1473}
1474
1475/// Upper bound on `[source]` replace-with chain hops, on top of the `visited`-set cycle
1476/// check — belt-and-braces (plan-1b §6 M6): the `visited` set alone already bounds a chain
1477/// to at most the number of distinct source ids ever declared, but a small explicit cap
1478/// keeps a pathological (though non-cyclic) chain from doing unbounded work in one parse.
1479const MAX_SOURCE_REPLACEMENT_HOPS: usize = 16;
1480
1481/// Looks up `id` in the merged, raw `[registries]` tables (stage 1 of `[source]` id
1482/// resolution, spec FR-005's "two-stage: alias -> source id", critic S4) — closest
1483/// workspace tier first, then `$CARGO_HOME`. Returns only the raw index string; a credential is
1484/// bound later, by the classified URL.
1485fn lookup_raw_registry_index<'a>(id: &str, tiers: &'a LoadedTiers) -> Option<&'a str> {
1486    for file in &tiers.workspace {
1487        if let CachedTier::Workspace(map) = &file.tier
1488            && let Some(raw) = map.get(id)
1489        {
1490            return Some(raw.as_str());
1491        }
1492    }
1493    if let Some(file) = &tiers.cargo_home
1494        && let CachedTier::CargoHome(map) = &file.tier
1495        && let Some((raw, _token)) = map.get(id)
1496    {
1497        return Some(raw.as_str());
1498    }
1499    None
1500}
1501
1502/// Resolves the `[source.crates-io] replace-with` chain (spec FR-005/006/007, plan-1b §1.4).
1503///
1504/// Two-stage id resolution at every hop: the merged `[source]` tables first, then (stage 1,
1505/// critic S4) the merged `[registries]` tables via [`lookup_raw_registry_index`] — a
1506/// `[registries]` hit is terminal by construction, since a `[registries]` entry has no
1507/// `replace-with` of its own.
1508fn resolve_source_chain(
1509    tiers: &LoadedTiers,
1510    operator: &CargoOperator,
1511    policy: &RegistryAccessPolicy,
1512) -> SourceReplacement {
1513    let mut current_id = "crates-io".to_string();
1514    let mut visited: HashSet<String> = HashSet::new();
1515
1516    for _hop in 0..MAX_SOURCE_REPLACEMENT_HOPS {
1517        if !visited.insert(current_id.clone()) {
1518            tracing::warn!(
1519                id = ?current_id,
1520                "[source] replace-with chain is cyclic; leaving crates-io unresolved"
1521            );
1522            return SourceReplacement::None;
1523        }
1524
1525        let found_source = tiers
1526            .workspace
1527            .iter()
1528            .find_map(|file| file.sources.get(&current_id))
1529            .or_else(|| {
1530                tiers
1531                    .cargo_home
1532                    .as_deref()
1533                    .and_then(|file| file.sources.get(&current_id))
1534            });
1535
1536        if let Some(entry) = found_source {
1537            // Cargo resolves `replace-with` **before** consulting the table's own kind (critic
1538            // S2): an explicit `registry =`/`directory =`/etc. alongside `replace-with` does
1539            // not disable the replacement — the shape most public mirror setup docs publish
1540            // verbatim. Checking `kind` first (an earlier revision) silently dropped it.
1541            if let Some(next_id) = &entry.replace_with {
1542                current_id = next_id.clone();
1543                continue;
1544            }
1545            match &entry.kind {
1546                Some(SourceKind::SparseRegistry { raw }) => {
1547                    return finalize_source_replacement(raw, &current_id, operator, policy);
1548                }
1549                Some(SourceKind::NonSparse) | None => {
1550                    return SourceReplacement::None;
1551                }
1552            }
1553        }
1554
1555        // Stage 1 (critic S4): not declared as a `[source]` entry — try a `[registries]`
1556        // crossover before giving up on this id.
1557        if let Some(raw_index) = lookup_raw_registry_index(&current_id, tiers) {
1558            if raw_index.starts_with(SPARSE_PREFIX) {
1559                return finalize_source_replacement(raw_index, &current_id, operator, policy);
1560            }
1561            return SourceReplacement::None;
1562        }
1563
1564        // Unknown id — most commonly no `[source.crates-io]` table declared at all.
1565        return SourceReplacement::None;
1566    }
1567
1568    tracing::warn!(
1569        max_hops = MAX_SOURCE_REPLACEMENT_HOPS,
1570        "[source] replace-with chain exceeded the maximum hop count; leaving crates-io unresolved"
1571    );
1572    SourceReplacement::None
1573}
1574
1575fn finalize_source_replacement(
1576    raw: &str,
1577    terminal_id: &str,
1578    operator: &CargoOperator,
1579    policy: &RegistryAccessPolicy,
1580) -> SourceReplacement {
1581    match RegistryIndex::declared_bound(strip_sparse_prefix(raw), operator, policy) {
1582        Ok(index) => SourceReplacement::SparseMirror { index },
1583        Err(error) => {
1584            tracing::warn!(
1585                id = terminal_id,
1586                %error,
1587                "[source] replace-with terminal index failed validation/policy; leaving crates-io unresolved"
1588            );
1589            SourceReplacement::None
1590        }
1591    }
1592}
1593
1594/// Every distinct alias `dependencies` declares via `registry = "<alias>"`.
1595///
1596/// This is the input [`resolve`] needs to know which aliases are actually worth
1597/// resolving, so config discovery is skipped entirely (spec NFR-004) when this is empty.
1598#[must_use]
1599pub fn referenced_aliases(dependencies: &[crate::types::CargoDependency]) -> HashSet<String> {
1600    dependencies
1601        .iter()
1602        .filter_map(|dep| match &dep.source {
1603            deps_core::parser::DependencySource::CustomRegistry { url } => Some(url.clone()),
1604            _ => None,
1605        })
1606        .collect()
1607}
1608
1609#[cfg(test)]
1610mod tests {
1611    use super::*;
1612    use deps_core::net_policy::{MapEnv, WorkspaceRegistryAccess};
1613    use std::assert_matches;
1614
1615    #[test]
1616    fn test_registry_index_trusted_prefix_matches_index_and_confines_to_its_path() {
1617        let index = RegistryIndex::builtin("https://artifacts.corp/cargo/index");
1618        let prefix = index.trusted_prefix();
1619
1620        assert_eq!(prefix.as_str(), index.as_str());
1621        assert!(
1622            prefix.permits(
1623                &url::Url::parse("https://artifacts.corp/cargo/index/se/rd/serde").unwrap()
1624            )
1625        );
1626        assert!(
1627            !prefix
1628                .permits(&url::Url::parse("https://artifacts.corp/cargo/index-public/x").unwrap())
1629        );
1630    }
1631
1632    fn public_only_policy() -> RegistryAccessPolicy {
1633        RegistryAccessPolicy::new(WorkspaceRegistryAccess::PublicOnly)
1634    }
1635
1636    fn all_policy() -> RegistryAccessPolicy {
1637        RegistryAccessPolicy::with_allowlist(
1638            WorkspaceRegistryAccess::All,
1639            Arc::new(deps_core::net_policy::PrivateRegistryAllowlist::for_test(
1640                &["10.0.0.0/8"],
1641            )),
1642        )
1643    }
1644
1645    fn off_policy() -> RegistryAccessPolicy {
1646        RegistryAccessPolicy::new(WorkspaceRegistryAccess::Off)
1647    }
1648
1649    fn no_operator() -> OperatorRegistries {
1650        OperatorRegistries::default()
1651    }
1652
1653    fn operator_declaring(urls: &[&str]) -> OperatorRegistries {
1654        OperatorRegistries::declared_in(
1655            &OperatorPath::for_test("/home/me/.cargo/config.toml"),
1656            urls.iter().copied(),
1657        )
1658    }
1659
1660    fn cargo_home_config(dir: &Path) -> OperatorPath {
1661        OperatorPath::for_test(dir.join("config.toml"))
1662    }
1663
1664    #[test]
1665    fn test_registry_index_strips_sparse_prefix() {
1666        let policy = all_policy();
1667        let index =
1668            RegistryIndex::declared("sparse+https://index.mycorp.dev", &no_operator(), &policy)
1669                .unwrap();
1670        assert_eq!(index.as_str(), "https://index.mycorp.dev");
1671    }
1672
1673    #[test]
1674    fn test_registry_index_rejects_http() {
1675        let policy = all_policy();
1676        assert_matches!(
1677            RegistryIndex::declared("http://index.mycorp.dev", &no_operator(), &policy),
1678            Err(RegistryIndexError::NotHttps(_))
1679        );
1680    }
1681
1682    #[test]
1683    fn test_registry_index_rejects_userinfo() {
1684        let policy = all_policy();
1685        assert_matches!(
1686            RegistryIndex::declared(
1687                "https://user:pass@index.mycorp.dev",
1688                &no_operator(),
1689                &policy
1690            ),
1691            Err(RegistryIndexError::UserInfoPresent)
1692        );
1693    }
1694
1695    #[test]
1696    fn test_registry_index_rejects_bare_username() {
1697        let policy = all_policy();
1698        assert_matches!(
1699            RegistryIndex::declared("https://user@index.mycorp.dev", &no_operator(), &policy),
1700            Err(RegistryIndexError::UserInfoPresent)
1701        );
1702    }
1703
1704    #[test]
1705    fn test_registry_index_rejects_invalid_url() {
1706        let policy = all_policy();
1707        assert_matches!(
1708            RegistryIndex::declared("not a url", &no_operator(), &policy),
1709            Err(RegistryIndexError::InvalidUrl(_))
1710        );
1711    }
1712
1713    /// S1: a userinfo-bearing `index = "…"` value that also fails `Url::parse` for an
1714    /// unrelated reason (an invalid port here) lands in `RegistryIndexError::InvalidUrl`, not
1715    /// `UserInfoPresent` — every call site here logs this error via `tracing::warn!(alias,
1716    /// %error, …)`, so the credential must never survive into `InvalidUrl`'s payload or its
1717    /// `Display`. Fixed once inside `deps_core::net_policy::validate_index_url`, which every
1718    /// `RegistryIndex::declared` call routes through — no separate redaction needed here.
1719    #[test]
1720    fn test_registry_index_invalid_url_error_redacts_userinfo() {
1721        let policy = all_policy();
1722        let err = RegistryIndex::declared(
1723            "https://user:hunter2@index.mycorp.dev:99999",
1724            &no_operator(),
1725            &policy,
1726        )
1727        .unwrap_err();
1728        assert_matches!(err, RegistryIndexError::InvalidUrl(_));
1729        assert!(!err.to_string().contains("hunter2"), "Display: {err}");
1730    }
1731
1732    #[test]
1733    fn test_registry_index_accepts_https_without_sparse_prefix() {
1734        let policy = all_policy();
1735        assert!(
1736            RegistryIndex::declared("https://index.mycorp.dev", &no_operator(), &policy).is_ok()
1737        );
1738    }
1739
1740    #[test]
1741    fn test_registry_index_builtin_crates_io() {
1742        // Also the coverage that makes `builtin`'s panic path unreachable in practice.
1743        let index = RegistryIndex::builtin("https://index.crates.io");
1744        assert_eq!(index.as_str(), "https://index.crates.io");
1745    }
1746
1747    /// The URL-alone rule, not the caller, assigns trust: a URL the operator declared is
1748    /// Trusted and any other is workspace-declared.
1749    #[test]
1750    fn test_registry_index_trust_follows_the_operator_set() {
1751        let policy = all_policy();
1752        let url = "https://index.mycorp.dev";
1753        let trusted = RegistryIndex::declared(url, &operator_declaring(&[url]), &policy).unwrap();
1754        assert_eq!(trusted.trust(), RegistryTrust::Trusted);
1755
1756        let workspace_declared = RegistryIndex::declared(url, &no_operator(), &policy).unwrap();
1757        assert_eq!(workspace_declared.trust(), RegistryTrust::WorkspaceDeclared);
1758    }
1759
1760    // Issue #455, test-plan item 11: `builtin` is always `Trusted`.
1761    #[test]
1762    fn test_registry_index_builtin_is_trusted() {
1763        let index = RegistryIndex::builtin("https://index.crates.io");
1764        assert_eq!(index.trust(), RegistryTrust::Trusted);
1765    }
1766
1767    /// An operator-declared URL skips the workspace policy under every level, but never the
1768    /// never-a-registry floor: the cloud-metadata address is rejected even though the operator
1769    /// named it (#1855).
1770    #[test]
1771    fn test_registry_index_operator_declared_metadata_ip_rejected_by_the_floor() {
1772        let url = "https://169.254.169.254/";
1773        for policy in [off_policy(), public_only_policy(), all_policy()] {
1774            assert_matches!(
1775                RegistryIndex::declared(url, &operator_declaring(&[url]), &policy),
1776                Err(RegistryIndexError::BlockedHost { .. }),
1777                "the floor applies to a Trusted candidate too"
1778            );
1779        }
1780    }
1781
1782    #[test]
1783    fn test_registry_index_operator_declared_private_host_skips_the_policy() {
1784        let url = "https://10.0.0.1/";
1785        let index =
1786            RegistryIndex::declared(url, &operator_declaring(&[url]), &off_policy()).unwrap();
1787        assert_eq!(index.trust(), RegistryTrust::Trusted);
1788    }
1789
1790    #[test]
1791    fn test_registry_index_workspace_declared_metadata_ip_blocked_under_public_only() {
1792        let policy = public_only_policy();
1793        assert_matches!(
1794            RegistryIndex::declared("https://169.254.169.254/", &no_operator(), &policy),
1795            Err(RegistryIndexError::BlockedHost { .. })
1796        );
1797    }
1798
1799    #[test]
1800    fn test_registry_index_workspace_declared_global_allowed_under_public_only() {
1801        let policy = public_only_policy();
1802        assert!(
1803            RegistryIndex::declared("https://index.mycorp.dev", &no_operator(), &policy).is_ok()
1804        );
1805    }
1806
1807    #[test]
1808    fn test_registry_index_workspace_declared_blocked_under_off() {
1809        let policy = off_policy();
1810        assert_matches!(
1811            RegistryIndex::declared("https://index.mycorp.dev", &no_operator(), &policy),
1812            Err(RegistryIndexError::BlockedHost { .. })
1813        );
1814    }
1815
1816    #[test]
1817    fn test_registry_index_workspace_declared_rfc1918_allowed_under_all() {
1818        let policy = all_policy();
1819        assert!(RegistryIndex::declared("https://10.0.0.1/", &no_operator(), &policy).is_ok());
1820    }
1821
1822    /// #1855: a credential follows the operator-declared URL it is bound to, in any spelling, and
1823    /// no other URL gets one: not an operator URL without a token, not a workspace URL.
1824    #[test]
1825    fn test_declared_bound_attaches_the_credential_to_its_url_only() {
1826        let policy = all_policy();
1827        let bound = "https://index.mycorp.dev/bound";
1828        let unbound = "https://index.mycorp.dev/unbound";
1829        let mut operator = CargoOperator::declaring(operator_declaring(&[bound, unbound]));
1830        operator.bind(
1831            strip_sparse_prefix(bound),
1832            AuthToken::new("operator-token".to_string()),
1833        );
1834        let index =
1835            |raw: &str| RegistryIndex::declared_bound(strip_sparse_prefix(raw), &operator, &policy);
1836
1837        for spelling in [
1838            bound,
1839            "https://index.mycorp.dev/bound/",
1840            "sparse+https://index.mycorp.dev/bound",
1841        ] {
1842            let found = index(spelling).unwrap();
1843            assert_eq!(
1844                found.credential().map(AuthToken::expose_secret),
1845                Some("operator-token"),
1846                "{spelling}"
1847            );
1848        }
1849
1850        let operator_without_token = index(unbound).unwrap();
1851        assert_eq!(operator_without_token.trust(), RegistryTrust::Trusted);
1852        assert!(!operator_without_token.has_credential());
1853
1854        let workspace = index("https://index.mycorp.dev/elsewhere").unwrap();
1855        assert_eq!(workspace.trust(), RegistryTrust::WorkspaceDeclared);
1856        assert!(!workspace.has_credential());
1857    }
1858
1859    /// The first binding of a URL wins, and the operator binds in a fixed order, so two aliases
1860    /// declaring one URL always give the same credential.
1861    #[test]
1862    fn test_bind_keeps_the_first_credential_for_a_url() {
1863        let url = "https://index.mycorp.dev/first-wins";
1864        let mut operator = CargoOperator::declaring(operator_declaring(&[url]));
1865        operator.bind(
1866            strip_sparse_prefix(url),
1867            AuthToken::new("first".to_string()),
1868        );
1869        operator.bind(
1870            strip_sparse_prefix(url),
1871            AuthToken::new("second".to_string()),
1872        );
1873
1874        let index =
1875            RegistryIndex::declared_bound(strip_sparse_prefix(url), &operator, &all_policy())
1876                .unwrap();
1877        assert_eq!(
1878            index.credential().map(AuthToken::expose_secret),
1879            Some("first")
1880        );
1881    }
1882
1883    #[test]
1884    fn test_auth_token_debug_and_display_redact() {
1885        let token = AuthToken::new("super-secret-value".to_string());
1886        assert_eq!(format!("{token:?}"), "AuthToken(***)");
1887        assert_eq!(format!("{token}"), "***");
1888        assert!(!format!("{token:?}").contains("super-secret-value"));
1889    }
1890
1891    #[test]
1892    fn test_parse_workspace_registries_raw_never_populates_auth() {
1893        let content = r#"
1894[registries.my-corp]
1895index = "sparse+https://index.mycorp.dev"
1896token = "should-be-ignored"
1897"#;
1898        let result = parse_workspace_registries_raw(content);
1899        // The return type itself has no token field — this just also confirms the `index`
1900        // value is captured correctly alongside the ignored `token` key.
1901        assert_eq!(
1902            result.get("my-corp").map(String::as_str),
1903            Some("sparse+https://index.mycorp.dev")
1904        );
1905    }
1906
1907    #[test]
1908    fn test_parse_cargo_home_registries_raw_reads_token() {
1909        let content = r#"
1910[registries.my-corp]
1911index = "sparse+https://index.mycorp.dev"
1912token = "secret-token"
1913"#;
1914        let result = parse_cargo_home_registries_raw(content);
1915        let (raw_index, token) = result.get("my-corp").unwrap();
1916        assert_eq!(raw_index, "sparse+https://index.mycorp.dev");
1917        assert_eq!(
1918            token.as_ref().unwrap().as_redacted().expose_secret(),
1919            "secret-token"
1920        );
1921    }
1922
1923    #[test]
1924    fn test_parse_registries_raw_malformed_toml_fails_closed() {
1925        let content = "this is [ not valid toml";
1926        assert!(parse_workspace_registries_raw(content).is_empty());
1927        assert!(parse_cargo_home_registries_raw(content).is_empty());
1928    }
1929
1930    #[test]
1931    fn test_parse_registries_raw_rejects_excessive_nesting() {
1932        let content = format!("a = {}1{}", "[".repeat(300), "]".repeat(300));
1933        assert!(parse_workspace_registries_raw(&content).is_empty());
1934        assert!(parse_cargo_home_registries_raw(&content).is_empty());
1935    }
1936
1937    #[test]
1938    fn test_cargo_home_config_path_none_when_unset() {
1939        assert!(cargo_home_config_path_with_env(&MapEnv::new()).is_none());
1940    }
1941
1942    #[test]
1943    fn test_cargo_home_config_path_some_when_set() {
1944        let dir = tempfile::tempdir().unwrap();
1945        let env = MapEnv::new().with_var("CARGO_HOME", dir.path().to_str().unwrap());
1946        let path = cargo_home_config_path_with_env(&env).unwrap();
1947        assert_eq!(path.as_path(), dir.path().join("config.toml"));
1948    }
1949
1950    /// A relative `CARGO_HOME` would resolve against a directory a repository can influence, so
1951    /// it names no operator-owned location and is ignored (#1855).
1952    #[test]
1953    fn test_cargo_home_config_path_ignores_a_relative_cargo_home() {
1954        let env = MapEnv::new().with_var("CARGO_HOME", "relative/.cargo");
1955        assert!(cargo_home_config_path_with_env(&env).is_none());
1956    }
1957
1958    #[test]
1959    fn test_resolve_workspace_wins_over_cargo_home() {
1960        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
1961        let _guard = deps_core::fs_probe::snapshot_guard();
1962        let root = tempfile::tempdir().unwrap();
1963        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
1964        std::fs::write(
1965            root.path().join(".cargo/config.toml"),
1966            "[registries.my-corp]\nindex = \"sparse+https://workspace.example\"\n",
1967        )
1968        .unwrap();
1969
1970        let cargo_home = tempfile::tempdir().unwrap();
1971        std::fs::write(
1972            cargo_home.path().join("config.toml"),
1973            "[registries.my-corp]\nindex = \"sparse+https://real.example\"\ntoken = \"real-token\"\n",
1974        )
1975        .unwrap();
1976
1977        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
1978        let cache = ConfigFileCache::new();
1979        let policy = all_policy();
1980        let (config, _) = resolve(
1981            &aliases,
1982            &[root.path().join(".cargo/config.toml")],
1983            Some(&cargo_home_config(cargo_home.path())),
1984            &cache,
1985            &policy,
1986        );
1987
1988        let entry = config.get("my-corp").unwrap();
1989        assert_eq!(entry.index.as_str(), "https://workspace.example");
1990        assert!(
1991            !entry.index.has_credential(),
1992            "workspace-shadowed entry must never carry the cargo-home token"
1993        );
1994        assert_eq!(entry.provenance, Provenance::Workspace);
1995    }
1996
1997    /// Regression: a project living under `$HOME` (the default `CARGO_HOME=~/.cargo`
1998    /// layout) has the ancestor walk pick up `~/.cargo/config.toml` — the *same file* as
1999    /// `$CARGO_HOME/config.toml` — as a workspace-tier candidate. Before the
2000    /// canonicalized-path exclusion, that duplicate entry won the workspace-tier-always-wins
2001    /// precedence and silently dropped the token: the alias still resolved, just
2002    /// unauthenticated, which looks like success.
2003    #[test]
2004    fn test_resolve_home_nested_project_does_not_lose_cargo_home_token() {
2005        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2006        let _guard = deps_core::fs_probe::snapshot_guard();
2007        let home = tempfile::tempdir().unwrap();
2008        std::fs::create_dir_all(home.path().join(".cargo")).unwrap();
2009        let cargo_home_config = home.path().join(".cargo/config.toml");
2010        std::fs::write(
2011            &cargo_home_config,
2012            "[registries.my-corp]\nindex = \"sparse+https://real.example\"\ntoken = \"real-token\"\n",
2013        )
2014        .unwrap();
2015
2016        // Reproduces the ancestor-walk collision directly, without depending on
2017        // `crate::parser`'s merged walk (tested separately in `parser.rs`).
2018        let workspace_paths = vec![cargo_home_config.clone()];
2019
2020        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2021        let cache = ConfigFileCache::new();
2022        let policy = all_policy();
2023        let (config, _) = resolve(
2024            &aliases,
2025            &workspace_paths,
2026            Some(&OperatorPath::for_test(cargo_home_config)),
2027            &cache,
2028            &policy,
2029        );
2030
2031        let entry = config.get("my-corp").unwrap();
2032        assert_eq!(entry.index.as_str(), "https://real.example");
2033        assert_eq!(entry.provenance, Provenance::CargoHome);
2034        assert_eq!(
2035            entry.index.credential().map(AuthToken::expose_secret),
2036            Some("real-token"),
2037            "the CARGO_HOME token must not be lost just because the project lives \
2038             under $HOME"
2039        );
2040    }
2041
2042    #[test]
2043    fn test_resolve_falls_back_to_cargo_home_when_no_workspace_entry() {
2044        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2045        let _guard = deps_core::fs_probe::snapshot_guard();
2046        let cargo_home = tempfile::tempdir().unwrap();
2047        std::fs::write(
2048            cargo_home.path().join("config.toml"),
2049            "[registries.my-corp]\nindex = \"sparse+https://real.example\"\ntoken = \"real-token\"\n",
2050        )
2051        .unwrap();
2052
2053        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2054        let cache = ConfigFileCache::new();
2055        let policy = all_policy();
2056        let (config, _) = resolve(
2057            &aliases,
2058            &[],
2059            Some(&cargo_home_config(cargo_home.path())),
2060            &cache,
2061            &policy,
2062        );
2063
2064        let entry = config.get("my-corp").unwrap();
2065        assert_eq!(entry.index.as_str(), "https://real.example");
2066        assert_eq!(
2067            entry.index.credential().unwrap().expose_secret(),
2068            "real-token"
2069        );
2070        assert_eq!(entry.provenance, Provenance::CargoHome);
2071    }
2072
2073    /// #1453 impl-critic S1: a `$CARGO_HOME/config.toml` `[registries.<name>] index = ...`
2074    /// entry that fails validation for a non-blocked-host reason must populate
2075    /// `CargoConfig::rejected` exactly like a workspace-tier entry does — `RegistryTrust::Trusted`
2076    /// only skips the policy gate, not the scheme/userinfo/URL-shape checks
2077    /// `validate_index_url` still applies.
2078    #[test]
2079    fn test_resolve_cargo_home_file_entry_rejected_populates_rejected() {
2080        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2081        let _guard = deps_core::fs_probe::snapshot_guard();
2082        let cargo_home = tempfile::tempdir().unwrap();
2083        std::fs::write(
2084            cargo_home.path().join("config.toml"),
2085            "[registries.my-corp]\nindex = \"http://insecure.example\"\n",
2086        )
2087        .unwrap();
2088
2089        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2090        let cache = ConfigFileCache::new();
2091        let policy = all_policy();
2092        let (config, _) = resolve(
2093            &aliases,
2094            &[],
2095            Some(&cargo_home_config(cargo_home.path())),
2096            &cache,
2097            &policy,
2098        );
2099
2100        assert!(config.get("my-corp").is_none());
2101        assert_eq!(
2102            config.rejected_reason("my-corp"),
2103            Some(RegistryRejectionReason::NotHttps)
2104        );
2105    }
2106
2107    /// #1453 impl-critic S1: an invalid `CARGO_REGISTRIES_*_INDEX` env override must not be
2108    /// reported as a rejection when the file-tier fallback resolves to a valid entry — the
2109    /// env override silently loses to the working fallback exactly as before, so nothing new
2110    /// should surface as a diagnostic for this case.
2111    #[test]
2112    fn test_resolve_env_var_index_override_rejected_falls_back_silently_to_valid_file_entry() {
2113        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2114        let _guard = deps_core::fs_probe::snapshot_guard();
2115        let cargo_home = tempfile::tempdir().unwrap();
2116        std::fs::write(
2117            cargo_home.path().join("config.toml"),
2118            "[registries.my-corp]\nindex = \"sparse+https://real.example\"\n",
2119        )
2120        .unwrap();
2121
2122        let env = MapEnv::new().with_var("CARGO_REGISTRIES_MY_CORP_INDEX", "not-a-valid-url");
2123
2124        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2125        let cache = ConfigFileCache::new();
2126        let policy = all_policy();
2127        let (config, _) = resolve_with_env(
2128            &aliases,
2129            &[],
2130            Some(&cargo_home_config(cargo_home.path())),
2131            &cache,
2132            &policy,
2133            &env,
2134        );
2135
2136        let entry = config.get("my-corp").unwrap();
2137        assert_eq!(entry.index.as_str(), "https://real.example");
2138        assert_eq!(config.rejected_reason("my-corp"), None);
2139    }
2140
2141    /// #1453 impl-critic S1: an invalid `CARGO_REGISTRIES_*_INDEX` env override with no
2142    /// file-tier fallback at all must populate `CargoConfig::rejected` — previously this
2143    /// silently dropped the alias with only a `tracing::warn!`.
2144    #[test]
2145    fn test_resolve_env_var_index_override_rejected_with_no_file_entry_populates_rejected() {
2146        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2147        let _guard = deps_core::fs_probe::snapshot_guard();
2148        let env = MapEnv::new().with_var(
2149            "CARGO_REGISTRIES_MY_CORP_INDEX",
2150            "sparse+https://user:pass@index.mycorp.dev",
2151        );
2152
2153        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2154        let cache = ConfigFileCache::new();
2155        let policy = all_policy();
2156        let (config, _) = resolve_with_env(&aliases, &[], None, &cache, &policy, &env);
2157
2158        assert!(config.get("my-corp").is_none());
2159        assert_eq!(
2160            config.rejected_reason("my-corp"),
2161            Some(RegistryRejectionReason::UserInfoPresent)
2162        );
2163    }
2164
2165    /// #1453 code-review finding 3: when *both* the `CARGO_REGISTRIES_*_INDEX` env override
2166    /// and the `$CARGO_HOME/config.toml` file-tier entry are independently invalid, the env
2167    /// override's own reason must be reported — not silently discarded in favor of the
2168    /// unrelated file-tier failure.
2169    #[test]
2170    fn test_resolve_env_and_file_both_rejected_prefers_env_reason() {
2171        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2172        let _guard = deps_core::fs_probe::snapshot_guard();
2173        let cargo_home = tempfile::tempdir().unwrap();
2174        std::fs::write(
2175            cargo_home.path().join("config.toml"),
2176            "[registries.my-corp]\nindex = \"http://insecure.example\"\n",
2177        )
2178        .unwrap();
2179
2180        let env = MapEnv::new().with_var(
2181            "CARGO_REGISTRIES_MY_CORP_INDEX",
2182            "sparse+https://user:pass@index.mycorp.dev",
2183        );
2184
2185        let aliases: HashSet<String> = std::iter::once("my-corp".to_string()).collect();
2186        let cache = ConfigFileCache::new();
2187        let policy = all_policy();
2188        let (config, _) = resolve_with_env(
2189            &aliases,
2190            &[],
2191            Some(&cargo_home_config(cargo_home.path())),
2192            &cache,
2193            &policy,
2194            &env,
2195        );
2196
2197        assert!(config.get("my-corp").is_none());
2198        assert_eq!(
2199            config.rejected_reason("my-corp"),
2200            Some(RegistryRejectionReason::UserInfoPresent),
2201            "the env override's own reason must survive, not the unrelated file entry's"
2202        );
2203    }
2204
2205    #[test]
2206    fn test_resolve_unconfigured_alias_stays_unresolved() {
2207        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2208        let _guard = deps_core::fs_probe::snapshot_guard();
2209        let aliases: HashSet<String> = std::iter::once("unknown".to_string()).collect();
2210        let cache = ConfigFileCache::new();
2211        let policy = all_policy();
2212        let (config, _) = resolve(&aliases, &[], None, &cache, &policy);
2213        assert!(config.get("unknown").is_none());
2214    }
2215
2216    #[test]
2217    fn test_resolve_env_var_index_override() {
2218        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2219        let _guard = deps_core::fs_probe::snapshot_guard();
2220        let aliases: HashSet<String> = std::iter::once("env-only-corp".to_string()).collect();
2221        let env = MapEnv::new()
2222            .with_var(
2223                "CARGO_REGISTRIES_ENV_ONLY_CORP_INDEX",
2224                "sparse+https://env.example",
2225            )
2226            .with_var("CARGO_REGISTRIES_ENV_ONLY_CORP_TOKEN", "env-token");
2227
2228        let cache = ConfigFileCache::new();
2229        let policy = all_policy();
2230        let (config, _) = resolve_with_env(&aliases, &[], None, &cache, &policy, &env);
2231        let entry = config.get("env-only-corp").unwrap();
2232        assert_eq!(entry.index.as_str(), "https://env.example");
2233        assert_eq!(
2234            entry.index.credential().unwrap().expose_secret(),
2235            "env-token"
2236        );
2237        assert_eq!(entry.provenance, Provenance::CargoHome);
2238    }
2239
2240    /// FR-015: two distinct alias spellings deriving the same env-var name must both be
2241    /// skipped for env resolution, not have one arbitrarily win.
2242    #[test]
2243    fn test_resolve_env_var_name_collision_disables_both() {
2244        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2245        let _guard = deps_core::fs_probe::snapshot_guard();
2246        let aliases: HashSet<String> = ["my-corp".to_string(), "my_corp".to_string()]
2247            .into_iter()
2248            .collect();
2249        let env = MapEnv::new().with_var(
2250            "CARGO_REGISTRIES_MY_CORP_INDEX",
2251            "sparse+https://ambiguous.example",
2252        );
2253
2254        let cache = ConfigFileCache::new();
2255        let policy = all_policy();
2256        let (config, _) = resolve_with_env(&aliases, &[], None, &cache, &policy, &env);
2257        assert!(config.get("my-corp").is_none());
2258        assert!(config.get("my_corp").is_none());
2259    }
2260
2261    /// The env-var TOKEN override must never resurrect a credential for an alias a
2262    /// workspace file has shadowed — the exact US-004 scenario, exercised through
2263    /// `resolve` end-to-end rather than only at the raw-parse unit level.
2264    #[test]
2265    fn test_resolve_env_token_never_attaches_to_workspace_shadowed_alias() {
2266        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2267        let _guard = deps_core::fs_probe::snapshot_guard();
2268        let root = tempfile::tempdir().unwrap();
2269        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
2270        std::fs::write(
2271            root.path().join(".cargo/config.toml"),
2272            "[registries.github]\nindex = \"sparse+https://attacker.example\"\n",
2273        )
2274        .unwrap();
2275
2276        let env = MapEnv::new().with_var("CARGO_REGISTRIES_GITHUB_TOKEN", "legitimate-token");
2277
2278        let aliases: HashSet<String> = std::iter::once("github".to_string()).collect();
2279        let cache = ConfigFileCache::new();
2280        let policy = all_policy();
2281        let (config, _) = resolve_with_env(
2282            &aliases,
2283            &[root.path().join(".cargo/config.toml")],
2284            None,
2285            &cache,
2286            &policy,
2287            &env,
2288        );
2289
2290        let entry = config.get("github").unwrap();
2291        assert_eq!(entry.index.as_str(), "https://attacker.example");
2292        assert!(
2293            !entry.index.has_credential(),
2294            "the legitimate env token must never attach to the attacker-controlled index"
2295        );
2296    }
2297
2298    /// #1855: a `sparse+` registry in `$CARGO_HOME` is operator-declared, so it classifies
2299    /// Trusted and carries its token.
2300    #[test]
2301    fn test_resolve_sparse_prefixed_cargo_home_registry_is_trusted_with_credential() {
2302        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2303        let _guard = deps_core::fs_probe::snapshot_guard();
2304        let cargo_home = tempfile::tempdir().unwrap();
2305        std::fs::write(
2306            cargo_home.path().join("config.toml"),
2307            "[registries.corp]\nindex = \"sparse+https://corp.example/index\"\ntoken = \"corp-token\"\n",
2308        )
2309        .unwrap();
2310
2311        let aliases: HashSet<String> = std::iter::once("corp".to_string()).collect();
2312        let (config, _) = resolve_with_env(
2313            &aliases,
2314            &[],
2315            Some(&cargo_home_config(cargo_home.path())),
2316            &ConfigFileCache::new(),
2317            &off_policy(),
2318            &MapEnv::new(),
2319        );
2320
2321        let entry = config.get("corp").unwrap();
2322        assert_eq!(entry.index.trust(), RegistryTrust::Trusted);
2323        assert_eq!(
2324            entry.index.credential().map(AuthToken::expose_secret),
2325            Some("corp-token")
2326        );
2327    }
2328
2329    /// #1855: an operator registry declared only through `CARGO_REGISTRIES_<ALIAS>_INDEX`, with
2330    /// `$CARGO_HOME` unset, is still operator-declared: Trusted, policy skipped, token attached.
2331    #[test]
2332    fn test_resolve_env_only_operator_registry_is_trusted_without_cargo_home() {
2333        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2334        let _guard = deps_core::fs_probe::snapshot_guard();
2335        let env = MapEnv::new()
2336            .with_var(
2337                "CARGO_REGISTRIES_ENVREG_INDEX",
2338                "sparse+https://envreg.example",
2339            )
2340            .with_var("CARGO_REGISTRIES_ENVREG_TOKEN", "env-token");
2341
2342        let aliases: HashSet<String> = std::iter::once("envreg".to_string()).collect();
2343        let (config, _) = resolve_with_env(
2344            &aliases,
2345            &[],
2346            None,
2347            &ConfigFileCache::new(),
2348            &off_policy(),
2349            &env,
2350        );
2351
2352        let entry = config.get("envreg").unwrap();
2353        assert_eq!(entry.index.trust(), RegistryTrust::Trusted);
2354        assert_eq!(
2355            entry.index.credential().map(AuthToken::expose_secret),
2356            Some("env-token")
2357        );
2358    }
2359
2360    /// #1855: a workspace alias that names an operator-declared URL gets that URL's egress trust
2361    /// (the policy is skipped, even under `off`) and the credential bound to that URL.
2362    #[test]
2363    fn test_resolve_workspace_alias_naming_an_operator_url_gets_the_urls_trust_and_credential() {
2364        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2365        let _guard = deps_core::fs_probe::snapshot_guard();
2366        let root = tempfile::tempdir().unwrap();
2367        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
2368        std::fs::write(
2369            root.path().join(".cargo/config.toml"),
2370            "[registries.repo-alias]\nindex = \"sparse+https://corp.example/index/\"\n",
2371        )
2372        .unwrap();
2373        let cargo_home = tempfile::tempdir().unwrap();
2374        std::fs::write(
2375            cargo_home.path().join("config.toml"),
2376            "[registries.corp]\nindex = \"sparse+https://corp.example/index\"\ntoken = \"corp-token\"\n",
2377        )
2378        .unwrap();
2379
2380        let aliases: HashSet<String> = std::iter::once("repo-alias".to_string()).collect();
2381        let (config, _) = resolve_with_env(
2382            &aliases,
2383            &[root.path().join(".cargo/config.toml")],
2384            Some(&cargo_home_config(cargo_home.path())),
2385            &ConfigFileCache::new(),
2386            &off_policy(),
2387            &MapEnv::new(),
2388        );
2389
2390        let entry = config.get("repo-alias").unwrap();
2391        assert_eq!(entry.provenance, Provenance::Workspace);
2392        assert_eq!(entry.index.trust(), RegistryTrust::Trusted);
2393        assert_eq!(
2394            entry.index.credential().map(AuthToken::expose_secret),
2395            Some("corp-token")
2396        );
2397    }
2398
2399    /// #1855: a workspace alias naming a URL the operator did not declare stays
2400    /// workspace-declared and is refused under `off`.
2401    #[test]
2402    fn test_resolve_workspace_alias_for_an_undeclared_url_is_policy_gated() {
2403        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2404        let _guard = deps_core::fs_probe::snapshot_guard();
2405        let root = tempfile::tempdir().unwrap();
2406        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
2407        std::fs::write(
2408            root.path().join(".cargo/config.toml"),
2409            "[registries.repo-alias]\nindex = \"sparse+https://repo-chosen.example/index\"\n",
2410        )
2411        .unwrap();
2412
2413        let aliases: HashSet<String> = std::iter::once("repo-alias".to_string()).collect();
2414        let (config, _) = resolve_with_env(
2415            &aliases,
2416            &[root.path().join(".cargo/config.toml")],
2417            None,
2418            &ConfigFileCache::new(),
2419            &off_policy(),
2420            &MapEnv::new(),
2421        );
2422
2423        assert!(config.get("repo-alias").is_none());
2424        assert!(config.blocked_class("repo-alias").is_some());
2425    }
2426
2427    /// #1855: the never-a-registry floor applies to an operator-declared `$CARGO_HOME` registry
2428    /// too: loopback and link-local hosts are rejected and reported as blocked.
2429    #[test]
2430    fn test_resolve_cargo_home_registry_on_loopback_or_link_local_is_blocked() {
2431        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2432        let _guard = deps_core::fs_probe::snapshot_guard();
2433        let cargo_home = tempfile::tempdir().unwrap();
2434        std::fs::write(
2435            cargo_home.path().join("config.toml"),
2436            "[registries.loop]\nindex = \"sparse+https://127.0.0.1:8443\"\n\
2437             [registries.metadata]\nindex = \"sparse+https://169.254.169.254\"\n",
2438        )
2439        .unwrap();
2440
2441        let aliases: HashSet<String> = ["loop".to_string(), "metadata".to_string()]
2442            .into_iter()
2443            .collect();
2444        let (config, _) = resolve_with_env(
2445            &aliases,
2446            &[],
2447            Some(&cargo_home_config(cargo_home.path())),
2448            &ConfigFileCache::new(),
2449            &all_policy(),
2450            &MapEnv::new(),
2451        );
2452
2453        for alias in ["loop", "metadata"] {
2454            assert!(config.get(alias).is_none(), "{alias}");
2455            assert!(config.blocked_class(alias).is_some(), "{alias}");
2456        }
2457    }
2458
2459    /// #1855: `sparse+` is removed exactly once, so the operator set and the classifier agree on
2460    /// the text; a doubled prefix is left as `sparse+https://…` and refused as not https.
2461    #[test]
2462    fn test_resolve_strips_the_sparse_prefix_once() {
2463        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2464        let _guard = deps_core::fs_probe::snapshot_guard();
2465        let env = MapEnv::new().with_var(
2466            "CARGO_REGISTRIES_DOUBLE_INDEX",
2467            "sparse+sparse+https://double.example",
2468        );
2469        let aliases: HashSet<String> = std::iter::once("double".to_string()).collect();
2470        let (config, _) = resolve_with_env(
2471            &aliases,
2472            &[],
2473            None,
2474            &ConfigFileCache::new(),
2475            &all_policy(),
2476            &env,
2477        );
2478
2479        assert!(config.get("double").is_none());
2480        assert_eq!(
2481            config.rejected_reason("double"),
2482            Some(RegistryRejectionReason::NotHttps)
2483        );
2484    }
2485
2486    #[test]
2487    fn test_referenced_aliases_collects_custom_registry_urls() {
2488        use crate::types::{CargoDependency, CargoDependencySection};
2489        use deps_core::parser::DependencySource;
2490        use deps_core::position::Range;
2491
2492        let deps = vec![
2493            CargoDependency {
2494                name: "a".into(),
2495                name_range: Range::default(),
2496                version_req: None,
2497                version_range: None,
2498                features: vec![],
2499                features_range: None,
2500                source: DependencySource::CustomRegistry {
2501                    url: "my-corp".into(),
2502                },
2503                section: CargoDependencySection::Dependencies,
2504                package: None,
2505                custom_registry_origin: None,
2506                native_cooldown: None,
2507            },
2508            CargoDependency {
2509                name: "b".into(),
2510                name_range: Range::default(),
2511                version_req: None,
2512                version_range: None,
2513                features: vec![],
2514                features_range: None,
2515                source: DependencySource::Registry,
2516                section: CargoDependencySection::Dependencies,
2517                package: None,
2518                custom_registry_origin: None,
2519                native_cooldown: None,
2520            },
2521        ];
2522
2523        let aliases = referenced_aliases(&deps);
2524        assert_eq!(aliases.len(), 1);
2525        assert!(aliases.contains("my-corp"));
2526    }
2527
2528    // ---- ConfigFileCache ----
2529
2530    #[test]
2531    fn test_config_file_cache_hit_reuses_parsed_arc_without_reparsing() {
2532        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2533        let _guard = deps_core::fs_probe::snapshot_guard();
2534        let dir = tempfile::tempdir().unwrap();
2535        let path = dir.path().join("config.toml");
2536        std::fs::write(
2537            &path,
2538            "[registries.a]\nindex = \"sparse+https://a.example\"\n",
2539        )
2540        .unwrap();
2541
2542        let cache = ConfigFileCache::new();
2543        let first = cache.get_or_parse_workspace(&path).unwrap();
2544        let second = cache.get_or_parse_workspace(&path).unwrap();
2545
2546        assert!(
2547            Arc::ptr_eq(&first, &second),
2548            "a cache hit must return the same Arc, not re-parse"
2549        );
2550    }
2551
2552    /// P1 (plan-1b §4 Performance/M4, flagged missing by the tester validator): the real
2553    /// bound is "at most two stats per ancestor directory... and zero filesystem reads per
2554    /// parse on a cache hit" — `Arc::ptr_eq` alone proves the *value* is reused, not that no
2555    /// syscall ran. This counts actual `stat`/`read` calls via `fs_probe`.
2556    #[test]
2557    fn test_config_file_cache_hit_does_zero_reads_and_exactly_one_stat() {
2558        let dir = tempfile::tempdir().unwrap();
2559        let path = dir.path().join("config.toml");
2560        std::fs::write(
2561            &path,
2562            "[registries.a]\nindex = \"sparse+https://a.example\"\n",
2563        )
2564        .unwrap();
2565
2566        let cache = ConfigFileCache::new();
2567        // Acquired before the priming call too: that warm-up still does one real stat/read
2568        // through fs_probe, which must not race a sibling test's own measured window either.
2569        let _guard = deps_core::fs_probe::snapshot_guard();
2570        // Prime the cache — the first call is necessarily a miss (one stat, one read).
2571        cache.get_or_parse_workspace(&path).unwrap();
2572
2573        let (stats_before, reads_before) = deps_core::fs_probe::snapshot();
2574        let hit = cache.get_or_parse_workspace(&path).unwrap();
2575        let (stats_after, reads_after) = deps_core::fs_probe::snapshot();
2576
2577        assert_eq!(
2578            reads_after - reads_before,
2579            0,
2580            "a cache hit must perform zero content reads"
2581        );
2582        assert_eq!(
2583            stats_after - stats_before,
2584            1,
2585            "a cache hit still pays exactly one mtime stat"
2586        );
2587        match &hit.tier {
2588            CachedTier::Workspace(map) => assert!(map.contains_key("a")),
2589            CachedTier::CargoHome(_) => panic!("expected Workspace tier"),
2590        }
2591    }
2592
2593    /// S3: adding a new `registry = "…"` alias to the manifest must resolve without any
2594    /// config-file change — the raw tables are cached, but alias *filtering* runs per
2595    /// parse.
2596    #[test]
2597    fn test_resolve_new_alias_resolves_without_config_file_change() {
2598        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2599        let _guard = deps_core::fs_probe::snapshot_guard();
2600        let root = tempfile::tempdir().unwrap();
2601        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
2602        std::fs::write(
2603            root.path().join(".cargo/config.toml"),
2604            "[registries.a]\nindex = \"sparse+https://a.example\"\n\
2605             [registries.b]\nindex = \"sparse+https://b.example\"\n",
2606        )
2607        .unwrap();
2608
2609        let cache = ConfigFileCache::new();
2610        let policy = all_policy();
2611        let workspace_paths = vec![root.path().join(".cargo/config.toml")];
2612
2613        let first_aliases: HashSet<String> = std::iter::once("a".to_string()).collect();
2614        let (first, _) = resolve(&first_aliases, &workspace_paths, None, &cache, &policy);
2615        assert!(first.get("a").is_some());
2616        assert!(first.get("b").is_none(), "b was not yet referenced");
2617
2618        // No config-file write between these two calls — only the referenced-alias set
2619        // changed, simulating a manifest edit that adds `registry = "b"`.
2620        let second_aliases: HashSet<String> =
2621            ["a".to_string(), "b".to_string()].into_iter().collect();
2622        let (second, _) = resolve(&second_aliases, &workspace_paths, None, &cache, &policy);
2623        assert!(
2624            second.get("b").is_some(),
2625            "newly-referenced alias b must resolve immediately"
2626        );
2627    }
2628
2629    /// A `didChangeConfiguration`-driven policy change must take effect immediately, with
2630    /// no cache invalidation of its own — the policy is not part of the cache at all.
2631    #[test]
2632    fn test_resolve_policy_change_takes_effect_with_no_cache_invalidation() {
2633        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2634        let _guard = deps_core::fs_probe::snapshot_guard();
2635        let root = tempfile::tempdir().unwrap();
2636        std::fs::create_dir_all(root.path().join(".cargo")).unwrap();
2637        std::fs::write(
2638            root.path().join(".cargo/config.toml"),
2639            "[registries.metadata]\nindex = \"https://10.0.0.1\"\n",
2640        )
2641        .unwrap();
2642
2643        let cache = ConfigFileCache::new();
2644        let policy = all_policy();
2645        let workspace_paths = vec![root.path().join(".cargo/config.toml")];
2646        let aliases: HashSet<String> = std::iter::once("metadata".to_string()).collect();
2647
2648        let (first, _) = resolve(&aliases, &workspace_paths, None, &cache, &policy);
2649        assert!(first.get("metadata").is_some(), "allowed under All");
2650
2651        policy.set(WorkspaceRegistryAccess::PublicOnly);
2652        let (second, _) = resolve(&aliases, &workspace_paths, None, &cache, &policy);
2653        assert!(
2654            second.get("metadata").is_none(),
2655            "blocked under PublicOnly, same cache"
2656        );
2657    }
2658
2659    // ---- [source] chain resolution ----
2660
2661    fn write_config(dir: &Path, content: &str) -> PathBuf {
2662        std::fs::create_dir_all(dir.join(".cargo")).unwrap();
2663        let path = dir.join(".cargo/config.toml");
2664        std::fs::write(&path, content).unwrap();
2665        path
2666    }
2667
2668    #[test]
2669    fn test_source_chain_single_hop_to_sparse() {
2670        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2671        let _guard = deps_core::fs_probe::snapshot_guard();
2672        let root = tempfile::tempdir().unwrap();
2673        let path = write_config(
2674            root.path(),
2675            "[source.crates-io]\nreplace-with = \"my-mirror\"\n\
2676             [source.my-mirror]\nregistry = \"sparse+https://mirror.example\"\n",
2677        );
2678
2679        let cache = ConfigFileCache::new();
2680        let policy = all_policy();
2681        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2682
2683        match replacement {
2684            SourceReplacement::SparseMirror { index } => {
2685                assert_eq!(index.as_str(), "https://mirror.example");
2686                assert!(!index.has_credential());
2687            }
2688            SourceReplacement::None => panic!("expected a resolved mirror"),
2689        }
2690    }
2691
2692    #[test]
2693    fn test_source_chain_two_hops() {
2694        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2695        let _guard = deps_core::fs_probe::snapshot_guard();
2696        let root = tempfile::tempdir().unwrap();
2697        let path = write_config(
2698            root.path(),
2699            "[source.crates-io]\nreplace-with = \"intermediate\"\n\
2700             [source.intermediate]\nreplace-with = \"terminal\"\n\
2701             [source.terminal]\nregistry = \"sparse+https://terminal.example\"\n",
2702        );
2703
2704        let cache = ConfigFileCache::new();
2705        let policy = all_policy();
2706        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2707
2708        assert_matches!(replacement, SourceReplacement::SparseMirror { .. });
2709    }
2710
2711    #[test]
2712    fn test_source_chain_directory_falls_back_to_none() {
2713        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2714        let _guard = deps_core::fs_probe::snapshot_guard();
2715        let root = tempfile::tempdir().unwrap();
2716        let path = write_config(
2717            root.path(),
2718            "[source.crates-io]\nreplace-with = \"vendored\"\n\
2719             [source.vendored]\ndirectory = \"vendor\"\n",
2720        );
2721
2722        let cache = ConfigFileCache::new();
2723        let policy = all_policy();
2724        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2725
2726        assert_eq!(replacement, SourceReplacement::None);
2727    }
2728
2729    #[test]
2730    fn test_source_chain_local_registry_falls_back_to_none() {
2731        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2732        let _guard = deps_core::fs_probe::snapshot_guard();
2733        let root = tempfile::tempdir().unwrap();
2734        let path = write_config(
2735            root.path(),
2736            "[source.crates-io]\nreplace-with = \"local\"\n\
2737             [source.local]\nlocal-registry = \"local-registry\"\n",
2738        );
2739
2740        let cache = ConfigFileCache::new();
2741        let policy = all_policy();
2742        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2743
2744        assert_eq!(replacement, SourceReplacement::None);
2745    }
2746
2747    #[test]
2748    fn test_source_chain_bare_https_git_index_falls_back_to_none() {
2749        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2750        let _guard = deps_core::fs_probe::snapshot_guard();
2751        let root = tempfile::tempdir().unwrap();
2752        let path = write_config(
2753            root.path(),
2754            "[source.crates-io]\nreplace-with = \"git-mirror\"\n\
2755             [source.git-mirror]\nregistry = \"https://github.com/rust-lang/crates.io-index\"\n",
2756        );
2757
2758        let cache = ConfigFileCache::new();
2759        let policy = all_policy();
2760        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2761
2762        assert_eq!(replacement, SourceReplacement::None);
2763    }
2764
2765    #[test]
2766    fn test_source_chain_self_referential_stops() {
2767        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2768        let _guard = deps_core::fs_probe::snapshot_guard();
2769        let root = tempfile::tempdir().unwrap();
2770        let path = write_config(
2771            root.path(),
2772            "[source.crates-io]\nreplace-with = \"crates-io\"\n",
2773        );
2774
2775        let cache = ConfigFileCache::new();
2776        let policy = all_policy();
2777        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2778
2779        assert_eq!(replacement, SourceReplacement::None);
2780    }
2781
2782    #[test]
2783    fn test_source_chain_three_cycle_stops() {
2784        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2785        let _guard = deps_core::fs_probe::snapshot_guard();
2786        let root = tempfile::tempdir().unwrap();
2787        let path = write_config(
2788            root.path(),
2789            "[source.crates-io]\nreplace-with = \"a\"\n\
2790             [source.a]\nreplace-with = \"b\"\n\
2791             [source.b]\nreplace-with = \"crates-io\"\n",
2792        );
2793
2794        let cache = ConfigFileCache::new();
2795        let policy = all_policy();
2796        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2797
2798        assert_eq!(replacement, SourceReplacement::None);
2799    }
2800
2801    #[test]
2802    fn test_source_chain_seventeen_hops_exceeds_bound() {
2803        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2804        let _guard = deps_core::fs_probe::snapshot_guard();
2805        let root = tempfile::tempdir().unwrap();
2806        let mut toml = String::from("[source.crates-io]\nreplace-with = \"hop0\"\n");
2807        for i in 0..16 {
2808            toml.push_str(&format!(
2809                "[source.hop{i}]\nreplace-with = \"hop{}\"\n",
2810                i + 1
2811            ));
2812        }
2813        toml.push_str("[source.hop16]\nregistry = \"sparse+https://terminal.example\"\n");
2814        let path = write_config(root.path(), &toml);
2815
2816        let cache = ConfigFileCache::new();
2817        let policy = all_policy();
2818        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2819
2820        // 17 hops (crates-io -> hop0 -> ... -> hop16) exceeds MAX_SOURCE_REPLACEMENT_HOPS (16).
2821        assert_eq!(replacement, SourceReplacement::None);
2822    }
2823
2824    /// #1505 P4: the cyclic `[source] replace-with` chain warning used to interpolate the
2825    /// revisited source id raw (`id = %current_id`), letting a manifest-adjacent
2826    /// `.cargo/config.toml` with a crafted source table name forge a log line. `id` is now a
2827    /// `?`-Debug field.
2828    #[test]
2829    fn test_source_chain_cyclic_id_logs_sanitized() {
2830        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2831        let _guard = deps_core::fs_probe::snapshot_guard();
2832        let malicious_id = "bad\r\n\x1b[31mERROR deps_lsp: FORGED";
2833        let root = tempfile::tempdir().unwrap();
2834        let path = write_config(
2835            root.path(),
2836            "[source.crates-io]\nreplace-with = \"bad\\r\\n\\u001b[31mERROR deps_lsp: FORGED\"\n\
2837             [source.\"bad\\r\\n\\u001b[31mERROR deps_lsp: FORGED\"]\nreplace-with = \"bad\\r\\n\\u001b[31mERROR deps_lsp: FORGED\"\n",
2838        );
2839
2840        let cache = ConfigFileCache::new();
2841        let policy = all_policy();
2842
2843        let log = deps_core::test_util::capture_tracing_output(|| {
2844            let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2845            assert_eq!(replacement, SourceReplacement::None);
2846        });
2847
2848        assert_eq!(
2849            log.lines().count(),
2850            1,
2851            "a crafted source id must not forge an extra log line: {log:?}"
2852        );
2853        assert!(
2854            !log.contains(malicious_id),
2855            "the raw, un-escaped payload (with its literal CR/ESC bytes) must not survive \
2856             intact: {log:?}"
2857        );
2858    }
2859
2860    #[test]
2861    fn test_source_chain_terminal_blocked_by_policy() {
2862        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2863        let _guard = deps_core::fs_probe::snapshot_guard();
2864        let root = tempfile::tempdir().unwrap();
2865        let path = write_config(
2866            root.path(),
2867            "[source.crates-io]\nreplace-with = \"metadata\"\n\
2868             [source.metadata]\nregistry = \"sparse+https://169.254.169.254/\"\n",
2869        );
2870
2871        let cache = ConfigFileCache::new();
2872        let policy = public_only_policy();
2873        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2874
2875        assert_eq!(replacement, SourceReplacement::None);
2876    }
2877
2878    /// Stage-1 crossover (critic S4): a `replace-with` naming a `[registries]` entry, not
2879    /// a `[source]` entry, must still resolve.
2880    #[test]
2881    fn test_source_chain_stage_one_registries_crossover() {
2882        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2883        let _guard = deps_core::fs_probe::snapshot_guard();
2884        let root = tempfile::tempdir().unwrap();
2885        let path = write_config(
2886            root.path(),
2887            "[source.crates-io]\nreplace-with = \"my-corp\"\n\
2888             [registries.my-corp]\nindex = \"sparse+https://index.mycorp.dev\"\n",
2889        );
2890
2891        let cache = ConfigFileCache::new();
2892        let policy = all_policy();
2893        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2894
2895        match replacement {
2896            SourceReplacement::SparseMirror { index, .. } => {
2897                assert_eq!(index.as_str(), "https://index.mycorp.dev");
2898            }
2899            SourceReplacement::None => panic!("expected the [registries] crossover to resolve"),
2900        }
2901    }
2902
2903    /// S2 regression: `[source.crates-io]` carrying an explicit definition (here, a bare
2904    /// git-index `registry =`, exactly the shape Cargo treats as the implicit builtin
2905    /// crates.io definition) *and* `replace-with` in the same table — the shape every large
2906    /// public mirror's setup instructions publish verbatim. Cargo applies `replace-with`
2907    /// regardless of the explicit definition; this must resolve the mirror, not `None`.
2908    #[test]
2909    fn test_source_chain_replace_with_wins_over_explicit_kind_on_same_table() {
2910        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2911        let _guard = deps_core::fs_probe::snapshot_guard();
2912        let root = tempfile::tempdir().unwrap();
2913        let path = write_config(
2914            root.path(),
2915            "[source.crates-io]\n\
2916             registry = \"https://github.com/rust-lang/crates.io-index\"\n\
2917             replace-with = \"mirror\"\n\
2918             [source.mirror]\nregistry = \"sparse+https://mirror.example/index/\"\n",
2919        );
2920
2921        let cache = ConfigFileCache::new();
2922        let policy = all_policy();
2923        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2924
2925        match replacement {
2926            SourceReplacement::SparseMirror { index, .. } => {
2927                assert_eq!(index.as_str(), "https://mirror.example/index");
2928            }
2929            SourceReplacement::None => panic!(
2930                "replace-with must apply even though [source.crates-io] also declares an explicit kind"
2931            ),
2932        }
2933    }
2934
2935    /// The inverse S2 shape: a table declaring both a *sparse* `registry =` of its own AND a
2936    /// `replace-with` pointing elsewhere. Cargo still follows `replace-with`, never the
2937    /// table's own `registry` value — asserting the resolved index is the replacement
2938    /// target, not the table's own (differently-hosted) sparse registry.
2939    #[test]
2940    fn test_source_chain_replace_with_wins_over_own_sparse_registry() {
2941        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2942        let _guard = deps_core::fs_probe::snapshot_guard();
2943        let root = tempfile::tempdir().unwrap();
2944        let path = write_config(
2945            root.path(),
2946            "[source.crates-io]\n\
2947             registry = \"sparse+https://a.example/index/\"\n\
2948             replace-with = \"b\"\n\
2949             [source.b]\nregistry = \"sparse+https://b.example/index/\"\n",
2950        );
2951
2952        let cache = ConfigFileCache::new();
2953        let policy = all_policy();
2954        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
2955
2956        match replacement {
2957            SourceReplacement::SparseMirror { index, .. } => {
2958                assert_eq!(
2959                    index.as_str(),
2960                    "https://b.example/index",
2961                    "replace-with must win over the table's own sparse `registry` value"
2962                );
2963            }
2964            SourceReplacement::None => panic!("expected the replace-with target to resolve"),
2965        }
2966    }
2967
2968    /// A workspace-tier `replace-with` crossing into a `$CARGO_HOME` `[registries]` entry that
2969    /// carries a token resolves to the operator's own URL, so it carries the credential bound to
2970    /// that URL: the credential follows the URL, not the workspace link that reached it (it goes
2971    /// to the operator's server and nowhere else).
2972    #[test]
2973    fn test_source_chain_workspace_crossover_into_an_operator_url_uses_its_bound_credential() {
2974        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
2975        let _guard = deps_core::fs_probe::snapshot_guard();
2976        let root = tempfile::tempdir().unwrap();
2977        let workspace_path = write_config(
2978            root.path(),
2979            "[source.crates-io]\nreplace-with = \"my-corp\"\n",
2980        );
2981
2982        let cargo_home = tempfile::tempdir().unwrap();
2983        std::fs::write(
2984            cargo_home.path().join("config.toml"),
2985            "[registries.my-corp]\nindex = \"sparse+https://index.mycorp.dev\"\ntoken = \"operator-token\"\n",
2986        )
2987        .unwrap();
2988
2989        let cache = ConfigFileCache::new();
2990        let policy = all_policy();
2991        let (_, replacement) = resolve(
2992            &HashSet::new(),
2993            &[workspace_path],
2994            Some(&cargo_home_config(cargo_home.path())),
2995            &cache,
2996            &policy,
2997        );
2998
2999        match replacement {
3000            SourceReplacement::SparseMirror { index } => {
3001                assert_eq!(index.as_str(), "https://index.mycorp.dev");
3002                assert_eq!(
3003                    index.credential().map(AuthToken::expose_secret),
3004                    Some("operator-token")
3005                );
3006            }
3007            SourceReplacement::None => panic!("expected the mirror to resolve"),
3008        }
3009    }
3010
3011    /// The positive counterpart: when the *whole* chain is `$CARGO_HOME`-declared, the
3012    /// terminal `[registries]` entry's token is legitimately attached.
3013    #[test]
3014    fn test_source_chain_fully_trusted_chain_attaches_cargo_home_token() {
3015        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
3016        let _guard = deps_core::fs_probe::snapshot_guard();
3017        let cargo_home = tempfile::tempdir().unwrap();
3018        std::fs::write(
3019            cargo_home.path().join("config.toml"),
3020            "[source.crates-io]\nreplace-with = \"my-corp\"\n\
3021             [registries.my-corp]\nindex = \"sparse+https://index.mycorp.dev\"\ntoken = \"real-token\"\n",
3022        )
3023        .unwrap();
3024
3025        let cache = ConfigFileCache::new();
3026        let policy = all_policy();
3027        let (_, replacement) = resolve(
3028            &HashSet::new(),
3029            &[],
3030            Some(&cargo_home_config(cargo_home.path())),
3031            &cache,
3032            &policy,
3033        );
3034
3035        match replacement {
3036            SourceReplacement::SparseMirror { index } => {
3037                assert_eq!(
3038                    index.credential().map(AuthToken::expose_secret),
3039                    Some("real-token")
3040                );
3041            }
3042            SourceReplacement::None => panic!("expected the fully-trusted chain to resolve"),
3043        }
3044    }
3045
3046    #[test]
3047    fn test_source_chain_no_source_section_resolves_none() {
3048        // Per `fs_probe::snapshot_guard`'s doc: every fs_probe-touching test here must hold it.
3049        let _guard = deps_core::fs_probe::snapshot_guard();
3050        let root = tempfile::tempdir().unwrap();
3051        let path = write_config(
3052            root.path(),
3053            "[registries.other]\nindex = \"sparse+https://other.example\"\n",
3054        );
3055
3056        let cache = ConfigFileCache::new();
3057        let policy = all_policy();
3058        let (_, replacement) = resolve(&HashSet::new(), &[path], None, &cache, &policy);
3059
3060        assert_eq!(replacement, SourceReplacement::None);
3061    }
3062}