cargo-vet 0.10.3

Supply-chain security for Rust
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
//! Details of the file formats used by cargo vet

use crate::cli::FetchMode;
use crate::errors::{StoreVersionParseError, VersionParseError};
use crate::resolver::{DiffRecommendation, ViolationConflict};
use crate::serialization::{spanned::Spanned, CacheFileVersion, Tidyable};
use crate::{flock::Filesystem, serialization};
use core::{cmp, fmt};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;

use cargo_metadata::{semver, Package};
use serde::{de, de::Visitor, Deserialize, Deserializer, Serialize, Serializer};

// Collections based on how we're using, so it's easier to swap them out.
pub type FastMap<K, V> = HashMap<K, V>;
pub type FastSet<T> = HashSet<T>;
pub type SortedMap<K, V> = BTreeMap<K, V>;
pub type SortedSet<T> = BTreeSet<T>;

pub type CriteriaName = String;
pub type CriteriaStr<'a> = &'a str;
pub type ForeignCriteriaName = String;
pub type PackageName = String;
pub type PackageStr<'a> = &'a str;
pub type ImportName = String;
pub type ImportStr<'a> = &'a str;
pub type CratesUserId = u64;
pub type CratesTrustpubSignature = String;

// newtype VersionReq so that we can implement PartialOrd on it.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct VersionReq(pub semver::VersionReq);
impl fmt::Display for VersionReq {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}
impl FromStr for VersionReq {
    type Err = <semver::VersionReq as FromStr>::Err;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        semver::VersionReq::from_str(s).map(VersionReq)
    }
}
impl core::ops::Deref for VersionReq {
    type Target = semver::VersionReq;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl cmp::PartialOrd for VersionReq {
    fn partial_cmp(&self, other: &VersionReq) -> Option<cmp::Ordering> {
        format!("{self}").partial_cmp(&format!("{other}"))
    }
}
impl VersionReq {
    pub fn parse(text: &str) -> Result<Self, <Self as FromStr>::Err> {
        cargo_metadata::semver::VersionReq::parse(text).map(VersionReq)
    }
    pub fn matches(&self, version: &VetVersion) -> bool {
        self.0.matches(&version.semver)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VetVersion {
    pub semver: semver::Version,
    pub git_rev: Option<String>,
}
impl VetVersion {
    pub fn parse(s: &str) -> Result<Self, VersionParseError> {
        if let Some((ver, rev)) = s.split_once('@') {
            if let Some(hash) = rev.trim_start().strip_prefix("git:") {
                if hash.len() != 40 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
                    Err(VersionParseError::InvalidGitHash)
                } else {
                    Ok(VetVersion {
                        semver: ver.trim_end().parse()?,
                        git_rev: Some(hash.to_owned()),
                    })
                }
            } else {
                Err(VersionParseError::UnknownRevision)
            }
        } else {
            Ok(VetVersion {
                semver: s.parse()?,
                git_rev: None,
            })
        }
    }

    /// Check if this VetVersion exactly matches the given semver version with
    /// no git revision metadata.
    pub fn equals_semver(&self, semver: &semver::Version) -> bool {
        self.git_rev.is_none() && &self.semver == semver
    }

    /// Get this VetVersion as a semver::Version, returning None if this version
    /// corresponds to a git revision.
    pub fn as_semver(&self) -> Option<&semver::Version> {
        if self.git_rev.is_none() {
            Some(&self.semver)
        } else {
            None
        }
    }
}
impl fmt::Display for VetVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.git_rev {
            Some(hash) => write!(f, "{}@git:{}", self.semver, hash),
            None => self.semver.fmt(f),
        }
    }
}
impl FromStr for VetVersion {
    type Err = VersionParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}
impl Serialize for VetVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_string().serialize(serializer)
    }
}
impl<'de> Deserialize<'de> for VetVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VersionVisitor;

        impl Visitor<'_> for VersionVisitor {
            type Value = VetVersion;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("semver version")
            }
            fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                VetVersion::parse(string).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_str(VersionVisitor)
    }
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                 Metaconfigs (found in Cargo.tomls)                             //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

/// A `[*.metadata.vet]` table in a Cargo.toml, configuring our behaviour
#[derive(serde::Deserialize)]
pub struct MetaConfigInstance {
    // Reserved for future use, if not present version=1 assumed.
    // (not sure whether this versions the format, or semantics, or...
    // for now assuming this species global semantics of some kind.
    pub version: Option<u64>,
    pub store: Option<StoreInfo>,
}
#[derive(serde::Deserialize)]
pub struct StoreInfo {
    pub path: Option<PathBuf>,
}

// FIXME: It's *possible* for someone to have a workspace but not have a
// global `vet` instance for the whole workspace. In this case they *could*
// have individual `vet` instances for each subcrate they care about.
// This is... Weird, and it's unclear what that *means*... but maybe it's valid?
// Either way, we definitely don't support it right now!

/// All available configuration files, overlaying each other.
/// Generally contains: `[Default, Workspace, Package]`
pub struct MetaConfig(pub Vec<MetaConfigInstance>);

