uv-types 0.0.86

This is an internal component crate of uv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
use std::fmt::Display;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

use rustc_hash::FxHashMap;

use uv_configuration::{Constraints, HashCheckingMode};
use uv_distribution_types::{
    ArchiveHashPolicy, DistributionMetadata, HashCollection, HashValidation, MetadataHashPolicy,
    Name, Requirement, RequirementSource, Resolution, UnresolvedRequirement, VersionId,
};
use uv_normalize::PackageName;
use uv_pep440::{Operator, Version};
use uv_pypi_types::{HashAlgorithm, HashDigest, HashDigests, HashError, ResolverMarkerEnvironment};
use uv_redacted::DisplaySafeUrl;

/// Hash collection and verification policies for a resolution.
///
/// Verification takes precedence for distributions with trusted hashes. The collection policy
/// applies to the remaining distributions.
#[derive(Debug, Default, Clone)]
pub struct HashStrategy {
    collection: HashCollection,
    verification: HashVerification,
}

/// The trusted hashes to enforce when retrieving distributions.
#[derive(Debug, Default, Clone)]
pub enum HashVerification {
    /// Hashes do not need to be validated.
    #[default]
    None,
    /// Validate known hashes, without requiring hashes for other distributions.
    IfPresent(Arc<FxHashMap<VersionId, Vec<HashDigest>>>),
    /// Every distribution must have a matching trusted hash.
    Required(Arc<FxHashMap<VersionId, Vec<HashDigest>>>),
}

impl HashStrategy {
    /// Collect declared hashes for resolution, computing missing hashes according to the policy.
    pub fn collect(collection: HashCollection) -> Self {
        Self {
            collection,
            ..Self::default()
        }
    }

    /// Validate hashes when present.
    pub fn verify(hashes: Arc<FxHashMap<VersionId, Vec<HashDigest>>>) -> Self {
        Self::default().with_verification(HashVerification::IfPresent(hashes))
    }

    /// Require a matching trusted hash for every distribution.
    fn require(hashes: Arc<FxHashMap<VersionId, Vec<HashDigest>>>) -> Self {
        Self::default().with_verification(HashVerification::Required(hashes))
    }

    /// Set verification independently of hash collection.
    #[must_use]
    pub fn with_verification(mut self, verification: HashVerification) -> Self {
        self.verification = verification;
        self
    }

    /// Apply constraint hashes using the same rules as [`Self::from_requirements`].
    ///
    /// Preserve hash collection and require hashes if either strategy requires them. Constraints
    /// for identities absent from this strategy remain available for newly resolved dependencies.
    pub fn with_constraint_hashes(mut self, constraints: &Self) -> Result<Self, HashStrategyError> {
        let (requirement_hashes, mode) = match &self.verification {
            HashVerification::None => {
                self.verification = constraints.verification.clone();
                return Ok(self);
            }
            HashVerification::IfPresent(hashes) => {
                let mode = match &constraints.verification {
                    HashVerification::Required(_) => HashCheckingMode::Require,
                    HashVerification::None | HashVerification::IfPresent(_) => {
                        HashCheckingMode::Verify
                    }
                };
                (hashes, mode)
            }
            HashVerification::Required(hashes) => (hashes, HashCheckingMode::Require),
        };

        let mut constraints = constraints.clone();
        let constraint_hashes = match &mut constraints.verification {
            HashVerification::None => return Ok(self),
            HashVerification::IfPresent(hashes) | HashVerification::Required(hashes) => {
                Arc::make_mut(hashes)
            }
        };
        if mode.is_require() {
            constraint_hashes.retain(|_, digests| {
                digests.retain(|digest| digest.algorithm() != HashAlgorithm::Md5);
                !digests.is_empty()
            });
        }
        let mut hashes = constraint_hashes.clone();
        for (id, digests) in requirement_hashes.iter() {
            let mut digests = digests.clone();
            if mode.is_require() {
                digests.retain(|digest| digest.algorithm() != HashAlgorithm::Md5);
            }
            let digests = if let Some(constraint) = constraints.hashes_for_id(id) {
                combine_constraint_hashes(id, digests, constraint, id, mode)?
            } else {
                digests
            };
            if !digests.is_empty() {
                hashes.insert(id.clone(), digests);
            }
        }
        self.verification = match mode {
            HashCheckingMode::Verify => HashVerification::IfPresent(Arc::new(hashes)),
            HashCheckingMode::Require => HashVerification::Required(Arc::new(hashes)),
        };
        Ok(self)
    }

