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.")
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            let Some((id, digests)) = Self::requirement_hashes(requirement)? else {
475                continue;
476            };
477            let current = hashes.as_ref().unwrap_or(existing);
478            let current_digests = current.get(&id);
479            let mut merged = current_digests.cloned().unwrap_or_default();
480            merge_digests(&mut merged, &digests, requirement)?;
481
482            if current_digests.map(Vec::as_slice) == Some(merged.as_slice()) {
483                continue;
484            }
485
486            hashes
487                .get_or_insert_with(|| existing.clone())
488                .insert(id, merged);
489        }
490
491        Ok(hashes)
492    }
493
494    /// Extract the archive URL hash target and digests for a requirement, if any.
495    fn requirement_hashes(
496        requirement: &Requirement,
497    ) -> Result<Option<(VersionId, Vec<HashDigest>)>, HashStrategyError> {
498        let Some(hashes) = requirement.hashes()? else {
499            return Ok(None);
500        };
501        let mut digests = HashDigests::from(hashes).to_vec();
502        if digests.is_empty() {
503            return Ok(None);
504        }
505        digests.sort_unstable();
506        let Some(id) = Self::pin(requirement) else {
507            return Ok(None);
508        };
509        Ok(Some((id, digests)))
510    }
511
512    /// Pin a [`Requirement`] to a [`VersionId`], if possible.
513    fn pin(requirement: &Requirement) -> Option<VersionId> {
514        match &requirement.source {
515            RequirementSource::Registry { specifier, .. } => {
516                // Must be a single specifier.
517                let [specifier] = specifier.as_ref() else {
518                    return None;
519                };
520
521                // Must be pinned to a specific version.
522                let is_pinned =
523                    matches!(specifier.operator(), Operator::Equal | Operator::ExactEqual);
524                if !is_pinned {
525                    return None;
526                }
527
528                Some(VersionId::from_registry(
529                    requirement.name.clone(),
530                    specifier.version().clone(),
531                ))
532            }
533            RequirementSource::Url {
534                location,
535                subdirectory,
536                ..
537            } => Some(VersionId::from_archive(
538                location.as_url().clone(),
539                subdirectory.clone().map(Path::into_path_buf),
540            )),
541            RequirementSource::GitDirectory {
542                git, subdirectory, ..
543            } => Some(VersionId::from_git(git, subdirectory.as_deref())),
544            RequirementSource::GitPath {
545                git, install_path, ..
546            } => Some(VersionId::from_git(git, Some(install_path))),
547            RequirementSource::Path { install_path, .. } => {
548                Some(VersionId::from_path(install_path))
549            }
550            RequirementSource::Directory { install_path, .. } => {
551                Some(VersionId::from_directory(install_path))
552            }
553        }
554    }
555}
556
557fn hash_validation<'a>(id: &VersionId, digests: &'a [HashDigest]) -> HashValidation<'a> {
558    match id {
559        VersionId::NameVersion { .. } => HashValidation::Any(digests),
560        VersionId::ArchiveUrl { .. }
561        | VersionId::Git { .. }
562        | VersionId::Path { .. }
563        | VersionId::Directory { .. }
564        | VersionId::Unknown { .. } => HashValidation::All(digests),
565    }
566}
567
568/// Combine hashes for a requirement and an applicable constraint.
569fn combine_constraint_hashes(
570    id: &VersionId,
571    mut digests: Vec<HashDigest>,
572    constraint: &[HashDigest],
573    requirement: impl Display,
574    mode: HashCheckingMode,
575) -> Result<Vec<HashDigest>, HashStrategyError> {
576    if digests.is_empty() {
577        // If there are _only_ hashes on the constraints, use them.
578        return Ok(constraint.to_vec());
579    }
580    match id {
581        VersionId::NameVersion(..) => {
582            // If there are constraint and requirement hashes, take the intersection.
583            digests.retain(|digest| constraint.contains(digest));
584            if digests.is_empty() {
585                return Err(HashStrategyError::NoIntersection(
586                    requirement.to_string(),
587                    mode,
588                ));
589            }
590        }
591        VersionId::ArchiveUrl { .. }
592        | VersionId::Git { .. }
593        | VersionId::Path(..)
594        | VersionId::Directory(..)
595        | VersionId::Unknown(..) => {
596            merge_digests(&mut digests, constraint, requirement)?;
597        }
598    }
599    Ok(digests)
600}
601
602/// Parse requirement-file hashes and combine them with any URL-fragment hashes.
603fn parse_declared_hashes(
604    hashes: &[String],
605    fragment_hashes: Result<Option<Hashes>, HashError>,
606    requirement: impl Display,
607    mode: HashCheckingMode,
608) -> Result<(Vec<HashDigest>, Option<HashAlgorithm>), HashStrategyError> {
609    let mut digests = hashes
610        .iter()
611        .map(|digest| HashDigest::from_str(digest))
612        .collect::<Result<Vec<_>, _>>()?;
613    if let Some(fragment_hashes) = fragment_hashes? {
614        merge_digests(
615            &mut digests,
616            HashDigests::from(fragment_hashes).iter(),
617            requirement,
618        )?;
619    }
620    let rejected = if mode.is_require() {
621        let rejected = digests
622            .iter()
623            .find(|digest| !satisfies_require_hashes(digest))
624            .map(HashDigest::algorithm);
625        digests.retain(satisfies_require_hashes);
626        rejected
627    } else {
628        None
629    };
630    Ok((digests, rejected))
631}
632
633/// Merge repeated hashes for a requirement or constraint into the hash map.
634fn merge_hashes(
635    hashes: &mut FxHashMap<VersionId, Vec<HashDigest>>,
636    id: VersionId,
637    incoming: Vec<HashDigest>,
638    requirement: impl Display,
639) -> Result<(), HashStrategyError> {
640    if incoming.is_empty() {
641        return Ok(());
642    }
643
644    if !matches!(&id, VersionId::ArchiveUrl { .. }) {
645        hashes.insert(id, incoming);
646        return Ok(());
647    }
648
649    if let Some(existing) = hashes.get_mut(&id) {
650        return merge_digests(existing, &incoming, requirement);
651    }
652
653    let mut merged = Vec::new();
654    merge_digests(&mut merged, &incoming, requirement)?;
655    hashes.insert(id, merged);
656    Ok(())
657}
658
659/// Merge `incoming` digests into `existing`.
660///
661/// Exact duplicates are ignored. Digests for different algorithms are accumulated. If the
662/// same algorithm appears with two different values, returns
663/// [`HashStrategyError::ConflictingArchiveUrlHashes`].
664fn merge_digests<'a>(
665    existing: &mut Vec<HashDigest>,
666    incoming: impl IntoIterator<Item = &'a HashDigest>,
667    requirement: impl Display,
668) -> Result<(), HashStrategyError> {
669    for digest in incoming {
670        match existing
671            .iter()
672            .find(|candidate| candidate.algorithm() == digest.algorithm())
673        {
674            Some(candidate) if candidate == digest => {}
675            Some(conflict) => {
676                return Err(HashStrategyError::ConflictingArchiveUrlHashes(
677                    requirement.to_string(),
678                    conflict.clone(),
679                    digest.clone(),
680                ));
681            }
682            None => existing.push(digest.clone()),
683        }
684    }
685    existing.sort_unstable();
686
687    Ok(())
688}
689
690#[derive(thiserror::Error, Debug)]
691pub enum HashStrategyError {
692    #[error(transparent)]
693    Hash(#[from] HashError),
694    #[error("Conflicting archive URL hashes for `{0}`: `{1}` conflicts with `{2}`")]
695    ConflictingArchiveUrlHashes(String, HashDigest, HashDigest),
696    #[error(
697        "In `{1}` mode, all requirements must have their versions pinned with `==`, but found: {0}"
698    )]
699    UnpinnedRequirement(String, HashCheckingMode),
700    #[error(
701        "`{1}` hashes are insecure and cannot be used with `{2}` but no other hashes are available for: {0}"
702    )]
703    InsecureHashAlgorithm(String, HashAlgorithm, HashCheckingMode),
704    #[error("In `{1}` mode, all requirements must have a hash, but none were provided for: {0}")]
705    MissingHashes(String, HashCheckingMode),
706    #[error(
707        "In `{1}` mode, all requirements must have a hash, but there were no overlapping hashes between the requirements and constraints for: {0}"
708    )]
709    NoIntersection(String, HashCheckingMode),
710}
711
712#[cfg(test)]
713mod tests {
714    use std::path::Path;
715    use std::slice;
716    use std::str::FromStr;
717    use std::sync::Arc;
718
719    use rustc_hash::FxHashMap;
720    use uv_configuration::HashCheckingMode;
721    use uv_distribution_filename::DistExtension;
722    use uv_distribution_types::{
723        ArchiveHashPolicy, HashCollection, HashValidation, MetadataHashPolicy, Requirement,
724        RequirementScope, RequirementSource, UnresolvedRequirement, VersionId,
725    };
726    use uv_normalize::PackageName;
727    use uv_pep440::Version;
728    use uv_pypi_types::HashDigest;
729    use uv_redacted::SafeUrl;
730    use uv_redacted::policy::Raw;
731
732    use super::{HashStrategy, HashVerification};
733
734    fn requirement(url: &str) -> Requirement {
735        Requirement {
736            name: "anyio".parse().unwrap(),
737            extras: Box::default(),
738            groups: Box::default(),
739            marker: "python_version >= '3.8'".parse().unwrap(),
740            source: RequirementSource::Url {
741                location: "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl"
742                    .parse::<SafeUrl>()
743                    .unwrap()
744                    .with_policy(Raw),
745                subdirectory: None,
746                ext: DistExtension::Wheel,
747                url: url.parse().unwrap(),
748            },
749            scope: RequirementScope::Global,
750            origin: None,
751        }
752    }
753
754    #[test]
755    fn from_requirements_merges_direct_url_hashes_across_fragments() {
756        let first = UnresolvedRequirement::Named(requirement(
757            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha256=CFDB2B588B9FC25EDE96D8DB56ED50848B0B649DCA3DD1DF0B11F683BB9E0B5F",
758        ));
759        let second = UnresolvedRequirement::Named(requirement(
760            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha512=f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
761        ));
762
763        let hasher = HashStrategy::from_requirements(
764            [(&first, &[][..]), (&second, &[][..])].into_iter(),
765            std::iter::empty(),
766            None,
767            HashCheckingMode::Require,
768        )
769        .unwrap();
770
771        let mut expected = vec![
772            HashDigest::from_str(
773                "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
774            )
775            .unwrap(),
776            HashDigest::from_str(
777                "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
778            )
779            .unwrap(),
780        ];
781        expected.sort_unstable();
782
783        for requirement in [&first, &second] {
784            let UnresolvedRequirement::Named(requirement) = requirement else {
785                panic!("expected named requirement");
786            };
787            let RequirementSource::Url { url, .. } = &requirement.source else {
788                panic!("expected direct URL requirement");
789            };
790            assert_eq!(
791                hasher.archive_policy_for_url(url),
792                ArchiveHashPolicy::All(expected.as_slice())
793            );
794        }
795    }
796
797    #[test]
798    fn generate_and_verify_validates_known_hashes_and_generates_unknown_hashes()
799    -> Result<(), Box<dyn std::error::Error>> {
800        let url: SafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
801        let unknown_url: SafeUrl = "https://example.com/anyio-4.1.0.tar.gz".parse()?;
802        let name: PackageName = "anyio".parse()?;
803        let version: Version = "4.0.0".parse()?;
804        let unknown_version: Version = "4.1.0".parse()?;
805        let digest = HashDigest::from_str(
806            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
807        )?;
808        let hashes = FxHashMap::from_iter([
809            (VersionId::from_url(&url), vec![digest.clone()]),
810            (
811                VersionId::from_registry(name.clone(), version.clone()),
812                vec![digest.clone()],
813            ),
814        ]);
815        let strategy = HashStrategy::collect(HashCollection::All)
816            .with_verification(HashVerification::IfPresent(Arc::new(hashes)));
817
818        assert_eq!(
819            strategy.archive_policy_for_url(&url),
820            ArchiveHashPolicy::All(slice::from_ref(&digest))
821        );
822        for fragment in [
823            "#subdirectory=.",
824            "#subdirectory=./",
825            "#subdirectory=",
826            "#subdirectory=nested/..",
827        ] {
828            let root_url = format!("{url}{fragment}").parse()?;
829            assert_eq!(
830                strategy.archive_policy_for_url(&root_url),
831                ArchiveHashPolicy::All(slice::from_ref(&digest))
832            );
833        }
834        assert_eq!(
835            strategy.archive_policy_for_url(&unknown_url),
836            ArchiveHashPolicy::Generate
837        );
838        assert_eq!(
839            strategy.metadata_policy_for_url(&unknown_url),
840            MetadataHashPolicy {
841                collection: HashCollection::All,
842                validation: HashValidation::None,
843            }
844        );
845        assert_eq!(
846            strategy.metadata_policy_for_url(&url),
847            MetadataHashPolicy {
848                collection: HashCollection::All,
849                validation: HashValidation::All(slice::from_ref(&digest)),
850            }
851        );
852        assert_eq!(
853            strategy.archive_policy_for_package(&name, &version),
854            ArchiveHashPolicy::Any(slice::from_ref(&digest))
855        );
856        assert_eq!(
857            strategy.archive_policy_for_package(&name, &unknown_version),
858            ArchiveHashPolicy::Generate
859        );
860
861        Ok(())
862    }
863
864    #[test]
865    fn required_hashes_take_precedence_over_collection() -> Result<(), Box<dyn std::error::Error>> {
866        let url: SafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
867        let name: PackageName = "anyio".parse()?;
868        let version: Version = "4.0.0".parse()?;
869        let strategy = HashStrategy::collect(HashCollection::All)
870            .with_verification(HashVerification::Required(Arc::default()));
871
872        assert_eq!(
873            strategy.archive_policy_for_url(&url),
874            ArchiveHashPolicy::All(&[])
875        );
876        assert_eq!(
877            strategy.metadata_policy_for_url(&url),
878            MetadataHashPolicy {
879                collection: HashCollection::All,
880                validation: HashValidation::All(&[]),
881            }
882        );
883        assert_eq!(
884            strategy.archive_policy_for_package(&name, &version),
885            ArchiveHashPolicy::Any(&[])
886        );
887        assert!(!strategy.allows_url(&url));
888        assert!(!strategy.allows_package(&name, &version));
889
890        let digest = HashDigest::from_str(
891            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
892        )?;
893        let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([
894            (VersionId::from_url(&url), vec![digest.clone()]),
895            (
896                VersionId::from_registry(name.clone(), version.clone()),
897                vec![HashDigest::from_str(
898                    "md5:420d85e19168705cdf0223621b18831a",
899                )?],
900            ),
901        ])));
902        for strategy in [
903            strategy.clone().with_constraint_hashes(&constraints)?,
904            constraints.with_constraint_hashes(&strategy)?,
905        ] {
906            assert_eq!(
907                strategy.archive_policy_for_url(&url),
908                ArchiveHashPolicy::All(slice::from_ref(&digest))
909            );
910            assert_eq!(
911                strategy.archive_policy_for_package(&name, &version),
912                ArchiveHashPolicy::Any(&[])
913            );
914            assert!(!strategy.allows_package(&name, &version));
915        }
916        Ok(())
917    }
918
919    #[test]
920    fn constraint_hashes_combine_with_locked_hashes() -> Result<(), Box<dyn std::error::Error>> {
921        let name: PackageName = "anyio".parse()?;
922        let version: Version = "4.0.0".parse()?;
923        let local_version: Version = "4.0.0+local".parse()?;
924        let digest = HashDigest::from_str(
925            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
926        )?;
927        let other = HashDigest::from_str(
928            "sha256:f7ed51751b2c2add651e5747c891b47e26d2a21be5d32d9311dfe9692f3e5d7a",
929        )?;
930        let sha512 = HashDigest::from_str(
931            "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
932        )?;
933        let registry = VersionId::from_registry(name.clone(), version);
934        let local_registry = VersionId::from_registry(name, local_version);
935        let archive = VersionId::from_url(&"https://example.com/anyio-4.0.0.tar.gz".parse()?);
936        let path = VersionId::from_path(Path::new("anyio-4.0.0.tar.gz"));
937        for (id, constraint_id, constraint, expected) in [
938            (
939                registry.clone(),
940                registry,
941                digest.clone(),
942                vec![digest.clone()],
943            ),
944            (
945                local_registry,
946                VersionId::from_registry("anyio".parse()?, "4.0.0".parse()?),
947                digest.clone(),
948                vec![digest.clone()],
949            ),
950            (path.clone(), path, digest.clone(), vec![digest.clone()]),
951            (
952                archive.clone(),
953                archive,
954                sha512.clone(),
955                vec![digest.clone(), sha512],
956            ),
957        ] {
958            let locked = HashStrategy::collect(HashCollection::All).with_verification(
959                HashVerification::IfPresent(Arc::new(FxHashMap::from_iter([(
960                    id.clone(),
961                    vec![digest.clone()],
962                )]))),
963            );
964            let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
965                constraint_id.clone(),
966                vec![constraint],
967            )])));
968            let combined = locked.clone().with_constraint_hashes(&constraints)?;
969            assert_eq!(combined.collection(), HashCollection::All);
970            assert_eq!(combined.hashes_for_id(&id), Some(expected.as_slice()));
971
972            let conflicting = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
973                constraint_id,
974                vec![other.clone()],
975            )])));
976            assert!(locked.with_constraint_hashes(&conflicting).is_err());
977        }
978        Ok(())
979    }
980}