impl MetaConfig {
    pub fn store_path(&self) -> Filesystem {
        // Last config gets priority to set this
        for config in self.0.iter().rev() {
            if let Some(store) = &config.store {
                if let Some(path) = &store.path {
                    return Filesystem::new(path.into());
                }
            }
        }
        unreachable!("Default config didn't define store.path???");
    }
    pub fn version(&self) -> u64 {
        // Last config gets priority to set this
        for config in self.0.iter().rev() {
            if let Some(ver) = config.version {
                return ver;
            }
        }
        unreachable!("Default config didn't define version???");
    }
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                                audits.toml                                     //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

pub type WildcardAudits = SortedMap<PackageName, Vec<WildcardEntry>>;

pub type AuditedDependencies = SortedMap<PackageName, Vec<AuditEntry>>;

pub type TrustedPackages = SortedMap<PackageName, Vec<TrustEntry>>;

/// audits.toml
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct AuditsFile {
    /// A map of criteria_name to details on that criteria.
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    #[serde(default)]
    pub criteria: SortedMap<CriteriaName, CriteriaEntry>,
    /// Wildcard audits
    #[serde(rename = "wildcard-audits")]
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    #[serde(default)]
    pub wildcard_audits: WildcardAudits,
    /// Actual audits.
    pub audits: AuditedDependencies,
    /// Trusted packages
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    #[serde(default)]
    pub trusted: TrustedPackages,
}

impl Tidyable for AuditsFile {
    fn tidy(&mut self) {
        self.audits.tidy();
        self.wildcard_audits.tidy();
        self.trusted.tidy();
    }
}

/// Foreign audits.toml with unparsed entries and audits. Should have the same
/// structure as `AuditsFile`, but with individual audits and criteria unparsed.
#[derive(serde::Deserialize, Clone, Debug)]
pub struct ForeignAuditsFile {
    #[serde(default)]
    pub criteria: SortedMap<CriteriaName, toml::Table>,
    #[serde(default)]
    #[serde(rename = "wildcard-audits")]
    pub wildcard_audits: SortedMap<PackageName, Vec<toml::Table>>,
    #[serde(default)]
    pub audits: SortedMap<PackageName, Vec<toml::Table>>,
    #[serde(default)]
    pub trusted: SortedMap<PackageName, Vec<toml::Table>>,
}

/// Information on a Criteria
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CriteriaEntry {
    /// Summary of how you evaluate something by this criteria.
    pub description: Option<String>,
    /// An alternative to description which locates the criteria text at a publicly-accessible URL.
    /// This can be useful for sharing criteria descriptions across multiple repositories.
    #[serde(rename = "description-url")]
    pub description_url: Option<String>,
    /// Criteria that this one implies
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    #[serde(with = "serialization::string_or_vec")]
    pub implies: Vec<Spanned<CriteriaName>>,
    /// Chain of sources this criteria was aggregated from, most recent last.
    #[serde(rename = "aggregated-from")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    #[serde(with = "serialization::string_or_vec")]
    pub aggregated_from: Vec<Spanned<String>>,
}

/// This is conceptually an enum
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(try_from = "serialization::audit::AuditEntryAll")]
#[serde(into = "serialization::audit::AuditEntryAll")]
pub struct AuditEntry {
    pub who: Vec<Spanned<String>>,
    pub criteria: Vec<Spanned<CriteriaName>>,
    pub kind: AuditKind,
    pub importable: bool,
    pub notes: Option<String>,
    /// Chain of sources this audit was aggregated from, most recent last.
    pub aggregated_from: Vec<Spanned<String>>,
    /// A non-serialized member which indicates whether this audit is a "fresh"
    /// audit. This will be set for all audits imported found in the remote
    /// audits file which aren't also found in the local `imports.lock` cache.
    ///
    /// This should almost always be `false`, and only set to `true` by the
    /// import handling code.
    #[serde(skip)]
    pub is_fresh_import: bool,
}

impl AuditEntry {
    /// Should `self` be considered to be the same audit as `other`, e.g. for
    /// the purposes of `is_fresh_import` checks?
    pub fn same_audit_as(&self, other: &AuditEntry) -> bool {
        // Ignore `who` and `notes` for comparison, as they are not relevant
        // semantically and might have been updated uneventfully.
        self.kind == other.kind && self.criteria == other.criteria
    }

    /// Try to collapse this (delta) entry with the given entry, which must be just prior to it
    /// (whether a delta or a full audit).
    ///
    /// If the entry can be collapsed, the new entry is returned. The new entry will merge the
    /// `who`, `notes`, and `kind` fields appropriately, and will derive `importable` based on
    /// `kind`.
    pub fn try_collapse_with_prior(&self, other: &AuditEntry) -> Option<Self> {
        let AuditKind::Delta {
            from: self_from,
            to: self_to,
        } = &self.kind
        else {
            return None;
        };
        let (other_from, other_to) = match &other.kind {
            AuditKind::Full { version } => (None, version),
            AuditKind::Delta { from, to } => (Some(from), to),
            AuditKind::Violation { .. } => return None,
        };

        if other_to != self_from {
            return None;
        }

        // TODO should this use a criteria mapper to avoid different orderings?
        if other.criteria != self.criteria {
            return None;
        }

        // Consume the existing audit's `from`, `who`, and `notes`.
        let mut new_entry = self.clone();
        new_entry.kind = match other_from {
            Some(version) => AuditKind::Delta {
                from: version.clone(),
                to: self_to.clone(),
            },
            None => AuditKind::Full {
                version: self_to.clone(),
            },
        };

        let unique_who: Vec<_> = other
            .who
            .iter()
            .filter(|s| !new_entry.who.contains(s))
            .cloned()
            .collect();
        // Precede with the `who` from the audit which aren't in this
        // ceritification, to retain a temporal ordering of auditors.
        new_entry.who.splice(..0, unique_who);

        // Precede the certification notes with the notes from the audit.
        if let Some(prior_notes) = &other.notes {
            new_entry.notes = Some(match new_entry.notes {
                None => prior_notes.clone(),
                Some(new_notes) => format!("{prior_notes}\n{new_notes}"),
            });
        }

        // Rederive `importable` based on the versions.
        new_entry.importable = new_entry.kind.default_importable();

        Some(new_entry)
    }
}