    /// Return the hash collection policy.
    pub fn collection(&self) -> HashCollection {
        self.collection
    }

    /// Return the hash verification policy.
    pub fn verification(&self) -> &HashVerification {
        &self.verification
    }

    /// Return the [`ArchiveHashPolicy`] for the given distribution.
    pub fn archive_policy<T: DistributionMetadata>(
        &self,
        distribution: &T,
    ) -> ArchiveHashPolicy<'_> {
        self.archive_policy_for_id(|| distribution.version_id())
    }

    /// Return the [`MetadataHashPolicy`] for retrieving the given distribution's metadata.
    pub fn metadata_policy<T: DistributionMetadata>(
        &self,
        distribution: &T,
    ) -> MetadataHashPolicy<'_> {
        MetadataHashPolicy {
            collection: self.collection,
            validation: self.validation_for_id(|| distribution.version_id()),
        }
    }

    /// Return the [`ArchiveHashPolicy`] for the given registry-based package.
    pub fn archive_policy_for_package(
        &self,
        name: &PackageName,
        version: &Version,
    ) -> ArchiveHashPolicy<'_> {
        self.archive_policy_for_id(|| VersionId::from_registry(name.clone(), version.clone()))
    }

    /// Return the [`ArchiveHashPolicy`] for the given direct URL package.
    ///
    /// A direct URL identifies a single concrete artifact, so every provided digest must match.
    pub fn archive_policy_for_url(&self, url: &DisplaySafeUrl) -> ArchiveHashPolicy<'_> {
        self.archive_policy_for_id(|| VersionId::from_url(url))
    }

    /// Return the [`MetadataHashPolicy`] for a URL whose package name is not yet known.
    pub fn metadata_policy_for_url(&self, url: &DisplaySafeUrl) -> MetadataHashPolicy<'_> {
        MetadataHashPolicy {
            collection: self.collection,
            validation: self.validation_for_id(|| VersionId::from_url(url)),
        }
    }

    /// Return the archive hash policy for a distribution identity.
    fn archive_policy_for_id(&self, id: impl FnOnce() -> VersionId) -> ArchiveHashPolicy<'_> {
        let validation = self.validation_for_id(id);
        match validation {
            HashValidation::None => match self.collection {
                HashCollection::None => ArchiveHashPolicy::None,
                HashCollection::Url | HashCollection::All => ArchiveHashPolicy::Generate,
            },
            HashValidation::Any(_) | HashValidation::All(_) => validation.into(),
        }
    }

    /// Construct an identity only when verification requires a lookup.
    fn validation_for_id(&self, id: impl FnOnce() -> VersionId) -> HashValidation<'_> {
        match &self.verification {
            HashVerification::IfPresent(_) => {
                let id = id();
                if let Some(hashes) = self.hashes_for_id(&id) {
                    return hash_validation(&id, hashes);
                }
            }
            HashVerification::Required(hashes) => {
                let id = id();
                return hash_validation(
                    &id,
                    hashes.get(&id).map(Vec::as_slice).unwrap_or_default(),
                );
            }
            HashVerification::None => {}
        }
        HashValidation::None
    }

    /// Look up supplied hashes, including public-version pins in verification mode.
    fn hashes_for_id(&self, id: &VersionId) -> Option<&[HashDigest]> {
        match &self.verification {
            HashVerification::None => None,
            HashVerification::IfPresent(hashes) => hashes
                .get(id)
                .or_else(|| {
                    // `==1.0.0` can also select `1.0.0+local`. If the local version has no hash
                    // of its own, check it against the hash for `1.0.0`.
                    if let VersionId::NameVersion(name, version) = id
                        && version.is_local()
                    {
                        hashes.get(&VersionId::from_registry(
                            name.clone(),
                            version.clone().without_local(),
                        ))
                    } else {
                        None
                    }
                })
                .map(Vec::as_slice),
            HashVerification::Required(hashes) => hashes.get(id).map(Vec::as_slice),
        }
    }

    /// Returns `true` if the given registry-based package is allowed.
    pub fn allows_package(&self, name: &PackageName, version: &Version) -> bool {
        match &self.verification {
            HashVerification::Required(hashes) => {
                hashes.contains_key(&VersionId::from_registry(name.clone(), version.clone()))
            }
            HashVerification::None | HashVerification::IfPresent(_) => true,
        }
    }

    /// Returns `true` if the given direct URL package is allowed.
    pub fn allows_url(&self, url: &DisplaySafeUrl) -> bool {
        match &self.verification {
            HashVerification::Required(hashes) => hashes.contains_key(&VersionId::from_url(url)),
            HashVerification::None | HashVerification::IfPresent(_) => true,
        }
    }

    /// Return a [`HashStrategy`] augmented with archive URL hashes discovered in additional
    /// requirements after the initial command-line parse.
    pub fn augment_with_requirements<'a>(
        mut self,
        requirements: impl Iterator<Item = &'a Requirement>,
    ) -> Result<Self, HashStrategyError> {
        match &mut self.verification {
            HashVerification::None => {}
            HashVerification::IfPresent(existing) | HashVerification::Required(existing) => {
                if let Some(hashes) = Self::augment_hashes(existing, requirements)? {
                    *existing = Arc::new(hashes);
                }
            }
        }
        Ok(self)
    }

    /// Return a [`HashStrategy`] augmented with archive URL hashes discovered in distribution
    /// metadata.
    ///
    /// Required-hash verification is intentionally a closed set. In that mode, distribution
    /// untrusted metadata cannot authorize a requirement that was absent from the input hash set.
    /// Explicit requirements, such as `build-system.requires` and user-provided metadata, can still
    /// contribute hashes via [`Self::augment_with_requirements`].
    pub fn augment_with_metadata_requirements<'a>(
        self,
        requirements: impl Iterator<Item = &'a Requirement>,
    ) -> Result<Self, HashStrategyError> {
        if matches!(&self.verification, HashVerification::Required(_)) {
            return Ok(self);
        }
        self.augment_with_requirements(requirements)
    }

    /// Collect hashes from [`UnresolvedRequirement`] entries and constraints.
    ///
    /// For duplicate registry pins and local files, the last nonempty constraint hash list wins.
    /// Remote archive URLs combine hashes across algorithms and reject conflicting digests for
    /// the same algorithm. Registry pins accept any allowed digest; direct URLs must match all
    /// supplied digests. When requirements and constraints both supply hashes, only their shared
    /// hashes are allowed, except for remote archive URLs, whose hashes are combined instead.
    ///
    /// When the environment is not given, this treats all marker expressions
    /// that reference the environment as true. In other words, it does
    /// environment independent expression evaluation. (Which in turn devolves
    /// to "only evaluate marker expressions that reference an extra name.")
    pub fn from_requirements<'a>(
        requirements: impl Iterator<Item = (&'a UnresolvedRequirement, &'a [String])>,
        constraints: impl Iterator<Item = (&'a Requirement, &'a [String])>,
        marker_env: Option<&ResolverMarkerEnvironment>,
        mode: HashCheckingMode,
    ) -> Result<Self, HashStrategyError> {
        let mut constraint_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();

        // First, index the constraints by name.
        for (requirement, digests) in constraints {
            if !requirement
                .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[])
            {
                continue;
            }

            // Every constraint must be a pinned version.
            let Some(id) = Self::pin(requirement) else {
                if mode.is_require() {
                    return Err(HashStrategyError::UnpinnedRequirement(
                        requirement.to_string(),
                        mode,
                    ));
                }
                continue;
            };

            // Parse the hashes provided directly on the requirement, then merge in any hashes from
            // the URL fragment.
            let mut digests = digests
                .iter()
                .map(|digest| HashDigest::from_str(digest))
                .collect::<Result<Vec<_>, _>>()?;
            if let Some(fragment_hashes) = requirement.hashes()? {
                let fragment_hashes = HashDigests::from(fragment_hashes);
                merge_digests(&mut digests, fragment_hashes.iter(), requirement)?;
            }

            if mode.is_require() {
                digests.retain(|digest| digest.algorithm() != HashAlgorithm::Md5);
            }

            if digests.is_empty() {
                continue;
            }

            merge_hashes(&mut constraint_hashes, id, digests, requirement)?;
        }

        // For each requirement, map from hash identity to allowed hashes.
        let mut requirement_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();
        for (requirement, digests) in requirements {
            if !requirement
                .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[])
            {
                continue;
            }

            // Every requirement must be either a pinned version or a direct URL.
            let id = match &requirement {
                UnresolvedRequirement::Named(requirement) => {
                    if let Some(id) = Self::pin(requirement) {
                        id
                    } else {
                        if mode.is_require() {
                            return Err(HashStrategyError::UnpinnedRequirement(
                                requirement.to_string(),
                                mode,
                            ));
                        }
                        continue;
                    }
                }
                UnresolvedRequirement::Unnamed(requirement) => {
                    // Direct URLs are always allowed.
                    VersionId::from_parsed_url(requirement.url.parsed_url.clone())
                }
            };

            // Parse the hashes provided directly on the requirement, then merge in any hashes from
            // the URL fragment.
            let mut digests = digests
                .iter()
                .map(|digest| HashDigest::from_str(digest))
                .collect::<Result<Vec<_>, _>>()?;
            if let Some(fragment_hashes) = requirement.hashes()? {
                let fragment_hashes = HashDigests::from(fragment_hashes);
                merge_digests(&mut digests, fragment_hashes.iter(), requirement)?;
            }

            let has_md5 = mode.is_require()
                && digests
                    .iter()
                    .any(|digest| digest.algorithm() == HashAlgorithm::Md5);
            if mode.is_require() {
                digests.retain(|digest| digest.algorithm() != HashAlgorithm::Md5);
            }

            let digests = if let Some(constraint) = constraint_hashes.remove(&id) {
                combine_constraint_hashes(&id, digests, &constraint, requirement, mode)?
            } else {
                digests
            };

            // Under `--require-hashes`, every requirement must include a hash.
            if digests.is_empty() {
                if mode.is_require() {
                    if has_md5 {
                        return Err(HashStrategyError::InsecureHashAlgorithm(
                            requirement.to_string(),
                            HashAlgorithm::Md5,
                            mode,
                        ));
                    }
                    return Err(HashStrategyError::MissingHashes(
                        requirement.to_string(),
                        mode,
                    ));
                }
                continue;
            }

            merge_hashes(&mut requirement_hashes, id, digests, requirement)?;
        }

        // Merge the hashes, preferring requirements over constraints, since overlapping
        // requirements were already merged.
        let hashes: FxHashMap<VersionId, Vec<HashDigest>> = constraint_hashes
            .into_iter()
            .chain(requirement_hashes)
            .collect();
        match mode {
            HashCheckingMode::Verify => Ok(Self::verify(Arc::new(hashes))),
            HashCheckingMode::Require => Ok(Self::require(Arc::new(hashes))),
        }
    }

    /// Collect hashes from [`Constraints`] using the same handling as regular constraints in
    /// [`Self::from_requirements`], preserving declaration order.
    pub fn from_constraints(
        constraints: &Constraints,
        marker_env: Option<&ResolverMarkerEnvironment>,
        mode: HashCheckingMode,
    ) -> Result<Self, HashStrategyError> {
        Self::from_requirements(
            std::iter::empty(),
            constraints
                .specifications()
                .map(|entry| (&entry.requirement, entry.hashes.as_slice())),
            marker_env,
            mode,
        )
    }

    /// Read the required hashes from a [`Resolution`].
    pub fn from_resolution(
        resolution: &Resolution,
        mode: HashCheckingMode,
    ) -> Result<Self, HashStrategyError> {
        let mut hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default();

        for (dist, digests) in resolution.hashes() {
            if digests.is_empty() {
                // Under `--require-hashes`, every requirement must include a hash.
                if mode.is_require() {
                    return Err(HashStrategyError::MissingHashes(
                        dist.name().to_string(),
                        mode,
                    ));
                }
                continue;
            }
            hashes.insert(dist.version_id(), digests.to_vec());
        }

        match mode {
            HashCheckingMode::Verify => Ok(Self::verify(Arc::new(hashes))),
            HashCheckingMode::Require => Ok(Self::require(Arc::new(hashes))),
        }
    }

    /// Augment an existing set of hashes with archive URL hashes discovered in additional
    /// requirements.
    ///
    /// Archive URL requirements are keyed by a [`VersionId`] so that requirements that refer to
    /// the same underlying archive but differ only in hash fragments are merged onto the same
    /// digest set.
    ///
    /// Returns `Ok(None)` if no new hashes were added or updated.
    fn augment_hashes<'a>(
        existing: &FxHashMap<VersionId, Vec<HashDigest>>,
        requirements: impl Iterator<Item = &'a Requirement>,
    ) -> Result<Option<FxHashMap<VersionId, Vec<HashDigest>>>, HashStrategyError> {
        let mut hashes = None;

        for requirement in requirements {
            let Some((id, digests)) = Self::requirement_hashes(requirement)? else {
                continue;
            };
            let current = hashes.as_ref().unwrap_or(existing);
            let current_digests = current.get(&id);
            let mut merged = current_digests.cloned().unwrap_or_default();
            merge_digests(&mut merged, &digests, requirement)?;

            if current_digests.map(Vec::as_slice) == Some(merged.as_slice()) {
                continue;
            }

            hashes
                .get_or_insert_with(|| existing.clone())
                .insert(id, merged);
        }

        Ok(hashes)
    }

    /// Extract the archive URL hash target and digests for a requirement, if any.
    fn requirement_hashes(
        requirement: &Requirement,
    ) -> Result<Option<(VersionId, Vec<HashDigest>)>, HashStrategyError> {
        let Some(hashes) = requirement.hashes()? else {
            return Ok(None);
        };
        let mut digests = HashDigests::from(hashes).to_vec();
        if digests.is_empty() {
            return Ok(None);
        }
        digests.sort_unstable();
        let Some(id) = Self::pin(requirement) else {
            return Ok(None);
        };
        Ok(Some((id, digests)))
    }

    /// Pin a [`Requirement`] to a [`VersionId`], if possible.
    fn pin(requirement: &Requirement) -> Option<VersionId> {
        match &requirement.source {
            RequirementSource::Registry { specifier, .. } => {
                // Must be a single specifier.
                let [specifier] = specifier.as_ref() else {
                    return None;
                };

                // Must be pinned to a specific version.
                let is_pinned =
                    matches!(specifier.operator(), Operator::Equal | Operator::ExactEqual);
                if !is_pinned {
                    return None;
                }

                Some(VersionId::from_registry(
                    requirement.name.clone(),
                    specifier.version().clone(),
                ))
            }
            RequirementSource::Url {
                location,
                subdirectory,
                ..
            } => Some(VersionId::from_archive(
                location.clone(),
                subdirectory.clone().map(Path::into_path_buf),
            )),
            RequirementSource::GitDirectory {
                git, subdirectory, ..
            } => Some(VersionId::from_git(git, subdirectory.as_deref())),
            RequirementSource::GitPath {
                git, install_path, ..
            } => Some(VersionId::from_git(git, Some(install_path))),
            RequirementSource::Path { install_path, .. } => {
                Some(VersionId::from_path(install_path))
            }
            RequirementSource::Directory { install_path, .. } => {
                Some(VersionId::from_directory(install_path))
            }
        }
    }
}

