Skip to main content

uv_types/
hash.rs

1use std::fmt::Display;
2use std::path::Path;
3use std::str::FromStr;
4use std::sync::Arc;
5
6use rustc_hash::FxHashMap;
7
8use uv_configuration::{Constraints, HashCheckingMode};
9use uv_distribution_types::{
10    ArchiveHashPolicy, DistributionMetadata, HashCollection, HashValidation, MetadataHashPolicy,
11    Name, Requirement, RequirementSource, Resolution, UnresolvedRequirement, VersionId,
12    satisfies_require_hashes,
13};
14use uv_normalize::PackageName;
15use uv_pep440::{Operator, Version};
16use uv_pypi_types::{
17    HashAlgorithm, HashDigest, HashDigests, HashError, Hashes, ResolverMarkerEnvironment,
18};
19use uv_redacted::SafeUrl;
20
21/// Hash collection and verification policies for a resolution.
22///
23/// Verification takes precedence for distributions with trusted hashes. The collection policy
24/// applies to the remaining distributions.
25#[derive(Debug, Default, Clone)]
26pub struct HashStrategy {
27    collection: HashCollection,
28    verification: HashVerification,
29}
30
31/// The trusted hashes to enforce when retrieving distributions.
32#[derive(Debug, Default, Clone)]
33pub enum HashVerification {
34    /// No resolution-wide hash verification policy is configured.
35    #[default]
36    Unspecified,
37    /// Validate known hashes, without requiring hashes for other distributions.
38    IfPresent(Arc<FxHashMap<VersionId, Vec<HashDigest>>>),
39    /// Every distribution must have a matching trusted hash.
40    Required(Arc<FxHashMap<VersionId, Vec<HashDigest>>>),
41}
42
43impl HashStrategy {
44    /// Collect declared hashes for resolution, computing missing hashes according to the policy.
45    pub fn collect(collection: HashCollection) -> Self {
46        Self {
47            collection,
48            ..Self::default()
49        }
50    }
51
52    /// Validate hashes when present.
53    pub fn verify(hashes: Arc<FxHashMap<VersionId, Vec<HashDigest>>>) -> Self {
54        Self::default().with_verification(HashVerification::IfPresent(hashes))
55    }
56
57    /// Require a matching trusted hash for every distribution.
58    fn require(hashes: Arc<FxHashMap<VersionId, Vec<HashDigest>>>) -> Self {
59        Self::default().with_verification(HashVerification::Required(hashes))
60    }
61
62    /// Set verification independently of hash collection.
63    #[must_use]
64    pub fn with_verification(mut self, verification: HashVerification) -> Self {
65        self.verification = verification;
66        self
67    }
68
69    /// Apply constraint hashes using the same rules as [`Self::from_requirements`].
70    ///
71    /// Preserve hash collection and require hashes if either strategy requires them. Constraints
72    /// for identities absent from this strategy remain available for newly resolved dependencies.
73    pub fn with_constraint_hashes(mut self, constraints: &Self) -> Result<Self, HashStrategyError> {
74        let (requirement_hashes, mode) = match &self.verification {
75            HashVerification::Unspecified => {
76                self.verification = constraints.verification.clone();
77                return Ok(self);
78            }
79            HashVerification::IfPresent(hashes) => {
80                let mode = match &constraints.verification {
81                    HashVerification::Required(_) => HashCheckingMode::Require,
82                    HashVerification::Unspecified | HashVerification::IfPresent(_) => {
83                        HashCheckingMode::Verify
84                    }
85                };
86                (hashes, mode)
87            }
88            HashVerification::Required(hashes) => (hashes, HashCheckingMode::Require),
89        };
90
91        let mut constraints = constraints.clone();
92        let constraint_hashes = match &mut constraints.verification {
93            HashVerification::Unspecified => return Ok(self),
94            HashVerification::IfPresent(hashes) | HashVerification::Required(hashes) => {
95                Arc::make_mut(hashes)
96            }
97        };
98        if mode.is_require() {
99            constraint_hashes.retain(|_, digests| {
100                digests.retain(satisfies_require_hashes);
101                !digests.is_empty()
102            });
103        }
104        let mut hashes = constraint_hashes.clone();
105        for (id, digests) in requirement_hashes.iter() {
106            let mut digests = digests.clone();
107            if mode.is_require() {
108                digests.retain(satisfies_require_hashes);
109            }
110            let digests = if let Some(constraint) = constraints.hashes_for_id(id) {
111                combine_constraint_hashes(id, digests, constraint, id, mode)?
112            } else {
113                digests
114            };
115            if !digests.is_empty() {
116                hashes.insert(id.clone(), digests);
117            }
118        }
119        self.verification = match mode {
120            HashCheckingMode::Verify => HashVerification::IfPresent(Arc::new(hashes)),
121            HashCheckingMode::Require => HashVerification::Required(Arc::new(hashes)),
122        };
123        Ok(self)
124    }
125
126    /// Return the hash collection policy.
127    pub fn collection(&self) -> HashCollection {
128        self.collection
129    }
130
131    /// Return the hash verification policy.
132    pub fn verification(&self) -> &HashVerification {
133        &self.verification
134    }
135
136    /// Return the [`ArchiveHashPolicy`] for the given distribution.
137    pub fn archive_policy<T: DistributionMetadata>(
138        &self,
139        distribution: &T,
140    ) -> ArchiveHashPolicy<'_> {
141        self.archive_policy_for_id(|| distribution.version_id())
142    }
143
144    /// Return the [`MetadataHashPolicy`] for retrieving the given distribution's metadata.
145    pub fn metadata_policy<T: DistributionMetadata>(
146        &self,
147        distribution: &T,
148    ) -> MetadataHashPolicy<'_> {
149        MetadataHashPolicy {
150            collection: self.collection,
151            validation: self.validation_for_id(|| distribution.version_id()),
152        }
153    }
154
155    /// Return the [`ArchiveHashPolicy`] for the given registry-based package.
156    pub fn archive_policy_for_package(
157        &self,
158        name: &PackageName,
159        version: &Version,
160    ) -> ArchiveHashPolicy<'_> {
161        self.archive_policy_for_id(|| VersionId::from_registry(name.clone(), version.clone()))
162    }
163
164    /// Return the [`ArchiveHashPolicy`] for the given direct URL package.
165    ///
166    /// A direct URL identifies a single concrete artifact, so every provided digest must match.
167    pub fn archive_policy_for_url(&self, url: &SafeUrl) -> ArchiveHashPolicy<'_> {
168        self.archive_policy_for_id(|| VersionId::from_url(url))
169    }
170
171    /// Return the [`MetadataHashPolicy`] for a URL whose package name is not yet known.
172    pub fn metadata_policy_for_url(&self, url: &SafeUrl) -> MetadataHashPolicy<'_> {
173        MetadataHashPolicy {
174            collection: self.collection,
175            validation: self.validation_for_id(|| VersionId::from_url(url)),
176        }
177    }
178
179    /// Return the archive hash policy for a distribution identity.
180    fn archive_policy_for_id(&self, id: impl FnOnce() -> VersionId) -> ArchiveHashPolicy<'_> {
181        let validation = self.validation_for_id(id);
182        match validation {
183            HashValidation::None => match self.collection {
184                HashCollection::None => ArchiveHashPolicy::None,
185                HashCollection::Url | HashCollection::All => ArchiveHashPolicy::Generate,
186            },
187            HashValidation::Any(_) | HashValidation::All(_) => validation.into(),
188        }
189    }
190
191    /// Construct an identity only when verification requires a lookup.
192    fn validation_for_id(&self, id: impl FnOnce() -> VersionId) -> HashValidation<'_> {
193        match &self.verification {
194            HashVerification::IfPresent(_) => {
195                let id = id();
196                if let Some(hashes) = self.hashes_for_id(&id) {
197                    return hash_validation(&id, hashes);
198                }
199            }
200            HashVerification::Required(hashes) => {
201                let id = id();
202                return hash_validation(
203                    &id,
204                    hashes.get(&id).map(Vec::as_slice).unwrap_or_default(),
205                );
206            }
207            HashVerification::Unspecified => {}
208        }
209        HashValidation::None
210    }
211
212    /// Look up supplied hashes, including public-version pins in verification mode.
213    fn hashes_for_id(&self, id: &VersionId) -> Option<&[HashDigest]> {
214        match &self.verification {
215            HashVerification::Unspecified => None,
216            HashVerification::IfPresent(hashes) => hashes
217                .get(id)
218                .or_else(|| {
219                    // `==1.0.0` can also select `1.0.0+local`. If the local version has no hash
220                    // of its own, check it against the hash for `1.0.0`.
221                    if let VersionId::NameVersion(name, version) = id
222                        && version.is_local()
223                    {
224                        hashes.get(&VersionId::from_registry(
225                            name.clone(),
226                            version.clone().without_local(),
227                        ))
228                    } else {
229                        None
230                    }
231                })
232                .map(Vec::as_slice),
233            HashVerification::Required(hashes) => hashes.get(id).map(Vec::as_slice),
234        }
235    }
236
237    /// Returns `true` if the given registry-based package is allowed.
238    pub fn allows_package(&self, name: &PackageName, version: &Version) -> bool {
239        match &self.verification {
240            HashVerification::Required(hashes) => {
241                hashes.contains_key(&VersionId::from_registry(name.clone(), version.clone()))
242            }
243            HashVerification::Unspecified | HashVerification::IfPresent(_) => true,
244        }
245    }
246
247    /// Returns `true` if the given direct URL package is allowed.
248    pub fn allows_url(&self, url: &SafeUrl) -> bool {
249        match &self.verification {
250            HashVerification::Required(hashes) => hashes.contains_key(&VersionId::from_url(url)),
251            HashVerification::Unspecified | HashVerification::IfPresent(_) => true,
252        }
253    }
254
255    /// Return a [`HashStrategy`] augmented with archive URL hashes discovered in additional
256    /// requirements after the initial command-line parse.
257    pub fn augment_with_requirements<'a>(
258        mut self,
259        requirements: impl Iterator<Item = &'a Requirement>,
260    ) -> Result<Self, HashStrategyError> {
261        match &mut self.verification {
262            HashVerification::Unspecified => {}
263            HashVerification::IfPresent(existing) | HashVerification::Required(existing) => {
264                if let Some(hashes) = Self::augment_hashes(existing, requirements)? {
265                    *existing = Arc::new(hashes);
266                }
267            }
268        }
269        Ok(self)
270    }
271
272    /// Return a [`HashStrategy`] augmented with archive URL hashes discovered in distribution
273    /// metadata.
274    ///
275    /// Required-hash verification is intentionally a closed set. In that mode, distribution
276    /// untrusted metadata cannot authorize a requirement that was absent from the input hash set.
277    /// Explicit requirements, such as `build-system.requires` and user-provided metadata, can still
278    /// contribute hashes via [`Self::augment_with_requirements`].
279    pub fn augment_with_metadata_requirements<'a>(
280        self,
281        requirements: impl Iterator<Item = &'a Requirement>,
282    ) -> Result<Self, HashStrategyError> {
283        if matches!(&self.verification, HashVerification::Required(_)) {
284            return Ok(self);
285        }
286        self.augment_with_requirements(requirements)
287    }
288
289    /// Collect hashes from [`UnresolvedRequirement`] entries and constraints.
290    ///
291    /// For duplicate registry pins and local files, the last nonempty hash list wins. Remote
292    /// archive URLs combine hashes across algorithms and reject conflicting digests for the same
293    /// algorithm. Registry pins accept any allowed digest; direct references must match all
294    /// supplied digests. When requirements and constraints both supply hashes, registry pins
295    /// permit only shared hashes; direct references must match hashes from both sources.
296    ///
297    /// When the environment is not given, this treats all marker expressions
298    /// that reference the environment as true. In other words, it does
299    /// environment independent expression evaluation. (Which in turn devolves
300    /// to "only evaluate marker expressions that reference an extra name or a wheel variant.")
301    pub fn from_requirements<'a>(
302        requirements: impl Iterator<Item = (&'a UnresolvedRequirement, &'a [String])>,
303        constraints: impl Iterator<Item = (&'a Requirement, &'a [String])>,
304        marker_env: Option<&ResolverMarkerEnvironment>,
305        mode: HashCheckingMode,
306    ) -> Result<Self, HashStrategyError> {
307        let mut constraint_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();
308
309        // First, index the constraints by name.
310        for (requirement, digests) in constraints {
311            if !requirement
312                .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[])
313            {
314                continue;
315            }
316
317            // Every constraint must be a pinned version.
318            let Some(id) = Self::pin(requirement) else {
319                if mode.is_require() {
320                    return Err(HashStrategyError::UnpinnedRequirement(
321                        requirement.to_string(),
322                        mode,
323                    ));
324                }
325                continue;
326            };
327
328            let (digests, _) =
329                parse_declared_hashes(digests, requirement.hashes(), requirement, mode)?;
330
331            if digests.is_empty() {
332                continue;
333            }
334
335            merge_hashes(&mut constraint_hashes, id, digests, requirement)?;
336        }
337
338        // For each requirement, map from hash identity to allowed hashes.
339        let mut requirement_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();
340        for (requirement, digests) in requirements {
341            if !requirement
342                .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[])
343            {
344                continue;
345            }
346
347            // Every requirement must be either a pinned version or a direct URL.
348            let id = match &requirement {
349                UnresolvedRequirement::Named(requirement) => {
350                    if let Some(id) = Self::pin(requirement) {
351                        id
352                    } else {
353                        if mode.is_require() {
354                            return Err(HashStrategyError::UnpinnedRequirement(
355                                requirement.to_string(),
356                                mode,
357                            ));
358                        }
359                        continue;
360                    }
361                }
362                UnresolvedRequirement::Unnamed(requirement) => {
363                    // Direct URLs are always allowed.
364                    VersionId::from_parsed_url(requirement.url.parsed_url.clone())
365                }
366            };
367
368            let (digests, rejected_algorithm) =
369                parse_declared_hashes(digests, requirement.hashes(), requirement, mode)?;
370
371            let digests = if let Some(constraint) = constraint_hashes.get(&id) {
372                // A hashless duplicate must not replace earlier requirement hashes with the
373                // constraint's hashes.
374                if digests.is_empty() && requirement_hashes.contains_key(&id) {
375                    continue;
376                }
377                combine_constraint_hashes(&id, digests, constraint, requirement, mode)?
378            } else {
379                digests
380            };
381
382            // Under `--require-hashes`, every requirement needs a hash from the requirement or a
383            // constraint.
384            if digests.is_empty() {
385                if mode.is_require() {
386                    if let Some(algorithm) = rejected_algorithm {
387                        return Err(HashStrategyError::InsecureHashAlgorithm(
388                            requirement.to_string(),
389                            algorithm,
390                            mode,
391                        ));
392                    }
393                    return Err(HashStrategyError::MissingHashes(
394                        requirement.to_string(),
395                        mode,
396                    ));
397                }
398                continue;
399            }
400
401            merge_hashes(&mut requirement_hashes, id, digests, requirement)?;
402        }
403
404        // Requirements take precedence because each matching constraint is already applied.
405        let hashes: FxHashMap<VersionId, Vec<HashDigest>> = constraint_hashes
406            .into_iter()
407            .chain(requirement_hashes)
408            .collect();
409        match mode {
410            HashCheckingMode::Verify => Ok(Self::verify(Arc::new(hashes))),
411            HashCheckingMode::Require => Ok(Self::require(Arc::new(hashes))),
412        }
413    }
414
415    /// Collect hashes from [`Constraints`] using the same handling as regular constraints in
416    /// [`Self::from_requirements`], preserving declaration order.
417    pub fn from_constraints(
418        constraints: &Constraints,
419        marker_env: Option<&ResolverMarkerEnvironment>,
420        mode: HashCheckingMode,
421    ) -> Result<Self, HashStrategyError> {
422        Self::from_requirements(
423            std::iter::empty(),
424            constraints
425                .specifications()
426                .map(|entry| (&entry.requirement, entry.hashes.as_slice())),
427            marker_env,
428            mode,
429        )
430    }
431
432    /// Read the required hashes from a [`Resolution`].
433    pub fn from_resolution(
434        resolution: &Resolution,
435        mode: HashCheckingMode,
436    ) -> Result<Self, HashStrategyError> {
437        let mut hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();
438
439        for (dist, digests) in resolution.hashes() {
440            if digests.is_empty() {
441                // Under `--require-hashes`, every requirement must include a hash.
442                if mode.is_require() {
443                    return Err(HashStrategyError::MissingHashes(
444                        dist.name().to_string(),
445                        mode,
446                    ));
447                }
448                continue;
449            }
450            hashes.insert(dist.version_id(), digests.to_vec());
451        }
452
453        match mode {
454            HashCheckingMode::Verify => Ok(Self::verify(Arc::new(hashes))),
455            HashCheckingMode::Require => Ok(Self::require(Arc::new(hashes))),
456        }
457    }
458
459    /// Augment an existing set of hashes with archive URL hashes discovered in additional
460    /// requirements.
461    ///
462    /// Archive URL requirements are keyed by a [`VersionId`] so that requirements that refer to
463    /// the same underlying archive but differ only in hash fragments are merged onto the same
464    /// digest set.
465    ///
466    /// Returns `Ok(None)` if no new hashes were added or updated.
467    fn augment_hashes<'a>(
468        existing: &FxHashMap<VersionId, Vec<HashDigest>>,
469        requirements: impl Iterator<Item = &'a Requirement>,
470    ) -> Result<Option<FxHashMap<VersionId, Vec<HashDigest>>>, HashStrategyError> {
471        let mut hashes = None;
472
473        for requirement in requirements {
474            // TODO(konsti): A contradiction folded during parsing has already lost its
475            // variant marker. Decide how to handle hashes on all such declarations.
476            if requirement.marker.resolve_dependency_variants().is_none() {
477                continue;
478            }
479            let Some((id, digests)) = Self::requirement_hashes(requirement)? else {
480                continue;
481            };
482            let current = hashes.as_ref().unwrap_or(existing);
483            let current_digests = current.get(&id);
484            let mut merged = current_digests.cloned().unwrap_or_default();
485            merge_digests(&mut merged, &digests, requirement)?;
486
487            if current_digests.map(Vec::as_slice) == Some(merged.as_slice()) {
488                continue;
489            }
490
491            hashes
492                .get_or_insert_with(|| existing.clone())
493                .insert(id, merged);
494        }
495
496        Ok(hashes)
497    }
498
499    /// Extract the archive URL hash target and digests for a requirement, if any.
500    fn requirement_hashes(
501        requirement: &Requirement,
502    ) -> Result<Option<(VersionId, Vec<HashDigest>)>, HashStrategyError> {
503        let Some(hashes) = requirement.hashes()? else {
504            return Ok(None);
505        };
506        let mut digests = HashDigests::from(hashes).to_vec();
507        if digests.is_empty() {
508            return Ok(None);
509        }
510        digests.sort_unstable();
511        let Some(id) = Self::pin(requirement) else {
512            return Ok(None);
513        };
514        Ok(Some((id, digests)))
515    }
516
517    /// Pin a [`Requirement`] to a [`VersionId`], if possible.
518    fn pin(requirement: &Requirement) -> Option<VersionId> {
519        match &requirement.source {
520            RequirementSource::Registry { specifier, .. } => {
521                // Must be a single specifier.
522                let [specifier] = specifier.as_ref() else {
523                    return None;
524                };
525
526                // Must be pinned to a specific version.
527                let is_pinned =
528                    matches!(specifier.operator(), Operator::Equal | Operator::ExactEqual);
529                if !is_pinned {
530                    return None;
531                }
532
533                Some(VersionId::from_registry(
534                    requirement.name.clone(),
535                    specifier.version().clone(),
536                ))
537            }
538            RequirementSource::Url {
539                location,
540                subdirectory,
541                ..
542            } => Some(VersionId::from_archive(
543                location.as_url().clone(),
544                subdirectory.clone().map(Path::into_path_buf),
545            )),
546            RequirementSource::GitDirectory {
547                git, subdirectory, ..
548            } => Some(VersionId::from_git(git, subdirectory.as_deref())),
549            RequirementSource::GitPath {
550                git, install_path, ..
551            } => Some(VersionId::from_git(git, Some(install_path))),
552            RequirementSource::Path { install_path, .. } => {
553                Some(VersionId::from_path(install_path))
554            }
555            RequirementSource::Directory { install_path, .. } => {
556                Some(VersionId::from_directory(install_path))
557            }
558        }
559    }
560}
561
562fn hash_validation<'a>(id: &VersionId, digests: &'a [HashDigest]) -> HashValidation<'a> {
563    match id {
564        VersionId::NameVersion { .. } => HashValidation::Any(digests),
565        VersionId::ArchiveUrl { .. }
566        | VersionId::Git { .. }
567        | VersionId::Path { .. }
568        | VersionId::Directory { .. }
569        | VersionId::Unknown { .. } => HashValidation::All(digests),
570    }
571}
572
573/// Combine hashes for a requirement and an applicable constraint.
574fn combine_constraint_hashes(
575    id: &VersionId,
576    mut digests: Vec<HashDigest>,
577    constraint: &[HashDigest],
578    requirement: impl Display,
579    mode: HashCheckingMode,
580) -> Result<Vec<HashDigest>, HashStrategyError> {
581    if digests.is_empty() {
582        // If there are _only_ hashes on the constraints, use them.
583        return Ok(constraint.to_vec());
584    }
585    match id {
586        VersionId::NameVersion(..) => {
587            // If there are constraint and requirement hashes, take the intersection.
588            digests.retain(|digest| constraint.contains(digest));
589            if digests.is_empty() {
590                return Err(HashStrategyError::NoIntersection(
591                    requirement.to_string(),
592                    mode,
593                ));
594            }
595        }
596        VersionId::ArchiveUrl { .. }
597        | VersionId::Git { .. }
598        | VersionId::Path(..)
599        | VersionId::Directory(..)
600        | VersionId::Unknown(..) => {
601            merge_digests(&mut digests, constraint, requirement)?;
602        }
603    }
604    Ok(digests)
605}
606
607/// Parse requirement-file hashes and combine them with any URL-fragment hashes.
608fn parse_declared_hashes(
609    hashes: &[String],
610    fragment_hashes: Result<Option<Hashes>, HashError>,
611    requirement: impl Display,
612    mode: HashCheckingMode,
613) -> Result<(Vec<HashDigest>, Option<HashAlgorithm>), HashStrategyError> {
614    let mut digests = hashes
615        .iter()
616        .map(|digest| HashDigest::from_str(digest))
617        .collect::<Result<Vec<_>, _>>()?;
618    if let Some(fragment_hashes) = fragment_hashes? {
619        merge_digests(
620            &mut digests,
621            HashDigests::from(fragment_hashes).iter(),
622            requirement,
623        )?;
624    }
625    let rejected = if mode.is_require() {
626        let rejected = digests
627            .iter()
628            .find(|digest| !satisfies_require_hashes(digest))
629            .map(HashDigest::algorithm);
630        digests.retain(satisfies_require_hashes);
631        rejected
632    } else {
633        None
634    };
635    Ok((digests, rejected))
636}
637
638/// Merge repeated hashes for a requirement or constraint into the hash map.
639fn merge_hashes(
640    hashes: &mut FxHashMap<VersionId, Vec<HashDigest>>,
641    id: VersionId,
642    incoming: Vec<HashDigest>,
643    requirement: impl Display,
644) -> Result<(), HashStrategyError> {
645    if incoming.is_empty() {
646        return Ok(());
647    }
648
649    if !matches!(&id, VersionId::ArchiveUrl { .. }) {
650        hashes.insert(id, incoming);
651        return Ok(());
652    }
653
654    if let Some(existing) = hashes.get_mut(&id) {
655        return merge_digests(existing, &incoming, requirement);
656    }
657
658    let mut merged = Vec::new();
659    merge_digests(&mut merged, &incoming, requirement)?;
660    hashes.insert(id, merged);
661    Ok(())
662}
663
664/// Merge `incoming` digests into `existing`.
665///
666/// Exact duplicates are ignored. Digests for different algorithms are accumulated. If the
667/// same algorithm appears with two different values, returns
668/// [`HashStrategyError::ConflictingArchiveUrlHashes`].
669fn merge_digests<'a>(
670    existing: &mut Vec<HashDigest>,
671    incoming: impl IntoIterator<Item = &'a HashDigest>,
672    requirement: impl Display,
673) -> Result<(), HashStrategyError> {
674    for digest in incoming {
675        match existing
676            .iter()
677            .find(|candidate| candidate.algorithm() == digest.algorithm())
678        {
679            Some(candidate) if candidate == digest => {}
680            Some(conflict) => {
681                return Err(HashStrategyError::ConflictingArchiveUrlHashes(
682                    requirement.to_string(),
683                    conflict.clone(),
684                    digest.clone(),
685                ));
686            }
687            None => existing.push(digest.clone()),
688        }
689    }
690    existing.sort_unstable();
691
692    Ok(())
693}
694
695#[derive(thiserror::Error, Debug)]
696pub enum HashStrategyError {
697    #[error(transparent)]
698    Hash(#[from] HashError),
699    #[error("Conflicting archive URL hashes for `{0}`: `{1}` conflicts with `{2}`")]
700    ConflictingArchiveUrlHashes(String, HashDigest, HashDigest),
701    #[error(
702        "In `{1}` mode, all requirements must have their versions pinned with `==`, but found: {0}"
703    )]
704    UnpinnedRequirement(String, HashCheckingMode),
705    #[error(
706        "`{1}` hashes are insecure and cannot be used with `{2}` but no other hashes are available for: {0}"
707    )]
708    InsecureHashAlgorithm(String, HashAlgorithm, HashCheckingMode),
709    #[error("In `{1}` mode, all requirements must have a hash, but none were provided for: {0}")]
710    MissingHashes(String, HashCheckingMode),
711    #[error(
712        "In `{1}` mode, all requirements must have a hash, but there were no overlapping hashes between the requirements and constraints for: {0}"
713    )]
714    NoIntersection(String, HashCheckingMode),
715}
716
717#[cfg(test)]
718mod tests {
719    use std::path::Path;
720    use std::slice;
721    use std::str::FromStr;
722    use std::sync::Arc;
723
724    use rustc_hash::FxHashMap;
725    use uv_configuration::HashCheckingMode;
726    use uv_distribution_filename::DistExtension;
727    use uv_distribution_types::{
728        ArchiveHashPolicy, HashCollection, HashValidation, MetadataHashPolicy, Requirement,
729        RequirementScope, RequirementSource, UnresolvedRequirement, VersionId,
730    };
731    use uv_normalize::PackageName;
732    use uv_pep440::Version;
733    use uv_pypi_types::HashDigest;
734    use uv_redacted::SafeUrl;
735    use uv_redacted::policy::Raw;
736
737    use super::{HashStrategy, HashVerification};
738
739    fn requirement(url: &str) -> Requirement {
740        Requirement {
741            name: "anyio".parse().unwrap(),
742            extras: Box::default(),
743            groups: Box::default(),
744            marker: "python_version >= '3.8'".parse().unwrap(),
745            source: RequirementSource::Url {
746                location: url
747                    .split_once('#')
748                    .map_or(url, |(location, _)| location)
749                    .parse::<SafeUrl>()
750                    .unwrap()
751                    .with_policy(Raw),
752                subdirectory: None,
753                ext: DistExtension::Wheel,
754                url: url.parse().unwrap(),
755            },
756            scope: RequirementScope::Global,
757            origin: None,
758        }
759    }
760
761    #[test]
762    fn from_requirements_merges_direct_url_hashes_across_fragments() {
763        let first = UnresolvedRequirement::Named(requirement(
764            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha256=CFDB2B588B9FC25EDE96D8DB56ED50848B0B649DCA3DD1DF0B11F683BB9E0B5F",
765        ));
766        let second = UnresolvedRequirement::Named(requirement(
767            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha512=f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
768        ));
769
770        let hasher = HashStrategy::from_requirements(
771            [(&first, &[][..]), (&second, &[][..])].into_iter(),
772            std::iter::empty(),
773            None,
774            HashCheckingMode::Require,
775        )
776        .unwrap();
777
778        let mut expected = vec![
779            HashDigest::from_str(
780                "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
781            )
782            .unwrap(),
783            HashDigest::from_str(
784                "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
785            )
786            .unwrap(),
787        ];
788        expected.sort_unstable();
789
790        for requirement in [&first, &second] {
791            let UnresolvedRequirement::Named(requirement) = requirement else {
792                panic!("expected named requirement");
793            };
794            let RequirementSource::Url { url, .. } = &requirement.source else {
795                panic!("expected direct URL requirement");
796            };
797            assert_eq!(
798                hasher.archive_policy_for_url(url),
799                ArchiveHashPolicy::All(expected.as_slice())
800            );
801        }
802    }
803
804    #[test]
805    fn inactive_variant_dependency_cannot_authorize_url() -> Result<(), Box<dyn std::error::Error>>
806    {
807        let url = "https://example.com/anyio-4.0.0-py3-none-any.whl";
808        let digest = "cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f";
809        let mut dependency = requirement(&format!("{url}#sha256={digest}"));
810        dependency.marker = "variant_label == 'gpu'".parse()?;
811        let hasher = HashStrategy::require(Arc::default())
812            .augment_with_requirements(std::iter::once(&dependency))?;
813        assert!(!hasher.allows_url(&url.parse()?));
814        Ok(())
815    }
816
817    #[test]
818    fn generate_and_verify_validates_known_hashes_and_generates_unknown_hashes()
819    -> Result<(), Box<dyn std::error::Error>> {
820        let url: SafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
821        let unknown_url: SafeUrl = "https://example.com/anyio-4.1.0.tar.gz".parse()?;
822        let name: PackageName = "anyio".parse()?;
823        let version: Version = "4.0.0".parse()?;
824        let unknown_version: Version = "4.1.0".parse()?;
825        let digest = HashDigest::from_str(
826            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
827        )?;
828        let hashes = FxHashMap::from_iter([
829            (VersionId::from_url(&url), vec![digest.clone()]),
830            (
831                VersionId::from_registry(name.clone(), version.clone()),
832                vec![digest.clone()],
833            ),
834        ]);
835        let strategy = HashStrategy::collect(HashCollection::All)
836            .with_verification(HashVerification::IfPresent(Arc::new(hashes)));
837
838        assert_eq!(
839            strategy.archive_policy_for_url(&url),
840            ArchiveHashPolicy::All(slice::from_ref(&digest))
841        );
842        for fragment in [
843            "#subdirectory=.",
844            "#subdirectory=./",
845            "#subdirectory=",
846            "#subdirectory=nested/..",
847        ] {
848            let root_url = format!("{url}{fragment}").parse()?;
849            assert_eq!(
850                strategy.archive_policy_for_url(&root_url),
851                ArchiveHashPolicy::All(slice::from_ref(&digest))
852            );
853        }
854        assert_eq!(
855            strategy.archive_policy_for_url(&unknown_url),
856            ArchiveHashPolicy::Generate
857        );
858        assert_eq!(
859            strategy.metadata_policy_for_url(&unknown_url),
860            MetadataHashPolicy {
861                collection: HashCollection::All,
862                validation: HashValidation::None,
863            }
864        );
865        assert_eq!(
866            strategy.metadata_policy_for_url(&url),
867            MetadataHashPolicy {
868                collection: HashCollection::All,
869                validation: HashValidation::All(slice::from_ref(&digest)),
870            }
871        );
872        assert_eq!(
873            strategy.archive_policy_for_package(&name, &version),
874            ArchiveHashPolicy::Any(slice::from_ref(&digest))
875        );
876        assert_eq!(
877            strategy.archive_policy_for_package(&name, &unknown_version),
878            ArchiveHashPolicy::Generate
879        );
880
881        Ok(())
882    }
883
884    #[test]
885    fn required_hashes_take_precedence_over_collection() -> Result<(), Box<dyn std::error::Error>> {
886        let url: SafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
887        let name: PackageName = "anyio".parse()?;
888        let version: Version = "4.0.0".parse()?;
889        let strategy = HashStrategy::collect(HashCollection::All)
890            .with_verification(HashVerification::Required(Arc::default()));
891
892        assert_eq!(
893            strategy.archive_policy_for_url(&url),
894            ArchiveHashPolicy::All(&[])
895        );
896        assert_eq!(
897            strategy.metadata_policy_for_url(&url),
898            MetadataHashPolicy {
899                collection: HashCollection::All,
900                validation: HashValidation::All(&[]),
901            }
902        );
903        assert_eq!(
904            strategy.archive_policy_for_package(&name, &version),
905            ArchiveHashPolicy::Any(&[])
906        );
907        assert!(!strategy.allows_url(&url));
908        assert!(!strategy.allows_package(&name, &version));
909
910        let digest = HashDigest::from_str(
911            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
912        )?;
913        let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([
914            (VersionId::from_url(&url), vec![digest.clone()]),
915            (
916                VersionId::from_registry(name.clone(), version.clone()),
917                vec![HashDigest::from_str(
918                    "md5:420d85e19168705cdf0223621b18831a",
919                )?],
920            ),
921        ])));
922        for strategy in [
923            strategy.clone().with_constraint_hashes(&constraints)?,
924            constraints.with_constraint_hashes(&strategy)?,
925        ] {
926            assert_eq!(
927                strategy.archive_policy_for_url(&url),
928                ArchiveHashPolicy::All(slice::from_ref(&digest))
929            );
930            assert_eq!(
931                strategy.archive_policy_for_package(&name, &version),
932                ArchiveHashPolicy::Any(&[])
933            );
934            assert!(!strategy.allows_package(&name, &version));
935        }
936        Ok(())
937    }
938
939    #[test]
940    fn constraint_hashes_combine_with_locked_hashes() -> Result<(), Box<dyn std::error::Error>> {
941        let name: PackageName = "anyio".parse()?;
942        let version: Version = "4.0.0".parse()?;
943        let local_version: Version = "4.0.0+local".parse()?;
944        let digest = HashDigest::from_str(
945            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
946        )?;
947        let other = HashDigest::from_str(
948            "sha256:f7ed51751b2c2add651e5747c891b47e26d2a21be5d32d9311dfe9692f3e5d7a",
949        )?;
950        let sha512 = HashDigest::from_str(
951            "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
952        )?;
953        let registry = VersionId::from_registry(name.clone(), version);
954        let local_registry = VersionId::from_registry(name, local_version);
955        let archive = VersionId::from_url(&"https://example.com/anyio-4.0.0.tar.gz".parse()?);
956        let path = VersionId::from_path(Path::new("anyio-4.0.0.tar.gz"));
957        for (id, constraint_id, constraint, expected) in [
958            (
959                registry.clone(),
960                registry,
961                digest.clone(),
962                vec![digest.clone()],
963            ),
964            (
965                local_registry,
966                VersionId::from_registry("anyio".parse()?, "4.0.0".parse()?),
967                digest.clone(),
968                vec![digest.clone()],
969            ),
970            (path.clone(), path, digest.clone(), vec![digest.clone()]),
971            (
972                archive.clone(),
973                archive,
974                sha512.clone(),
975                vec![digest.clone(), sha512],
976            ),
977        ] {
978            let locked = HashStrategy::collect(HashCollection::All).with_verification(
979                HashVerification::IfPresent(Arc::new(FxHashMap::from_iter([(
980                    id.clone(),
981                    vec![digest.clone()],
982                )]))),
983            );
984            let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
985                constraint_id.clone(),
986                vec![constraint],
987            )])));
988            let combined = locked.clone().with_constraint_hashes(&constraints)?;
989            assert_eq!(combined.collection(), HashCollection::All);
990            assert_eq!(combined.hashes_for_id(&id), Some(expected.as_slice()));
991
992            let conflicting = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
993                constraint_id,
994                vec![other.clone()],
995            )])));
996            assert!(locked.with_constraint_hashes(&conflicting).is_err());
997        }
998        Ok(())
999    }
1000}