/// Implement PartialOrd manually because the order we want for sorting is
/// different than the order we want for serialization.
///
/// Strictly speaking Ord and PartialOrd implementations are supposed to agree,
/// and clippy recently started complaining about this. We should consider whether
/// there's another solution to this problem.
#[allow(clippy::non_canonical_partial_ord_impl)]
impl cmp::PartialOrd for AuditEntry {
    fn partial_cmp<'a>(&'a self, other: &'a AuditEntry) -> Option<cmp::Ordering> {
        let tuple = |x: &'a AuditEntry| (&x.kind, &x.criteria, &x.who, &x.notes);
        tuple(self).partial_cmp(&tuple(other))
    }
}

impl cmp::Ord for AuditEntry {
    fn cmp(&self, other: &AuditEntry) -> cmp::Ordering {
        self.partial_cmp(other).unwrap()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum AuditKind {
    Full { version: VetVersion },
    Delta { from: VetVersion, to: VetVersion },
    Violation { violation: VersionReq },
}

impl AuditKind {
    pub fn default_importable(&self) -> bool {
        match self {
            Self::Full { version } => version.git_rev.is_none(),
            Self::Delta { from, to } => from.git_rev.is_none() && to.git_rev.is_none(),
            Self::Violation { .. } => false,
        }
    }
}

/// A "VERSION" or "VERSION -> VERSION"
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Delta {
    pub from: Option<VetVersion>,
    pub to: VetVersion,
}

impl<'de> Deserialize<'de> for Delta {
    fn deserialize<D>(deserializer: D) -> Result<Delta, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct DeltaVisitor;

        impl Visitor<'_> for DeltaVisitor {
            type Value = Delta;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("version -> version delta")
            }

            fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if let Some((from, to)) = string.split_once("->") {
                    Ok(Delta {
                        from: Some(VetVersion::parse(from.trim()).map_err(de::Error::custom)?),
                        to: VetVersion::parse(to.trim()).map_err(de::Error::custom)?,
                    })
                } else {
                    Ok(Delta {
                        from: None,
                        to: VetVersion::parse(string.trim()).map_err(de::Error::custom)?,
                    })
                }
            }
        }

        deserializer.deserialize_str(DeltaVisitor)
    }
}

impl Serialize for Delta {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match &self.from {
            Some(from) => format!("{} -> {}", from, self.to).serialize(serializer),
            None => self.to.serialize(serializer),
        }
    }
}

impl fmt::Display for Delta {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.from {
            Some(from) => writeln!(f, "{} -> {}", from, self.to),
            None => self.to.fmt(f),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(untagged)]
pub enum CratesSourceId {
    User {
        #[serde(rename = "user-id")]
        user_id: CratesUserId,
    },
    TrustedPublisher {
        #[serde(rename = "trusted-publisher")]
        trusted_publisher: CratesTrustpubSignature,
    },
}

/// An entry specifying a wildcard audit for a specific crate based on crates.io
/// publication time and user-id.
///
/// These audits will be reified in the imports.lock file when unlocked.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct WildcardEntry {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(with = "serialization::string_or_vec")]
    pub who: Vec<Spanned<String>>,
    #[serde(with = "serialization::string_or_vec")]
    pub criteria: Vec<Spanned<CriteriaName>>,
    #[serde(flatten)]
    pub source: CratesSourceId,
    pub start: Spanned<chrono::NaiveDate>,
    pub end: Spanned<chrono::NaiveDate>,
    pub renew: Option<bool>,
    pub notes: Option<String>,
    #[serde(rename = "aggregated-from")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(with = "serialization::string_or_vec")]
    #[serde(default)]
    pub aggregated_from: Vec<Spanned<String>>,
    /// See `AuditEntry::is_fresh_import`.
    #[serde(skip)]
    pub is_fresh_import: bool,
}

impl WildcardEntry {
    /// Should `self` be considered to be the same audit as `other`, e.g. for
    /// the purposes of `is_fresh_import` checks?
    pub fn same_audit_as(&self, other: &WildcardEntry) -> bool {
        // Ignore `who` and `notes` for comparison, as they are not relevant
        // semantically and might have been updated uneventfully.
        self.source == other.source
            && self.start == other.start
            && self.end == other.end
            && self.criteria == other.criteria
    }

    /// Whether a renewal should be suggested for the entry.
    ///
    /// If the entry expires before `date` (and `renew` isn't `false`) a renewal will be
    /// suggested.
    pub fn should_renew(&self, date: chrono::NaiveDate) -> bool {
        self.renew.unwrap_or(true) && self.end < date
    }
}

/// An entry specifying a trusted publisher for a specific crate based on
/// crates.io publication time and user-id.
///
/// Trusted crates will be reified in the imports.lock file when unlocked.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct TrustEntry {
    #[serde(with = "serialization::string_or_vec")]
    pub criteria: Vec<Spanned<CriteriaName>>,
    #[serde(flatten)]
    pub source: CratesSourceId,
    pub start: Spanned<chrono::NaiveDate>,
    pub end: Spanned<chrono::NaiveDate>,
    pub notes: Option<String>,
    #[serde(rename = "aggregated-from")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(with = "serialization::string_or_vec")]
    #[serde(default)]
    pub aggregated_from: Vec<Spanned<String>>,
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                                config.toml                                     //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