fn hash_validation<'a>(id: &VersionId, digests: &'a [HashDigest]) -> HashValidation<'a> {
    match id {
        VersionId::NameVersion { .. } => HashValidation::Any(digests),
        VersionId::ArchiveUrl { .. }
        | VersionId::Git { .. }
        | VersionId::Path { .. }
        | VersionId::Directory { .. }
        | VersionId::Unknown { .. } => HashValidation::All(digests),
    }
}

/// Combine hashes for a requirement and an applicable constraint.
fn combine_constraint_hashes(
    id: &VersionId,
    mut digests: Vec<HashDigest>,
    constraint: &[HashDigest],
    requirement: impl Display,
    mode: HashCheckingMode,
) -> Result<Vec<HashDigest>, HashStrategyError> {
    if digests.is_empty() {
        // If there are _only_ hashes on the constraints, use them.
        return Ok(constraint.to_vec());
    }
    match id {
        VersionId::ArchiveUrl { .. } => {
            merge_digests(&mut digests, constraint, requirement)?;
        }
        VersionId::NameVersion(..)
        | VersionId::Git { .. }
        | VersionId::Path(..)
        | VersionId::Directory(..)
        | VersionId::Unknown(..) => {
            // If there are constraint and requirement hashes, take the intersection.
            digests.retain(|digest| constraint.contains(digest));
            if digests.is_empty() {
                return Err(HashStrategyError::NoIntersection(
                    requirement.to_string(),
                    mode,
                ));
            }
        }
    }
    Ok(digests)
}

