1use 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#[derive(Clone, PartialEq, Eq)]
71pub(crate) struct AuthToken(deps_core::secret::Redacted);
72
73impl AuthToken {
74 pub(crate) fn new(token: String) -> Self {
77 Self(deps_core::secret::Redacted::new(token))
78 }
79
80 pub(crate) const fn as_redacted(&self) -> &deps_core::secret::Redacted {
82 &self.0
83 }
84
85 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Provenance {
114 CargoHome,
118 Workspace,
121}
122
123pub use deps_core::net_policy::RegistryTrust;
127
128pub(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
142const SPARSE_PREFIX: &str = "sparse+";
144
145#[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
159pub(crate) fn strip_sparse_prefix(raw: &str) -> StrippedIndexUrl<'_> {
161 StrippedIndexUrl(raw.strip_prefix(SPARSE_PREFIX).unwrap_or(raw))
162}
163
164pub 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
177pub use deps_core::net_policy::IndexUrlError as RegistryIndexError;
182
183#[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#[derive(Debug, Clone, PartialEq, Eq)]
213enum IndexAccess {
214 Credentialed(OperatorCredential),
215 Anonymous(RegistryTrust),
216}
217
218#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct RegistryIndex {
231 url: ValidatedRegistryUrl<CargoIndexKind>,
232 base: TrustedPrefix,
233 access: IndexAccess,
234}
235
236#[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 pub(crate) fn declaring(registries: OperatorRegistries) -> Self {
261 Self {
262 registries,
263 credentials: HashMap::new(),
264 }
265 }
266
267 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 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 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 #[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 #[must_use]
381 pub fn as_str(&self) -> &str {
382 self.url.as_str()
383 }
384
385 #[must_use]
387 pub(crate) fn trusted_prefix(&self) -> TrustedPrefix {
388 self.base.clone()
389 }
390
391 #[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 #[must_use]
403 pub const fn has_credential(&self) -> bool {
404 matches!(self.access, IndexAccess::Credentialed(_))
405 }
406
407 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 #[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 #[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#[non_exhaustive]
475#[derive(Debug, Clone)]
476pub struct ResolvedRegistryEntry {
477 pub index: RegistryIndex,
479 pub provenance: Provenance,
481}
482
483#[derive(Debug, Default)]
490pub struct CargoConfig {
491 registries: HashMap<String, ResolvedRegistryEntry>,
492 unresolved: HashMap<String, UnresolvedIndex>,
499}
500
501#[derive(Debug, Clone, Copy)]
504enum UnresolvedIndex {
505 Blocked(BlockedHost),
510 Rejected(RegistryRejectionReason),
515}
516
517impl UnresolvedIndex {
518 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 #[must_use]
530 pub fn get(&self, alias: &str) -> Option<&ResolvedRegistryEntry> {
531 self.registries.get(alias)
532 }
533
534 #[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 #[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#[non_exhaustive]
559#[derive(Debug, Clone, PartialEq)]
560pub enum SourceReplacement {
561 None,
566 SparseMirror {
568 index: RegistryIndex,
573 },
574}
575
576#[derive(Debug, Clone, PartialEq, Eq)]
580struct SourceEntry {
581 kind: Option<SourceKind>,
586 replace_with: Option<String>,
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
597enum SourceKind {
598 SparseRegistry {
600 raw: String,
602 },
603 NonSparse,
607}
608
609fn 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
629const MAX_SOURCE_ENTRIES: usize = 256;
634
635fn 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
679fn 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
690fn 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
725fn 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
761fn env_var_name(alias: &str, suffix: &'static str) -> OperatorEnvName {
765 OperatorEnvName::prefixed(ENV_REGISTRY_PREFIX, alias, suffix)
766}
767
768#[derive(Debug)]
777struct ParsedConfigFile {
778 tier: CachedTier,
779 sources: HashMap<String, SourceEntry>,
780 native: NativeConfigFile,
781}
782
783#[derive(Debug)]
792enum CachedTier {
793 Workspace(HashMap<String, String>),
795 CargoHome(HashMap<String, (String, Option<AuthToken>)>),
797}
798
799#[derive(Debug, Clone, Copy)]
801enum RawNativeValue {
802 Window(NativeTimeSpan),
804 Disabled,
806 Invalid,
808}
809
810#[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 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
908pub(crate) enum NativeScope {
909 CratesIo,
914 Alias(String),
916 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
930pub(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#[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 #[must_use]
1009 pub fn new() -> Self {
1010 Self(MtimeFileCache::new(
1011 DEFAULT_MAX_CACHED_FILES,
1012 "cargo config",
1013 ))
1014 }
1015
1016 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 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#[must_use]
1043pub fn cargo_home_config_path() -> Option<OperatorPath> {
1044 cargo_home_config_path_with_env(&ProcessEnv)
1045}
1046
1047pub(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
1063struct 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 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#[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
1161pub(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
1191fn 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
1200pub(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
1276fn 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 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
1308fn 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
1325fn 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
1332fn 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
1403enum CargoHomeResolution {
1405 Resolved(ResolvedRegistryEntry),
1407 Unresolved(UnresolvedIndex),
1414 Absent,
1416}
1417
1418fn 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 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 env_failure
1469 .or_else(|| UnresolvedIndex::from_error(&error))
1470 .map_or(CargoHomeResolution::Absent, CargoHomeResolution::Unresolved)
1471 }
1472 }
1473}
1474
1475const MAX_SOURCE_REPLACEMENT_HOPS: usize = 16;
1480
1481fn 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
1502fn 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(¤t_id))
1529 .or_else(|| {
1530 tiers
1531 .cargo_home
1532 .as_deref()
1533 .and_then(|file| file.sources.get(¤t_id))
1534 });
1535
1536 if let Some(entry) = found_source {
1537 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, ¤t_id, operator, policy);
1548 }
1549 Some(SourceKind::NonSparse) | None => {
1550 return SourceReplacement::None;
1551 }
1552 }
1553 }
1554
1555 if let Some(raw_index) = lookup_raw_registry_index(¤t_id, tiers) {
1558 if raw_index.starts_with(SPARSE_PREFIX) {
1559 return finalize_source_replacement(raw_index, ¤t_id, operator, policy);
1560 }
1561 return SourceReplacement::None;
1562 }
1563
1564 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#[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 #[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 let index = RegistryIndex::builtin("https://index.crates.io");
1744 assert_eq!(index.as_str(), "https://index.crates.io");
1745 }
1746
1747 #[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 #[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 #[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 #[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 #[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 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 #[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 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 #[test]
2004 fn test_resolve_home_nested_project_does_not_lose_cargo_home_token() {
2005 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 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 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 #[test]
2079 fn test_resolve_cargo_home_file_entry_rejected_populates_rejected() {
2080 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 #[test]
2112 fn test_resolve_env_var_index_override_rejected_falls_back_silently_to_valid_file_entry() {
2113 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 #[test]
2145 fn test_resolve_env_var_index_override_rejected_with_no_file_entry_populates_rejected() {
2146 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 #[test]
2170 fn test_resolve_env_and_file_both_rejected_prefers_env_reason() {
2171 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 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 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 #[test]
2243 fn test_resolve_env_var_name_collision_disables_both() {
2244 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 #[test]
2265 fn test_resolve_env_token_never_attaches_to_workspace_shadowed_alias() {
2266 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 #[test]
2301 fn test_resolve_sparse_prefixed_cargo_home_registry_is_trusted_with_credential() {
2302 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 #[test]
2332 fn test_resolve_env_only_operator_registry_is_trusted_without_cargo_home() {
2333 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 #[test]
2363 fn test_resolve_workspace_alias_naming_an_operator_url_gets_the_urls_trust_and_credential() {
2364 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 #[test]
2402 fn test_resolve_workspace_alias_for_an_undeclared_url_is_policy_gated() {
2403 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 #[test]
2430 fn test_resolve_cargo_home_registry_on_loopback_or_link_local_is_blocked() {
2431 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 #[test]
2462 fn test_resolve_strips_the_sparse_prefix_once() {
2463 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 #[test]
2531 fn test_config_file_cache_hit_reuses_parsed_arc_without_reparsing() {
2532 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 #[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 let _guard = deps_core::fs_probe::snapshot_guard();
2570 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 #[test]
2597 fn test_resolve_new_alias_resolves_without_config_file_change() {
2598 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 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 #[test]
2632 fn test_resolve_policy_change_takes_effect_with_no_cache_invalidation() {
2633 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 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 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 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 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 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 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 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 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 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 assert_eq!(replacement, SourceReplacement::None);
2822 }
2823
2824 #[test]
2829 fn test_source_chain_cyclic_id_logs_sanitized() {
2830 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 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 #[test]
2881 fn test_source_chain_stage_one_registries_crossover() {
2882 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 #[test]
2909 fn test_source_chain_replace_with_wins_over_explicit_kind_on_same_table() {
2910 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 #[test]
2940 fn test_source_chain_replace_with_wins_over_own_sparse_registry() {
2941 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 #[test]
2973 fn test_source_chain_workspace_crossover_into_an_operator_url_uses_its_bound_credential() {
2974 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 #[test]
3014 fn test_source_chain_fully_trusted_chain_attaches_cargo_home_token() {
3015 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 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}