/// config.toml
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct ConfigFile {
    #[serde(rename = "cargo-vet")]
    #[serde(default = "CargoVetConfig::missing")]
    pub cargo_vet: CargoVetConfig,

    /// This top-level key specifies the default criteria that cargo vet certify will use
    /// when recording audits. If unspecified, this defaults to "safe-to-deploy".
    #[serde(rename = "default-criteria")]
    #[serde(default = "get_default_criteria")]
    #[serde(skip_serializing_if = "is_default_criteria")]
    pub default_criteria: CriteriaName,

    /// Remote audits.toml's that we trust and want to import.
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    #[serde(default)]
    pub imports: SortedMap<ImportName, RemoteImport>,

    /// A table of policies for crates.
    #[serde(skip_serializing_if = "Policy::is_empty")]
    #[serde(default)]
    pub policy: Policy,

    /// All of the "foreign" dependencies that we rely on but haven't audited yet.
    /// Foreign dependencies are just "things on crates.io", everything else
    /// (paths, git, etc) is assumed to be "under your control" and therefore implicitly trusted.
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    #[serde(default)]
    #[serde(alias = "unaudited")]
    pub exemptions: SortedMap<PackageName, Vec<ExemptedDependency>>,
}

impl Tidyable for ConfigFile {
    fn tidy(&mut self) {
        self.exemptions.tidy();
    }
}

pub static SAFE_TO_DEPLOY: CriteriaStr = "safe-to-deploy";
pub static SAFE_TO_RUN: CriteriaStr = "safe-to-run";
pub static DEFAULT_CRITERIA: CriteriaStr = SAFE_TO_DEPLOY;

pub fn get_default_criteria() -> CriteriaName {
    CriteriaName::from(DEFAULT_CRITERIA)
}
fn is_default_criteria(val: &CriteriaName) -> bool {
    val == DEFAULT_CRITERIA
}

/// The table of crate policies.
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
#[serde(try_from = "serialization::policy::AllPolicies")]
#[serde(into = "serialization::policy::AllPolicies")]
pub struct Policy {
    pub package: SortedMap<PackageName, PackagePolicyEntry>,
}

impl Policy {
    /// Get the policy entry for the given crate, if any.
    pub fn get(&self, name: PackageStr, version: &VetVersion) -> Option<&PolicyEntry> {
        self.package
            .get(name)
            .and_then(|pkg_policy| match pkg_policy {
                PackagePolicyEntry::Unversioned(e) => Some(e),
                PackagePolicyEntry::Versioned { version: v } => v.get(version),
            })
    }

    /// Get the mutable policy entry for the given crate, if any.
    pub fn get_mut(
        &mut self,
        name: PackageStr,
        version: Option<&VetVersion>,
    ) -> Option<&mut PolicyEntry> {
        self.package
            .get_mut(name)
            .and_then(|pkg_policy| match pkg_policy {
                PackagePolicyEntry::Unversioned(e) => Some(e),
                PackagePolicyEntry::Versioned { version: v } => {
                    version.and_then(|version| v.get_mut(version))
                }
            })
    }

    /// Get the mutable policy entry for the given crate, creating a default if none exists.
    ///
    /// Unlike `get_mut`, if `require_versions` is provided, this guarantees that the policy is
    /// represented as versioned. This will never convert a versioned policy entry to an
    /// unversioned one.
    ///
    /// When converting an unversioned policy entry to a versioned one, the existing unversioned
    /// entry will be used for all new versioned entries which are being inserted.
    pub fn get_mut_or_default(
        &mut self,
        name: PackageName,
        version: &VetVersion,
        require_versions: Option<Vec<VetVersion>>,
    ) -> &mut PolicyEntry {
        // Ensure a policy entry exists for this package, inserting a default (unversioned) entry
        // if it doesn't. This will be converted to a versioned entry below if necessary.
        let pkg_policy = self.package.entry(name).or_default();

        // If we need a versioned entry, make sure all necessary versioned entries exist.
        if let Some(require_versions) = require_versions {
            // By default we insert an empty policy, but if there was an
            // existing unversioned entry, we'll use that as the policy for all
            // entries.
            let mut default = PolicyEntry::default();
            let versions_map = loop {
                match pkg_policy {
                    PackagePolicyEntry::Unversioned(entry) => {
                        default = std::mem::take(entry);
                        *pkg_policy = PackagePolicyEntry::Versioned {
                            version: Default::default(),
                        }
                    }
                    PackagePolicyEntry::Versioned { version } => break version,
                }
            };
            for version in require_versions {
                versions_map
                    .entry(version)
                    .or_insert_with(|| default.clone());
            }
        }

        match pkg_policy {
            PackagePolicyEntry::Unversioned(e) => e,
            PackagePolicyEntry::Versioned {
                version: versions_map,
            } => {
                // If the version is missing, create it
                versions_map.entry(version.clone()).or_default()
            }
        }
    }

    /// Insert a new package policy entry.
    pub fn insert(
        &mut self,
        name: PackageName,
        entry: PackagePolicyEntry,
    ) -> Option<PackagePolicyEntry> {
        self.package.insert(name, entry)
    }

    /// Return whether there are no policies defined.
    pub fn is_empty(&self) -> bool {
        self.package.is_empty()
    }

    /// Return an iterator over defined policies.
    pub fn iter(&self) -> PolicyIter<'_> {
        PolicyIter {
            iter: self.package.iter(),
            versioned: None,
        }
    }
}

pub struct PolicyIter<'a> {
    iter: <&'a SortedMap<PackageName, PackagePolicyEntry> as IntoIterator>::IntoIter,
    versioned: Option<(
        &'a PackageName,
        <&'a SortedMap<VetVersion, PolicyEntry> as IntoIterator>::IntoIter,
    )>,
}