/// Merge repeated hashes for a requirement or constraint into the hash map.
fn merge_hashes(
    hashes: &mut FxHashMap<VersionId, Vec<HashDigest>>,
    id: VersionId,
    incoming: Vec<HashDigest>,
    requirement: impl Display,
) -> Result<(), HashStrategyError> {
    if incoming.is_empty() {
        return Ok(());
    }

    if !matches!(&id, VersionId::ArchiveUrl { .. }) {
        hashes.insert(id, incoming);
        return Ok(());
    }

    if let Some(existing) = hashes.get_mut(&id) {
        return merge_digests(existing, &incoming, requirement);
    }

    let mut merged = Vec::new();
    merge_digests(&mut merged, &incoming, requirement)?;
    hashes.insert(id, merged);
    Ok(())
}

/// Merge `incoming` digests into `existing`.
///
/// Exact duplicates are ignored. Digests for different algorithms are accumulated. If the
/// same algorithm appears with two different values, returns
/// [`HashStrategyError::ConflictingArchiveUrlHashes`].
fn merge_digests<'a>(
    existing: &mut Vec<HashDigest>,
    incoming: impl IntoIterator<Item = &'a HashDigest>,
    requirement: impl Display,
) -> Result<(), HashStrategyError> {
    for digest in incoming {
        match existing
            .iter()
            .find(|candidate| candidate.algorithm() == digest.algorithm())
        {
            Some(candidate) if candidate == digest => {}
            Some(conflict) => {
                return Err(HashStrategyError::ConflictingArchiveUrlHashes(
                    requirement.to_string(),
                    conflict.clone(),
                    digest.clone(),
                ));
            }
            None => existing.push(digest.clone()),
        }
    }
    existing.sort_unstable();

    Ok(())
}