impl<'a> Iterator for PolicyIter<'a> {
    type Item = (&'a PackageName, Option<&'a VetVersion>, &'a PolicyEntry);

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.versioned {
            Some((name, versioned)) => match versioned.next() {
                Some((v, p)) => Some((name, Some(v), p)),
                None => {
                    self.versioned = None;
                    self.next()
                }
            },
            None => {
                let (name, ppe) = self.iter.next()?;
                match ppe {
                    PackagePolicyEntry::Versioned { version } => {
                        self.versioned = Some((name, version.iter()));
                        self.next()
                    }
                    PackagePolicyEntry::Unversioned(p) => Some((name, None, p)),
                }
            }
        }
    }
}

impl<'a> IntoIterator for &'a Policy {
    type IntoIter = PolicyIter<'a>;
    type Item = <PolicyIter<'a> as Iterator>::Item;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Policies for a particular package (crate).
///
/// If the crate exists as a third-party crate anywhere in the dependency tree, crate versions for
/// _all_ and _only_ the versions present in the dependency tree must be provided to set policies.
/// Otherwise, versions may be omitted.
#[derive(Debug, Clone)]
// We have to use a slightly different serialization than than `serde(untagged)`, because toml only
// parses `Spanned` elements (as contained in `PolicyEntry`) through their own Deseralizer, and
// `serde(untagged)` deserializes everything into a buffer first to try different deserialization
// branches (which will use an internal `serde` Deserializer rather than the `toml` Deserializer).
pub enum PackagePolicyEntry {
    Versioned {
        version: SortedMap<VetVersion, PolicyEntry>,
    },
    Unversioned(PolicyEntry),
}

impl Default for PackagePolicyEntry {
    fn default() -> Self {
        PackagePolicyEntry::Unversioned(Default::default())
    }
}

/// Policies that crates must pass.
///
/// Policy settings here are basically the equivalent of audits.toml, which is separated out
/// because it's not supposed to be shared (or, doesn't really make sense to share, since
/// first-party crates are defined by "not on crates.io").
///
/// Because first-party crates are implicitly trusted, the only purpose of this table is to define
/// the boundary between first-party and third-party ones.  More specifically, the criteria of the
/// dependency edges between a first-party crate and its direct third-party dependencies.
///
/// If this sounds overwhelming, don't worry, everything defaults to "nothing special"
/// and an empty PolicyTable basically just means "everything should satisfy the
/// default criteria in audits.toml".
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
pub struct PolicyEntry {
    /// Whether this nominally-first-party crate should actually be subject to audits
    /// as-if it was third-party, based on matches to crates.io packages with the same
    /// name and version. This field is optional for any package that *doesn't* have
    /// such a match, and mandatory for all others (None == Some(false)).
    ///
    /// If true, this package will be handled like a third-party package and require
    /// audits. If the package is not in the crates.io registry, it will be an error
    /// and you should either make sure the current version is published or flip
    /// this back to false.
    ///
    /// Setting this value to true is intended for actual externally developed projects
    /// that you are importing into your project in a weird way with minimal modifications.
    /// For instance, if you manually vendor the package in, or maintain a small patchset
    /// on top of the currently published version.
    ///
    /// It should not be used for packages that are directly developed in this project
    /// (a project shouldn't publish audits for its own code) or for non-trivial forks.
    ///
    /// Audits you *do* perform should be for the actual version published to crates.io,
    /// which are the versions `cargo vet diff` and `cargo vet inspect` will fetch.
    #[serde(rename = "audit-as-crates-io")]
    pub audit_as_crates_io: Option<bool>,

    /// Default criteria that must be satisfied by all *direct* third-party (foreign) dependencies
    /// of the crate. If satisfied, the crate is set to satisfying all criteria.
    ///
    /// If not present, this defaults to the default criteria in the audits table.
    #[serde(default)]
    #[serde(with = "serialization::string_or_vec_or_none")]
    pub criteria: Option<Vec<Spanned<CriteriaName>>>,

    /// Same as `criteria`, but for crates that are only used as dev-dependencies.
    #[serde(rename = "dev-criteria")]
    #[serde(default)]
    #[serde(with = "serialization::string_or_vec_or_none")]
    pub dev_criteria: Option<Vec<Spanned<CriteriaName>>>,

    /// Custom criteria for a specific crate's dependencies.
    ///
    /// Any dependency edge that isn't explicitly specified defaults to `criteria`.
    #[serde(rename = "dependency-criteria")]
    #[serde(skip_serializing_if = "CriteriaMap::is_empty")]
    #[serde(with = "serialization::criteria_map")]
    #[serde(default)]
    pub dependency_criteria: CriteriaMap,

    /// Freeform notes
    pub notes: Option<String>,
}

/// Helper type for managing a mapping from a string to a set of criteria. This
/// is used for dependency-criteria to specify the criteria that transitive
/// dependencies must satisfy, as well as for criteria-maps when specifying the
/// criteria implied by foreign criteria.
///
/// Example:
///
/// ```toml
/// dependency_criteria = { hmac = ['secure', 'crypto_reviewed'] }
/// ```
///
/// ```toml
/// criteria-map = { fuzzed = 'safe-to-deploy' }
/// ```
pub type CriteriaMap = SortedMap<Spanned<String>, Vec<Spanned<CriteriaName>>>;

pub static DEFAULT_POLICY_CRITERIA: CriteriaStr = SAFE_TO_DEPLOY;
pub static DEFAULT_POLICY_DEV_CRITERIA: CriteriaStr = SAFE_TO_RUN;

/// A remote audits.toml that we trust the contents of (by virtue of trusting the maintainer).
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
pub struct RemoteImport {
    /// URL(s) of the foreign audits.toml
    #[serde(with = "serialization::string_or_vec")]
    pub url: Vec<String>,
    /// A list of crates for which no audits or violations should be imported.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub exclude: Vec<PackageName>,
    /// A list of criteria that are implied by foreign criteria
    #[serde(rename = "criteria-map")]
    #[serde(skip_serializing_if = "CriteriaMap::is_empty")]
    #[serde(with = "serialization::criteria_map")]
    #[serde(default)]
    pub criteria_map: CriteriaMap,
}

/// Translations of foreign criteria to local criteria.
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct CriteriaMapping {
    /// This local criteria is implied...
    pub ours: CriteriaName,
    /// If this foreign criteria applies
    pub theirs: Spanned<ForeignCriteriaName>,
}

/// Semantically identical to a 'full audit' entry, but private to our project
/// and tracked as less-good than a proper audit, so that you try to get rid of it.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct ExemptedDependency {
    /// The version of the crate that we are currently "fine" with leaving unaudited.
    pub version: VetVersion,
    /// Criteria that we're willing to handwave for this version (assuming our dependencies
    /// satisfy this criteria). This isn't defaulted, 'vet init' and similar commands will
    /// pick a "good" initial value.
    #[serde(default)]
    #[serde(with = "serialization::string_or_vec")]
    pub criteria: Vec<Spanned<CriteriaName>>,
    /// Whether 'suggest' should bother mentioning this (defaults true).
    #[serde(default = "get_default_exemptions_suggest")]
    #[serde(skip_serializing_if = "is_default_exemptions_suggest")]
    pub suggest: bool,
    /// Freeform notes, put whatever you want here. Just more stable/reliable than comments.
    pub notes: Option<String>,
}

static DEFAULT_EXEMPTIONS_SUGGEST: bool = true;
pub fn get_default_exemptions_suggest() -> bool {
    DEFAULT_EXEMPTIONS_SUGGEST
}
fn is_default_exemptions_suggest(val: &bool) -> bool {
    val == &DEFAULT_EXEMPTIONS_SUGGEST
}

/// Special version type used for store versions. Only contains two components
/// (major/minor) to avoid patch version changes from causing changes to the
/// store.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct StoreVersion {
    pub major: u64,
    pub minor: u64,
}

impl StoreVersion {
    #[cfg(not(test))]
    pub fn current() -> Self {
        StoreVersion {
            major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(),
            minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(),
        }
    }

    // To keep output from tests stable, when running unit tests we always
    // pretend we're version 1.0
    #[cfg(test)]
    pub fn current() -> Self {
        StoreVersion { major: 1, minor: 0 }
    }
}

impl FromStr for StoreVersion {
    type Err = StoreVersionParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once('.') {
            Some((major, minor)) => Ok(StoreVersion {
                major: major.parse()?,
                minor: minor.parse()?,
            }),
            None => Err(StoreVersionParseError::MissingSeparator),
        }
    }
}

impl fmt::Display for StoreVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

impl Serialize for StoreVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_string().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for StoreVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VersionVisitor;

        impl Visitor<'_> for VersionVisitor {
            type Value = StoreVersion;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("store version")
            }
            fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                StoreVersion::from_str(string).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_str(VersionVisitor)
    }
}

/// Cargo vet config metadata field for the store's config file.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CargoVetConfig {
    pub version: StoreVersion,
}

impl CargoVetConfig {
    /// Pretend that any store which was created without a version specified is
    /// from version 0.4.
    fn missing() -> Self {
        Self {
            version: StoreVersion { major: 0, minor: 4 },
        }
    }
}