#[derive(thiserror::Error, Debug)]
pub enum HashStrategyError {
    #[error(transparent)]
    Hash(#[from] HashError),
    #[error("Conflicting archive URL hashes for `{0}`: `{1}` conflicts with `{2}`")]
    ConflictingArchiveUrlHashes(String, HashDigest, HashDigest),
    #[error(
        "In `{1}` mode, all requirements must have their versions pinned with `==`, but found: {0}"
    )]
    UnpinnedRequirement(String, HashCheckingMode),
    #[error(
        "`{1}` hashes are insecure and cannot be used with `{2}` but no other hashes are available for: {0}"
    )]
    InsecureHashAlgorithm(String, HashAlgorithm, HashCheckingMode),
    #[error("In `{1}` mode, all requirements must have a hash, but none were provided for: {0}")]
    MissingHashes(String, HashCheckingMode),
    #[error(
        "In `{1}` mode, all requirements must have a hash, but there were no overlapping hashes between the requirements and constraints for: {0}"
    )]
    NoIntersection(String, HashCheckingMode),
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::slice;
    use std::str::FromStr;
    use std::sync::Arc;

    use rustc_hash::FxHashMap;
    use uv_configuration::HashCheckingMode;
    use uv_distribution_filename::DistExtension;
    use uv_distribution_types::{
        ArchiveHashPolicy, HashCollection, HashValidation, MetadataHashPolicy, Requirement,
        RequirementScope, RequirementSource, UnresolvedRequirement, VersionId,
    };
    use uv_normalize::PackageName;
    use uv_pep440::Version;
    use uv_pypi_types::HashDigest;
    use uv_redacted::DisplaySafeUrl;

    use super::{HashStrategy, HashVerification};

    fn requirement(url: &str) -> Requirement {
        Requirement {
            name: "anyio".parse().unwrap(),
            extras: Box::default(),
            groups: Box::default(),
            marker: "python_version >= '3.8'".parse().unwrap(),
            source: RequirementSource::Url {
                location: "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl"
                    .parse()
                    .unwrap(),
                subdirectory: None,
                ext: DistExtension::Wheel,
                url: url.parse().unwrap(),
            },
            scope: RequirementScope::Global,
            origin: None,
        }
    }

    #[test]
    fn from_requirements_merges_direct_url_hashes_across_fragments() {
        let first = UnresolvedRequirement::Named(requirement(
            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha256=CFDB2B588B9FC25EDE96D8DB56ED50848B0B649DCA3DD1DF0B11F683BB9E0B5F",
        ));
        let second = UnresolvedRequirement::Named(requirement(
            "https://files.pythonhosted.org/packages/36/55/ad4de788d84a630656ece71059665e01ca793c04294c463fd84132f40fe6/anyio-4.0.0-py3-none-any.whl#sha512=f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
        ));

        let hasher = HashStrategy::from_requirements(
            [(&first, &[][..]), (&second, &[][..])].into_iter(),
            std::iter::empty(),
            None,
            HashCheckingMode::Require,
        )
        .unwrap();

        let mut expected = vec![
            HashDigest::from_str(
                "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
            )
            .unwrap(),
            HashDigest::from_str(
                "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
            )
            .unwrap(),
        ];
        expected.sort_unstable();

        for requirement in [&first, &second] {
            let UnresolvedRequirement::Named(requirement) = requirement else {
                panic!("expected named requirement");
            };
            let RequirementSource::Url { url, .. } = &requirement.source else {
                panic!("expected direct URL requirement");
            };
            assert_eq!(
                hasher.archive_policy_for_url(url),
                ArchiveHashPolicy::All(expected.as_slice())
            );
        }
    }

    #[test]
    fn generate_and_verify_validates_known_hashes_and_generates_unknown_hashes()
    -> Result<(), Box<dyn std::error::Error>> {
        let url: DisplaySafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
        let unknown_url: DisplaySafeUrl = "https://example.com/anyio-4.1.0.tar.gz".parse()?;
        let name: PackageName = "anyio".parse()?;
        let version: Version = "4.0.0".parse()?;
        let unknown_version: Version = "4.1.0".parse()?;
        let digest = HashDigest::from_str(
            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
        )?;
        let hashes = FxHashMap::from_iter([
            (VersionId::from_url(&url), vec![digest.clone()]),
            (
                VersionId::from_registry(name.clone(), version.clone()),
                vec![digest.clone()],
            ),
        ]);
        let strategy = HashStrategy::collect(HashCollection::All)
            .with_verification(HashVerification::IfPresent(Arc::new(hashes)));

        assert_eq!(
            strategy.archive_policy_for_url(&url),
            ArchiveHashPolicy::All(slice::from_ref(&digest))
        );
        for fragment in [
            "#subdirectory=.",
            "#subdirectory=./",
            "#subdirectory=",
            "#subdirectory=nested/..",
        ] {
            let root_url = format!("{url}{fragment}").parse()?;
            assert_eq!(
                strategy.archive_policy_for_url(&root_url),
                ArchiveHashPolicy::All(slice::from_ref(&digest))
            );
        }
        assert_eq!(
            strategy.archive_policy_for_url(&unknown_url),
            ArchiveHashPolicy::Generate
        );
        assert_eq!(
            strategy.metadata_policy_for_url(&unknown_url),
            MetadataHashPolicy {
                collection: HashCollection::All,
                validation: HashValidation::None,
            }
        );
        assert_eq!(
            strategy.metadata_policy_for_url(&url),
            MetadataHashPolicy {
                collection: HashCollection::All,
                validation: HashValidation::All(slice::from_ref(&digest)),
            }
        );
        assert_eq!(
            strategy.archive_policy_for_package(&name, &version),
            ArchiveHashPolicy::Any(slice::from_ref(&digest))
        );
        assert_eq!(
            strategy.archive_policy_for_package(&name, &unknown_version),
            ArchiveHashPolicy::Generate
        );

        Ok(())
    }

    #[test]
    fn required_hashes_take_precedence_over_collection() -> Result<(), Box<dyn std::error::Error>> {
        let url: DisplaySafeUrl = "https://example.com/anyio-4.0.0.tar.gz".parse()?;
        let name: PackageName = "anyio".parse()?;
        let version: Version = "4.0.0".parse()?;
        let strategy = HashStrategy::collect(HashCollection::All)
            .with_verification(HashVerification::Required(Arc::default()));

        assert_eq!(
            strategy.archive_policy_for_url(&url),
            ArchiveHashPolicy::All(&[])
        );
        assert_eq!(
            strategy.metadata_policy_for_url(&url),
            MetadataHashPolicy {
                collection: HashCollection::All,
                validation: HashValidation::All(&[]),
            }
        );
        assert_eq!(
            strategy.archive_policy_for_package(&name, &version),
            ArchiveHashPolicy::Any(&[])
        );
        assert!(!strategy.allows_url(&url));
        assert!(!strategy.allows_package(&name, &version));

        let digest = HashDigest::from_str(
            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
        )?;
        let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([
            (VersionId::from_url(&url), vec![digest.clone()]),
            (
                VersionId::from_registry(name.clone(), version.clone()),
                vec![HashDigest::from_str(
                    "md5:420d85e19168705cdf0223621b18831a",
                )?],
            ),
        ])));
        for strategy in [
            strategy.clone().with_constraint_hashes(&constraints)?,
            constraints.with_constraint_hashes(&strategy)?,
        ] {
            assert_eq!(
                strategy.archive_policy_for_url(&url),
                ArchiveHashPolicy::All(slice::from_ref(&digest))
            );
            assert_eq!(
                strategy.archive_policy_for_package(&name, &version),
                ArchiveHashPolicy::Any(&[])
            );
            assert!(!strategy.allows_package(&name, &version));
        }
        Ok(())
    }

    #[test]
    fn constraint_hashes_combine_with_locked_hashes() -> Result<(), Box<dyn std::error::Error>> {
        let name: PackageName = "anyio".parse()?;
        let version: Version = "4.0.0".parse()?;
        let local_version: Version = "4.0.0+local".parse()?;
        let digest = HashDigest::from_str(
            "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f",
        )?;
        let other = HashDigest::from_str(
            "sha256:f7ed51751b2c2add651e5747c891b47e26d2a21be5d32d9311dfe9692f3e5d7a",
        )?;
        let sha512 = HashDigest::from_str(
            "sha512:f30761c1e8725b49c498273b90dba4b05c0fd157811994c806183062cb6647e773364ce45f0e1ff0b10e32fe6d0232ea5ad39476ccf37109d6b49603a09c11c2",
        )?;
        let registry = VersionId::from_registry(name.clone(), version);
        let local_registry = VersionId::from_registry(name, local_version);
        let archive = VersionId::from_url(&"https://example.com/anyio-4.0.0.tar.gz".parse()?);
        let path = VersionId::from_path(Path::new("anyio-4.0.0.tar.gz"));
        for (id, constraint_id, constraint, expected) in [
            (
                registry.clone(),
                registry,
                digest.clone(),
                vec![digest.clone()],
            ),
            (
                local_registry,
                VersionId::from_registry("anyio".parse()?, "4.0.0".parse()?),
                digest.clone(),
                vec![digest.clone()],
            ),
            (path.clone(), path, digest.clone(), vec![digest.clone()]),
            (
                archive.clone(),
                archive,
                sha512.clone(),
                vec![digest.clone(), sha512],
            ),
        ] {
            let locked = HashStrategy::collect(HashCollection::All).with_verification(
                HashVerification::IfPresent(Arc::new(FxHashMap::from_iter([(
                    id.clone(),
                    vec![digest.clone()],
                )]))),
            );
            let constraints = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
                constraint_id.clone(),
                vec![constraint],
            )])));
            let combined = locked.clone().with_constraint_hashes(&constraints)?;
            assert_eq!(combined.collection(), HashCollection::All);
            assert_eq!(combined.hashes_for_id(&id), Some(expected.as_slice()));

            let conflicting = HashStrategy::verify(Arc::new(FxHashMap::from_iter([(
                constraint_id,
                vec![other.clone()],
            )])));
            assert!(locked.with_constraint_hashes(&conflicting).is_err());
        }
        Ok(())
    }
}