impl Default for CargoVetConfig {
    fn default() -> Self {
        Self {
            version: StoreVersion::current(),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                                imports.lock                                    //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ImportsFile {
    #[serde(default)]
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    pub unpublished: SortedMap<PackageName, Vec<UnpublishedEntry>>,
    #[serde(default)]
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    pub publisher: SortedMap<PackageName, Vec<CratesPublisher>>,
    #[serde(default)]
    #[serde(skip_serializing_if = "SortedMap::is_empty")]
    pub audits: SortedMap<ImportName, AuditsFile>,
}

impl Tidyable for ImportsFile {
    fn tidy(&mut self) {
        self.unpublished.tidy();
        self.publisher.tidy();
        for audits_file in self.audits.values_mut() {
            audits_file.tidy();
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[serde(untagged)]
pub enum CratesPublisherSource {
    User {
        #[serde(rename = "user-id")]
        user_id: CratesUserId,
        #[serde(rename = "user-login")]
        user_login: String,
        #[serde(rename = "user-name")]
        user_name: Option<String>,
    },
    TrustedPublisher {
        #[serde(rename = "trusted-publisher")]
        trusted_publisher: CratesTrustpubSignature,
    },
}

impl CratesPublisherSource {
    pub fn as_identifier(&self) -> &str {
        match self {
            CratesPublisherSource::User { user_login, .. } => &user_login[..],
            CratesPublisherSource::TrustedPublisher { trusted_publisher } => &trusted_publisher[..],
        }
    }

    pub fn as_wildcard_source(&self) -> CratesSourceId {
        match self {
            CratesPublisherSource::User { user_id, .. } => {
                CratesSourceId::User { user_id: *user_id }
            }
            CratesPublisherSource::TrustedPublisher { trusted_publisher } => {
                CratesSourceId::TrustedPublisher {
                    trusted_publisher: trusted_publisher.clone(),
                }
            }
        }
    }
}

impl fmt::Display for CratesPublisherSource {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CratesPublisherSource::User {
                user_login,
                user_name: Some(user_name),
                ..
            } => write!(f, "{} ({})", user_name, user_login),
            CratesPublisherSource::User { user_login, .. } => write!(f, "{}", user_login),
            CratesPublisherSource::TrustedPublisher { trusted_publisher } => {
                write!(f, "{}", trusted_publisher)
            }
        }
    }
}

impl PartialEq<CratesSourceId> for CratesPublisherSource {
    fn eq(&self, other: &CratesSourceId) -> bool {
        match (self, other) {
            (
                CratesPublisherSource::User { user_id: us, .. },
                CratesSourceId::User { user_id: them },
            ) => us == them,
            (
                CratesPublisherSource::TrustedPublisher {
                    trusted_publisher: us,
                },
                CratesSourceId::TrustedPublisher {
                    trusted_publisher: them,
                },
            ) => us == them,
            _ => false,
        }
    }
}
impl PartialEq<CratesPublisherSource> for CratesSourceId {
    fn eq(&self, other: &CratesPublisherSource) -> bool {
        other == self
    }
}

/// Information about who published a specific version of a crate to be cached
/// in imports.lock.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CratesPublisher {
    // NOTE: This will only ever be a `semver::Version`, however the resolver
    // code works on borrowed `VetVersion` instances, so we use one here so it
    // is easier to use within the resolver.
    pub version: VetVersion,
    pub when: chrono::NaiveDate,
    #[serde(flatten)]
    pub source: CratesPublisherSource,
    /// See `AuditEntry::is_fresh_import`.
    #[serde(skip)]
    pub is_fresh_import: bool,
}

// Information about a specific crate being unpublished
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct UnpublishedEntry {
    // NOTE: This will only ever be a `semver::Version`, however the resolver
    // code works on borrowed `VetVersion` instances, so we use one here so it
    // is easier to use within the resolver.
    pub version: VetVersion,
    pub audited_as: VetVersion,
    /// Set to `true` if `version` was not published when acquiring the Store.
    /// Always set to `false` when locked.
    #[serde(skip)]
    pub still_unpublished: bool,
    /// See `AuditEntry::is_fresh_import`.
    #[serde(skip)]
    pub is_fresh_import: bool,
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                               diffcache.toml                                   //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

#[derive(Serialize, Deserialize, Default, Clone)]
pub struct DiffCache {
    pub version: CacheFileVersion<2>,
    pub diffs: SortedMap<PackageName, SortedMap<Delta, DiffStat>>,
}

impl Tidyable for DiffCache {
    fn tidy(&mut self) {}
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct DiffStat {
    pub insertions: u64,
    pub deletions: u64,
    pub files_changed: u64,
}

impl DiffStat {
    pub fn count(&self) -> u64 {
        self.insertions + self.deletions
    }
}

impl fmt::Display for DiffStat {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} files changed", self.files_changed)?;
        if self.insertions > 0 {
            write!(f, ", {} insertions(+)", self.insertions)?;
        }
        if self.deletions > 0 {
            write!(f, ", {} deletions(-)", self.deletions)?;
        }
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                             command-history.json                               //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum FetchCommand {
    Inspect {
        package: PackageName,
        version: VetVersion,
    },
    Diff {
        package: PackageName,
        version1: VetVersion,
        version2: VetVersion,
    },
}

impl FetchCommand {
    pub fn package(&self) -> PackageStr<'_> {
        match self {
            FetchCommand::Inspect { package, .. } => package,
            FetchCommand::Diff { package, .. } => package,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct CommandHistory {
    pub version: CacheFileVersion<1>,
    #[serde(flatten)]
    pub last_fetch: Option<FetchCommand>,
    pub last_diff_fetch_mode: Option<FetchMode>,
    pub last_inspect_fetch_mode: Option<FetchMode>,
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                             crates-io-cache.json                               //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CratesCacheUser {
    pub login: String,
    pub name: Option<String>,
}
impl fmt::Display for CratesCacheUser {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(name) = &self.name {
            write!(f, "{} ({})", name, self.login)
        } else {
            write!(f, "{}", self.login)
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CratesCacheVersionDetails {
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub source: Option<CratesSourceId>,
}

#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub struct CratesCacheEntry {
    pub versions: SortedMap<semver::Version, CratesCacheVersionDetails>,
    pub metadata: CratesAPICrateMetadata,
}

#[derive(Serialize, Deserialize, Clone, Default)]
pub struct CratesCache {
    pub version: CacheFileVersion<2>,
    pub users: SortedMap<CratesUserId, CratesCacheUser>,
    pub crates: SortedMap<PackageName, Arc<CratesCacheEntry>>,
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                                 crates.io API                                  //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

// NOTE: This is a subset of the format returned from the crates.io v1 API.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CratesAPIUser {
    pub id: CratesUserId,
    pub login: String,
    pub name: Option<String>,
}

// NOTE: This is a subset of the format returned from the crates.io v1 API.
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[serde(tag = "provider")]
pub enum CratesAPITrustpubData {
    #[serde(rename = "github")]
    GitHub { repository: String },
    #[serde(other)]
    Unknown,
}

impl CratesAPITrustpubData {
    pub fn as_signature(&self) -> Option<CratesTrustpubSignature> {
        match self {
            CratesAPITrustpubData::GitHub { repository } => Some(format!("github:{repository}")),
            CratesAPITrustpubData::Unknown => None,
        }
    }
}

// NOTE: This is a subset of the format returned from the crates.io v1 API.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CratesAPIVersion {
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub num: semver::Version,
    pub published_by: Option<CratesAPIUser>,
    pub trustpub_data: Option<CratesAPITrustpubData>,
}

// NOTE: This is a subset of the format returned from the crates.io v1 API.
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct CratesAPICrateMetadata {
    pub description: Option<String>,
    pub repository: Option<String>,
}

// NOTE: This is a subset of the format returned from the crates.io v1 API.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CratesAPICrate {
    #[serde(rename = "crate")]
    pub crate_data: CratesAPICrateMetadata,
    pub versions: Vec<CratesAPIVersion>,
}

impl CratesAPICrateMetadata {
    /// Whether this metadata is similar enough to that of the given package to be considered the
    /// same.
    pub fn consider_as_same(&self, p: &Package) -> bool {
        (self.description.is_some() && p.description == self.description)
            || (self.repository.is_some() && p.repository == self.repository)
    }
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                               registry.toml                                    //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct RegistryFile {
    pub registry: SortedMap<ImportName, RegistryEntry>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RegistryEntry {
    #[serde(with = "serialization::string_or_vec")]
    pub url: Vec<String>,
}

////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                                                                //
//                                                                                //
//                             <json report output>                               //
//                                                                                //
//                                                                                //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////

/// cargo-vet's `--output-format=json` for `check` and `suggest` on:
///
/// * success
/// * audit failure
/// * violation conflicts
///
/// Other errors like i/o or supply-chain integrity issues will show
/// up as miette-style json errors.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonReport {
    #[serde(flatten)]
    pub conclusion: JsonReportConclusion,
}

/// The conclusion of running `check` or `suggest`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "conclusion")]
pub enum JsonReportConclusion {
    /// Success! Everything's Good.
    #[serde(rename = "success")]
    Success(JsonReportSuccess),
    /// The violations and audits/exemptions are contradictory!
    #[serde(rename = "fail (violation)")]
    FailForViolationConflict(JsonReportFailForViolationConflict),
    /// The audit failed, here's why and what to do.
    #[serde(rename = "fail (vetting)")]
    FailForVet(JsonReportFailForVet),
}

/// Success! Everything is audited!
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonReportSuccess {
    /// These packages are fully vetted
    pub vetted_fully: Vec<JsonPackage>,
    /// These packages are partially vetted (some audits but relies on an `exemption`).
    pub vetted_partially: Vec<JsonPackage>,
    /// These packages are exempted
    pub vetted_with_exemptions: Vec<JsonPackage>,
}

/// Failure! The violations and audits/exemptions are contradictory!
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonReportFailForViolationConflict {
    /// These packages have the following conflicts
    // FIXME(SCHEMA): we probably shouldn't expose this internal type
    pub violations: SortedMap<PackageAndVersion, Vec<ViolationConflict>>,
}

/// Failure! You need more audits!
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonReportFailForVet {
    /// Here are the problems we found
    pub failures: Vec<JsonVetFailure>,
    /// And here are the fixes we recommend
    pub suggest: Option<JsonSuggest>,
}

/// Suggested fixes for a FailForVet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonSuggest {
    /// Here are the suggestions sorted in the order of priority
    pub suggestions: Vec<JsonSuggestItem>,
    /// The same set of suggestions but grouped by the criteria (lists) needed to audit them
    // FIXME(SCHEMA): this is kinda redundant? do consumers want this?
    pub suggest_by_criteria: SortedMap<String, Vec<JsonSuggestItem>>,
    /// The total number of lines you would need to review to resolve this
    pub total_lines: u64,
}

/// This specific package needed the following criteria but doesn't have them!
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonVetFailure {
    /// The name of the package
    pub name: PackageName,
    /// The version of the package
    pub version: VetVersion,
    /// The missing criteria
    pub missing_criteria: Vec<CriteriaName>,
}

/// We recommend auditing the following package
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonSuggestItem {
    /// The name of the package
    pub name: PackageName,
    /// Any notable parents the package has (can be helpful in giving context to the user)
    // FIXME(SCHEMA): we probably shouldn't expose this as a String
    pub notable_parents: String,
    /// The criteria we recommend auditing the package for
    pub suggested_criteria: Vec<CriteriaName>,
    /// The diff (or full version) we recommend auditing
    // FIXME(SCHEMA): we probably shouldn't expose this internal type
    pub suggested_diff: DiffRecommendation,
}

/// A string of the form "package:version"
pub type PackageAndVersion = String;

/// A Package
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonPackage {
    /// Name of the package
    pub name: PackageName,
    /// Version of the package
    pub version: VetVersion,
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn vet_version_parsing() {
        assert_eq!(
            VetVersion::parse("1.0.0").unwrap(),
            VetVersion {
                semver: "1.0.0".parse().unwrap(),
                git_rev: None
            }
        );

        assert_eq!(
            VetVersion::parse("1.0.1@git:00112233445566778899aabbccddeeff00112233").unwrap(),
            VetVersion {
                semver: "1.0.1".parse().unwrap(),
                git_rev: Some("00112233445566778899aabbccddeeff00112233".into())
            }
        );

        match VetVersion::parse("1.0.1@git:00112233445566778899aabbccddeeff0011223g") {
            Err(VersionParseError::InvalidGitHash) => (),
            _ => panic!("expected invalid git hash"),
        }

        match VetVersion::parse("1.0.1@git:00112233") {
            Err(VersionParseError::InvalidGitHash) => (),
            _ => panic!("expected invalid git hash"),
        }

        match VetVersion::parse("1.0.1@pijul:00112233") {
            Err(VersionParseError::UnknownRevision) => (),
            _ => panic!("expected unknown revision"),
        }
    }
}