pkix-lint 0.2.0

Lint engine for X.509 certificates — structured soft-fail and advisory results
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
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
//! Deviation (waiver) mechanism for `pkix-lint`.
//!
//! A [`Deviation`] is an operator-authored, scoped, time-bounded exception to a
//! specific lint finding. Deviations are the only mechanism for suppressing or
//! downgrading lint findings — there are no CLI flags or global overrides.
//!
//! # Design rationale
//!
//! The deviation mechanism is designed to:
//! - Make suppression **explicit and attributable**: every deviation has an ID,
//!   a justification, and an `authorized_by` field that appear in reports.
//! - Force **scoping**: deviations match specific certs (by issuer DN, serial, etc.),
//!   not all certs globally.
//! - Enforce **expiry**: deviations with an `effective_end` re-activate findings
//!   after they expire, forcing renewal and re-justification.
//! - **Not launder violations**: a suppressed finding is recorded as a
//!   [`DeviatedFinding`] in the output, not silently removed. Auditors can see it.
//!
//! # Verification via git, not signatures
//!
//! `authorized_by` is human-readable attribution (name or email), not a
//! cryptographic signature. The audit trail comes from the git history of
//! the deviation store: the git log records who committed the deviation file,
//! when, and from which identity. Store deviation files in a git repository
//! with appropriate access controls and signed commits. This provides the
//! same audit properties as an in-band signature without requiring additional
//! key infrastructure that most operators don't have wired into their PKI tooling.
//!
//! # No vendor deviation packs
//!
//! `pkix-lint` never ships deviation packs. CAs, vendors, or policy authorities
//! who want to ship deviations for their customers must distribute them separately,
//! and operators must explicitly load them into their own [`DeviationStore`]. This
//! prevents the tool from becoming an instrument for CA-side laundering.
//!
//! # Usage
//!
//! ```rust,no_run
//! // This example requires an external certificate fixture; it compiles but
//! // cannot run in the doctest harness without DER fixtures on disk.
//! use pkix_lint::deviation::{Deviation, DeviationAction, DeviationScope, DeviationStore};
//! use pkix_lint::Severity;
//!
//! let mut store = DeviationStore::new();
//! store.add(Deviation {
//!     id: "agency-x-fpki-keyusage-2026-q1".to_string(),
//!     target_lint: "fpki.common.6.1.5".to_string(),
//!     scope: DeviationScope::IssuerDnContains("agency x issuing ca".to_string()),
//!     effective_start: None,
//!     effective_end: Some(1_767_225_600), // 2026-01-01
//!     action: DeviationAction::DowngradeSeverityTo(Severity::Info),
//!     justification: "FPKIPA waiver memo 2025-11-03; see exception register entry 47".to_string(),
//!     authorized_by: "agency-x-ciso@agency.gov".to_string(),
//!     // Optional: URI to the backing document. git commit history is the audit trail.
//!     evidence_uri: Some("https://pkipolicy.agency.gov/waivers/2025-11-03".to_string()),
//! }).unwrap();
//!
//! // Use a DeviationRunner (wraps LintRunner) to apply deviations automatically.
//! ```

use crate::Severity;
use x509_cert::Certificate;

#[cfg(feature = "serde")]
use crate::de_cow_static;

/// Error returned by [`DeviationStore::add`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeviationAddError {
    /// A deviation with the same `id` already exists in the store.
    DuplicateId(String),
    /// A required string field (`justification` or `authorized_by`) was empty.
    EmptyField(String),
}

impl std::fmt::Display for DeviationAddError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateId(id) => {
                write!(f, "deviation id '{id}' already exists in the store")
            }
            Self::EmptyField(field) => {
                write!(f, "deviation field '{field}' must not be empty")
            }
        }
    }
}

impl std::error::Error for DeviationAddError {}

/// A scoped, time-bounded exception to a specific lint finding.
///
/// See the module-level documentation for the design rationale and usage.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug)]
pub struct Deviation {
    /// Unique identifier for this deviation within the operator's store.
    ///
    /// Appears verbatim in finding output as `DEVIATION APPLIED by <id>`.
    /// Must be unique within the [`DeviationStore`] that contains it.
    pub id: String,

    /// The stable lint ID this deviation applies to.
    ///
    /// Must exactly match the value returned by [`crate::Lint::id`] for the
    /// target lint. Deviations are lint-ID scoped — they do not apply to all
    /// findings of a given severity or category.
    pub target_lint: String,

    /// Which certificates this deviation applies to.
    ///
    /// Only certs that match the scope will have the deviation applied.
    /// Use [`DeviationScope::Any`] only for internal CAs or test environments
    /// where the profile itself is being applied informally.
    pub scope: DeviationScope,

    /// Unix epoch (seconds) after which this deviation becomes active.
    ///
    /// `None` means the deviation is active immediately (from the Unix epoch).
    pub effective_start: Option<u64>,

    /// Unix epoch (seconds) after which this deviation expires.
    ///
    /// `None` means the deviation never expires. This is strongly discouraged
    /// for production deviations — omitting an end date removes the automatic
    /// re-review trigger. Use `None` only for structural deviations that are
    /// permanent by design (e.g., an internal CA that will never follow FPKI policy).
    pub effective_end: Option<u64>,

    /// What to do with a matching finding.
    pub action: DeviationAction,

    /// Human-readable justification for this deviation.
    ///
    /// Examples: "FPKIPA waiver memo 2025-11-03", "Internal CA not subject to FPKI",
    /// "CA confirmed CP §6.1.5 interpreted as optional for HW tokens per guidance doc".
    /// Appears in finding output and audit reports. Must be non-empty.
    pub justification: String,

    /// Who authorized this deviation.
    ///
    /// The name or email of the person with authority to approve the deviation.
    /// Examples: `"agency-x-ciso@agency.gov"`, `"CN=PKI Officer, OU=CISO, O=Agency X"`.
    ///
    /// This is human-readable attribution, not a cryptographic signature.
    /// The verification layer is the git commit history of the deviation store:
    /// the git log records who committed the deviation file, when, and from
    /// which identity. Store your deviation files in a git repository with
    /// appropriate access controls and signed commits; that provides the
    /// audit trail without requiring additional signing infrastructure here.
    ///
    /// Must be non-empty.
    pub authorized_by: String,

    /// Optional URI pointing to the backing waiver or authorization document.
    ///
    /// When present, this URI is included in [`DeviatedFinding`] output so that
    /// operators can navigate directly to the authorization document when
    /// reviewing or escalating a deviated finding.
    ///
    /// # Examples
    ///
    /// - `Some("file:///var/lib/agency-x-pki/waivers/2025-11-03.pdf")` — local file
    /// - `Some("https://pkipolicy.agency.gov/waivers/2025-11-03")` — web document
    /// - `Some("https://github.com/agency-x/pki-exceptions/issues/47")` — issue tracker
    ///
    /// `None` is acceptable but discouraged for production deviations in gov/mil
    /// contexts where the IG may ask for the authorizing document.
    pub evidence_uri: Option<String>,
}

impl Deviation {
    /// Returns `true` if this deviation is active at `now_unix`.
    ///
    /// A deviation is active when:
    /// - `effective_start` is `None` or `<= now_unix`
    /// - `effective_end` is `None` or `> now_unix`
    ///
    /// The `>` comparison on `effective_end` means a deviation expires at
    /// the second it reaches its end timestamp, not one second after.
    #[must_use]
    pub fn is_active_at(&self, now_unix: u64) -> bool {
        let after_start = self.effective_start.map_or(true, |start| now_unix >= start);
        let before_end = self.effective_end.map_or(true, |end| now_unix < end);
        after_start && before_end
    }

    /// Returns `true` if this deviation applies to `cert` at `now_unix`.
    ///
    /// Both the time-active check and the scope check must pass.
    #[must_use]
    pub fn applies_to(&self, cert: &Certificate, now_unix: u64) -> bool {
        if !self.is_active_at(now_unix) {
            return false;
        }
        self.scope.matches(cert)
    }
}

/// Specifies which certificates a [`Deviation`] applies to.
///
/// Scopes are evaluated against the certificate at chain index 0 (the leaf)
/// for cert-scope lints. For path-scope lints, the scope is evaluated against
/// the leaf certificate.
///
/// # Choosing a scope
///
/// Use the narrowest scope that resolves the actual problem:
/// - Prefer `SerialRange` when the deviation covers a specific issuance batch.
/// - Prefer `IssuerDnExact` when all certs from a given CA are affected.
/// - Use `IssuerDnContains` for human-readable convenience scoping in dev/test.
/// - Use `Any` only for internal CAs or test environments where the profile
///   is intentionally not applicable.
///
/// # Planned additions (v0.3)
///
/// - `SubjectDnContains(String)` — for subscriber-identity scoping
/// - `PolicyOid(ObjectIdentifier)` — certs asserting a specific CP OID
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviationScope {
    /// The deviation applies to all certificates.
    ///
    /// Use `Any` only for internal CAs or test environments where the profile
    /// is intentionally not applicable. `Any` deviations are the most likely
    /// to be questioned by an auditor.
    Any,

    /// The deviation applies to certs whose issuer DN string representation
    /// contains the given substring (case-insensitive).
    ///
    /// Example: `IssuerDnContains("agency x issuing ca".to_string())` matches
    /// any cert whose issuer DN contains "Agency X Issuing CA".
    ///
    /// The substring is automatically lowercased by [`DeviationStore::add`].
    /// Constructing the scope with a mixed-case string and inserting it via
    /// `add()` is safe; the stored string will be normalized. Direct
    /// construction of a scope without going through `add()` (e.g., for
    /// serialization round-trips) should use a pre-lowercased string to
    /// preserve the invariant that matching logic assumes.
    ///
    /// This is a substring match, not an RFC 4518-normalized DN match. Prefer
    /// [`DeviationScope::IssuerDnExact`] when precise DN identity is required.
    ///
    /// **Warning**: case folding uses `make_ascii_lowercase()`, which only folds
    /// ASCII characters. This may fail to match non-ASCII DN components (e.g.,
    /// accented letters or CJK characters) because non-ASCII code points are left
    /// unchanged. If the issuer DN contains non-ASCII characters, use
    /// [`DeviationScope::IssuerDnExact`] instead.
    IssuerDnContains(String),

    /// The deviation applies to certs whose issuer DN matches exactly, using
    /// RFC 4518 normalization (the same algorithm as `pkix_path::names_match`).
    ///
    /// # Construction
    ///
    /// Construct from a certificate you already have:
    ///
    /// ```rust,no_run
    /// // `ca_cert` is a Certificate obtained from the calling context.
    /// use pkix_lint::deviation::DeviationScope;
    /// use x509_cert::Certificate;
    ///
    /// let ca_cert: Certificate = unimplemented!("load from DER");
    /// let scope = DeviationScope::IssuerDnExact(
    ///     ca_cert.tbs_certificate.subject.clone()
    /// );
    /// ```
    ///
    /// This is the preferred scope for production deviations over `IssuerDnContains`
    /// because it is unambiguous and resistant to substring-match confusion.
    IssuerDnExact(x509_cert::name::Name),

    /// The deviation applies to certs issued by a specific CA within a serial
    /// number range (inclusive on both ends).
    ///
    /// `issuer` is the CA's subject DN (RFC 4518-normalized match).
    /// `start` and `end` are the serial number bounds as raw byte vectors.
    /// The comparison uses byte-lexicographic order, which is identical to
    /// numeric order for DER-encoded positive integers (big-endian, no leading
    /// zeros except to prevent sign-bit confusion).
    ///
    /// # Use case
    ///
    /// Use when a specific issuance batch (e.g., certs issued between two dates
    /// from a particular CA) has a known deviation. This is the most precise scope
    /// and the most defensible in an audit.
    ///
    /// # Construction
    ///
    /// ```rust,no_run
    /// // `start_cert`, `end_cert`, and `issuing_ca_cert` are Certificates from the
    /// // calling context. They are not defined here so this cannot run in a doctest.
    /// use pkix_lint::deviation::DeviationScope;
    /// use x509_cert::Certificate;
    ///
    /// let start_cert: Certificate = unimplemented!("load from DER");
    /// let end_cert: Certificate = unimplemented!("load from DER");
    /// let issuing_ca_cert: Certificate = unimplemented!("load from DER");
    /// // Obtain the serial bytes from an example cert in the batch:
    /// let start_bytes = start_cert.tbs_certificate.serial_number.as_bytes().to_vec();
    /// let end_bytes   = end_cert.tbs_certificate.serial_number.as_bytes().to_vec();
    /// let scope = DeviationScope::SerialRange {
    ///     issuer: issuing_ca_cert.tbs_certificate.subject.clone(),
    ///     start: start_bytes,
    ///     end: end_bytes,
    /// };
    /// ```
    SerialRange {
        /// The issuer CA's subject DN.
        issuer: x509_cert::name::Name,
        /// Start of the serial number range (inclusive), as raw bytes.
        start: Vec<u8>,
        /// End of the serial number range (inclusive), as raw bytes.
        end: Vec<u8>,
    },
}

impl DeviationScope {
    /// Returns `true` if `cert` is within this scope.
    #[must_use]
    pub fn matches(&self, cert: &Certificate) -> bool {
        match self {
            Self::Any => true,

            Self::IssuerDnContains(substring) => {
                // Allocates one String per call to convert the Name to its display form.
                // For high-frequency lint passes, prefer IssuerDnExact (uses RFC 4518
                // normalized comparison without String allocation).
                // `substring` is pre-lowercased by `DeviationStore::add`; no
                // need to call `.to_lowercase()` on it again here.
                // Use `make_ascii_lowercase` (in-place, single allocation) instead
                // of `to_lowercase` (which allocates a new String for Unicode chars).
                // CA DN strings are always ASCII in practice, so this is equivalent
                // and avoids a second heap allocation.
                let mut issuer_str = cert.tbs_certificate.issuer.to_string();
                issuer_str.make_ascii_lowercase();
                issuer_str.contains(substring.as_str())
            }

            Self::IssuerDnExact(name) => {
                // Use pkix_path::names_match for RFC 4518-normalized comparison.
                pkix_path::names_match(name, &cert.tbs_certificate.issuer)
            }

            Self::SerialRange { issuer, start, end } => {
                // Issuer DN must match.
                if !pkix_path::names_match(issuer, &cert.tbs_certificate.issuer) {
                    return false;
                }
                // Serial number must be within [start, end] by byte-lexicographic order.
                // DER-encoded positive integers are big-endian with minimal encoding,
                // so lexicographic order = numeric order for same-length values.
                // For different-length values: longer byte sequences represent larger numbers
                // only when stripped of leading-zero padding. We do a simple length-first
                // comparison, which is correct for well-formed DER serial numbers.
                let serial = cert.tbs_certificate.serial_number.as_bytes();
                let cmp_start = serial_cmp(serial, start);
                let cmp_end = serial_cmp(serial, end);
                cmp_start.is_ge() && cmp_end.is_le()
            }
        }
    }
}

// ---------------------------------------------------------------------------
// serde::Serialize for DeviationScope
//
// x509_cert::name::Name (used in IssuerDnExact and SerialRange) does not
// implement serde::Serialize in x509-cert 0.2.x.  We provide a manual impl
// that serializes Name values as their RFC 4514 string representation so that
// operator tooling can export deviation stores to JSON without pulling in
// additional encoding dependencies.  Deserialization is not provided because
// round-tripping through the string representation would require a DN parser,
// which is out of scope for v0.2.
// ---------------------------------------------------------------------------

#[cfg(feature = "serde")]
impl serde::Serialize for DeviationScope {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStructVariant as _;
        match self {
            Self::Any => serializer.serialize_unit_variant("DeviationScope", 0, "Any"),
            Self::IssuerDnContains(s) => {
                serializer.serialize_newtype_variant("DeviationScope", 1, "IssuerDnContains", s)
            }
            Self::IssuerDnExact(name) => serializer.serialize_newtype_variant(
                "DeviationScope",
                2,
                "IssuerDnExact",
                &name.to_string(),
            ),
            Self::SerialRange { issuer, start, end } => {
                let mut sv =
                    serializer.serialize_struct_variant("DeviationScope", 3, "SerialRange", 3)?;
                sv.serialize_field("issuer", &issuer.to_string())?;
                sv.serialize_field("start", start)?;
                sv.serialize_field("end", end)?;
                sv.end()
            }
        }
    }
}

/// Compare two byte slices as DER positive-integer serial numbers.
///
/// DER positive integers are big-endian with a leading 0x00 byte only when the
/// high bit would otherwise be set (sign-bit convention). Leading zeros are
/// stripped before comparing; longer (after stripping) is greater, equal length
/// falls through to lexicographic byte comparison.
///
/// Call sites use `.is_ge()` / `.is_le()` for "in range" checks.
fn serial_cmp(a: &[u8], b: &[u8]) -> core::cmp::Ordering {
    let a = strip_leading_zeros(a);
    let b = strip_leading_zeros(b);
    a.len().cmp(&b.len()).then_with(|| a.cmp(b))
}

fn strip_leading_zeros(bytes: &[u8]) -> &[u8] {
    let first_nonzero = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
    &bytes[first_nonzero..]
}

/// What a [`Deviation`] does to a matching finding.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviationAction {
    /// Change the finding's severity to the specified level.
    ///
    /// The finding is still recorded in the output — it is not removed.
    /// The deviation ID appears in the [`DeviatedFinding`] so auditors can see it.
    DowngradeSeverityTo(Severity),

    /// Mark the finding as suppressed (effectively `NotApplicable` for reporting).
    ///
    /// The finding is still recorded as a [`DeviatedFinding`] with
    /// `action: DeviationAction::Suppress` so auditors can see that the deviation
    /// was applied. It does not appear as a normal finding.
    ///
    /// Use only when `DowngradeSeverityTo(Severity::Info)` is not sufficient
    /// (e.g., the finding would be incorrectly categorized as Info in reports).
    Suppress,
}

/// A finding with a deviation applied.
///
/// The underlying lint ID, original result, and deviation metadata are all
/// preserved for audit purposes. A `DeviatedFinding` is never silently hidden.
///
/// # Operator UI guidance
///
/// Display deviated findings as "DEVIATION APPLIED" rather than green/pass.
/// Show `deviation_id`, `justification`, and `evidence_uri` (when present) so
/// operators can navigate to the backing waiver document without a second lookup.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(bound(deserialize = "'de: 'static")))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviatedFinding {
    /// The stable lint ID of the lint that produced this finding.
    #[cfg_attr(feature = "serde", serde(deserialize_with = "de_cow_static"))]
    pub lint_id: std::borrow::Cow<'static, str>,
    /// The citation for the lint that produced this finding.
    #[cfg_attr(feature = "serde", serde(deserialize_with = "de_cow_static"))]
    pub citation: std::borrow::Cow<'static, str>,
    /// The original lint result before the deviation was applied.
    pub original_result: crate::LintResult,
    /// The deviation ID that was applied.
    pub deviation_id: String,
    /// The action taken by the deviation.
    pub action: DeviationAction,
    /// Human-readable justification from the deviation.
    pub justification: String,
    /// URI pointing to the backing waiver document, if one was provided.
    ///
    /// `None` if the deviation did not include an `evidence_uri`.
    pub evidence_uri: Option<String>,
    /// For certificate-scope findings, the zero-based chain index.
    pub cert_index: Option<usize>,
    /// Unix epoch seconds at which the lint was evaluated.
    ///
    /// Propagated from [`crate::Finding::evaluated_at_unix`] when the deviation
    /// is applied. Matches the `now_unix` passed to the runner method.
    pub evaluated_at_unix: u64,
}

impl DeviatedFinding {
    /// Returns the effective severity after the deviation was applied.
    ///
    /// - `DowngradeSeverityTo(s)` returns `s`.
    /// - `Suppress` returns `None` (the finding is suppressed from normal output).
    #[must_use]
    pub const fn effective_severity(&self) -> Option<Severity> {
        match &self.action {
            DeviationAction::DowngradeSeverityTo(s) => Some(*s),
            DeviationAction::Suppress => None,
        }
    }
}

/// An in-memory collection of [`Deviation`]s.
///
/// The store is append-only in v0.2. Future versions may add update/delete
/// and persistence (file-backed JSON/OSCAL format).
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Default)]
pub struct DeviationStore {
    deviations: Vec<Deviation>,
}

impl DeviationStore {
    /// Create an empty store.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            deviations: Vec::new(),
        }
    }

    /// Add a deviation to the store.
    ///
    /// # Errors
    ///
    /// - [`DeviationAddError::EmptyField`] if `deviation.justification` or
    ///   `deviation.authorized_by` is empty.
    /// - [`DeviationAddError::DuplicateId`] if a deviation with the same
    ///   `id` already exists in the store.
    pub fn add(&mut self, mut deviation: Deviation) -> Result<(), DeviationAddError> {
        if deviation.justification.is_empty() {
            return Err(DeviationAddError::EmptyField("justification".into()));
        }
        if deviation.authorized_by.is_empty() {
            return Err(DeviationAddError::EmptyField("authorized_by".into()));
        }
        if self.deviations.iter().any(|d| d.id == deviation.id) {
            return Err(DeviationAddError::DuplicateId(deviation.id.clone()));
        }
        // Normalize IssuerDnContains substrings to lowercase at insertion time
        // so that matching logic does not need to re-normalize on every call.
        // This prevents a silent no-match when callers pass mixed-case strings.
        // Use make_ascii_lowercase (in-place, no allocation) consistent with
        // the matching code in DeviationScope::matches.
        if let DeviationScope::IssuerDnContains(s) = &mut deviation.scope {
            s.make_ascii_lowercase();
        }
        self.deviations.push(deviation);
        Ok(())
    }

    /// Return all deviations in the store.
    #[must_use]
    pub fn all(&self) -> &[Deviation] {
        &self.deviations
    }

    /// Return all deviations that are active at `now_unix`.
    #[must_use = "iterator is lazy; collect or iterate to use results"]
    pub fn active_at(&self, now_unix: u64) -> impl Iterator<Item = &Deviation> {
        self.deviations
            .iter()
            .filter(move |d| d.is_active_at(now_unix))
    }

    /// Return all deviations targeting `lint_id` that are active at `now_unix`.
    #[must_use = "iterator is lazy; collect or iterate to use results"]
    pub fn active_for_lint<'a>(
        &'a self,
        lint_id: &'a str,
        now_unix: u64,
    ) -> impl Iterator<Item = &'a Deviation> {
        self.deviations
            .iter()
            .filter(move |d| d.target_lint.as_str() == lint_id && d.is_active_at(now_unix))
    }

    /// Return all deviations that have expired as of `now_unix`.
    ///
    /// Used by corpus-reporting tools to surface deviations that need renewal.
    #[must_use = "iterator is lazy; collect or iterate to use results"]
    pub fn expired_at(&self, now_unix: u64) -> impl Iterator<Item = &Deviation> {
        self.deviations
            .iter()
            .filter(move |d| d.effective_end.is_some_and(|end| now_unix >= end))
    }

    /// Check whether a specific finding should be deviated.
    ///
    /// Returns the first active deviation that matches `cert` and `lint_id` at
    /// `now_unix`, or `None` if no deviation applies.
    ///
    /// In the case of multiple matching deviations, the first one added to the
    /// store wins. Deviations should be scoped to avoid unintentional overlap.
    #[must_use]
    pub fn find_deviation(
        &self,
        lint_id: &str,
        cert: &Certificate,
        now_unix: u64,
    ) -> Option<&Deviation> {
        self.deviations
            .iter()
            .find(|d| d.target_lint.as_str() == lint_id && d.applies_to(cert, now_unix))
    }
}

// ---------------------------------------------------------------------------
// DeviationRunner
// ---------------------------------------------------------------------------

/// The output of a [`DeviationRunner`] evaluation: findings with deviations applied.
///
/// Findings where a deviation was applied are moved from `findings` to `deviated`.
/// Callers can use `findings` for normal compliance reporting and `deviated`
/// for audit/transparency reporting.
///
/// # Stability
///
/// This struct is `#[non_exhaustive]`: new fields may be added in future minor
/// versions (e.g., a `suppressed` list for audit purposes). Do not construct
/// `DeviationRunResult` directly with struct literal syntax; use
/// [`DeviationRunResult::default()`] or obtain it from [`DeviationRunner`].
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviationRunResult {
    /// Findings that were not affected by any deviation.
    ///
    /// Contains the full output of the inner [`crate::LintRunner`] minus any
    /// findings that were moved to [`Self::deviated`]. This includes
    /// [`crate::LintResult::Pass`] and [`crate::LintResult::NotApplicable`]
    /// findings as well as actionable ones — mirroring the behaviour of
    /// [`crate::LintRunner::run_cert`]. Callers that want only actionable
    /// results should filter with [`crate::Finding::is_finding`].
    pub findings: Vec<crate::Finding>,

    /// Findings that had a deviation applied.
    ///
    /// These are always included in output (never silently hidden) so that
    /// auditors can see what was deviated and why. If `action` is
    /// [`DeviationAction::Suppress`], `effective_severity()` returns `None`;
    /// the caller can display these with a "DEVIATION APPLIED" tag rather than
    /// as normal findings.
    pub deviated: Vec<DeviatedFinding>,
}

/// A lint runner that applies [`DeviationStore`] logic to findings.
///
/// `DeviationRunner` wraps a [`crate::LintRunner`] and a [`DeviationStore`].
/// After each lint evaluation, it checks whether a deviation applies to the
/// finding. If one does, the finding is moved to [`DeviationRunResult::deviated`];
/// otherwise it stays in [`DeviationRunResult::findings`].
///
/// # Transparency guarantee
///
/// `DeviationRunner` **never silently drops findings**. Every finding — including
/// deviated ones — appears in [`DeviationRunResult`]. Operators see what was
/// deviated; auditors can enumerate deviations via [`DeviationStore::all`].
///
/// # Usage
///
/// ```rust,no_run
/// // `cert` and `now_unix` are obtained from the calling context.
/// use pkix_lint::deviation::{DeviationRunner, DeviationStore};
/// use pkix_lint::{LintRunner, SubjectKind};
/// use x509_cert::Certificate;
///
/// let cert: Certificate = unimplemented!("load from DER");
/// let now_unix: u64 = unimplemented!("current Unix epoch seconds");
/// let store = DeviationStore::new(); // populate with operator deviations
/// let runner = LintRunner::new(vec![/* your lints */]);
/// let dev_runner = DeviationRunner::new(runner, store);
///
/// let result = dev_runner.run_cert(&cert, SubjectKind::Leaf, 0, now_unix);
/// // result.findings — normal findings
/// // result.deviated — deviated findings (always included for auditability)
/// ```
pub struct DeviationRunner {
    runner: crate::LintRunner,
    store: DeviationStore,
}

impl DeviationRunner {
    /// Create a new deviation runner from a lint runner and a deviation store.
    #[must_use]
    pub const fn new(runner: crate::LintRunner, store: DeviationStore) -> Self {
        Self { runner, store }
    }

    /// Return a reference to the inner [`crate::LintRunner`].
    #[must_use]
    pub const fn lint_runner(&self) -> &crate::LintRunner {
        &self.runner
    }

    /// Return a reference to the [`DeviationStore`].
    #[must_use]
    pub const fn deviation_store(&self) -> &DeviationStore {
        &self.store
    }

    /// Evaluate certificate-scope lints and apply deviations.
    ///
    /// Same semantics as [`crate::LintRunner::run_cert`], but findings are
    /// partitioned into `findings` (no deviation) and `deviated` (deviation applied).
    #[must_use]
    pub fn run_cert(
        &self,
        cert: &Certificate,
        kind: crate::SubjectKind,
        cert_index: usize,
        now_unix: u64,
    ) -> DeviationRunResult {
        let raw = self.runner.run_cert(cert, kind, cert_index, now_unix);
        self.apply_deviations(raw, cert, now_unix)
    }

    /// Evaluate certificate-scope lints as of the cert's `notBefore` date and
    /// apply deviations.
    ///
    /// Mirrors [`crate::LintRunner::run_cert_at_issuance`]: extracts the
    /// `notBefore` timestamp and calls `run_cert` with that value as `now_unix`.
    /// This answers "was this cert compliant when it was issued?"
    #[must_use]
    pub fn run_cert_at_issuance(
        &self,
        cert: &Certificate,
        kind: crate::SubjectKind,
        cert_index: usize,
    ) -> DeviationRunResult {
        let issuance_unix = cert
            .tbs_certificate
            .validity
            .not_before
            .to_unix_duration()
            .as_secs();
        self.run_cert(cert, kind, cert_index, issuance_unix)
    }

    /// Evaluate certificate-scope lints on every cert in `chain` and apply deviations.
    ///
    /// `kinds` maps chain index to [`crate::SubjectKind`]. If `kinds` is shorter than
    /// `chain`, remaining certificates are treated as [`crate::SubjectKind::IntermediateCa`].
    #[must_use]
    pub fn run_chain(
        &self,
        chain: &[Certificate],
        kinds: &[crate::SubjectKind],
        now_unix: u64,
    ) -> DeviationRunResult {
        let mut result = DeviationRunResult::default();
        for (i, cert) in chain.iter().enumerate() {
            let kind = kinds
                .get(i)
                .copied()
                .unwrap_or(crate::SubjectKind::IntermediateCa);
            let raw = self.runner.run_cert(cert, kind, i, now_unix);
            let partial = self.apply_deviations(raw, cert, now_unix);
            result.findings.extend(partial.findings);
            result.deviated.extend(partial.deviated);
        }
        result
    }

    /// Evaluate path-scope lints and apply deviations.
    ///
    /// For path-scope lints, scope matching uses the leaf certificate (`chain[0]`).
    ///
    /// # Limitations
    ///
    /// Path-scope deviation matching always uses the leaf certificate (`chain[0]`)
    /// for scope evaluation. [`DeviationScope::IssuerDnExact`] and
    /// [`DeviationScope::SerialRange`] must reference the leaf certificate's
    /// issuer DN — deviations scoped to an intermediate CA's DN will not match.
    #[must_use]
    pub fn run_path(
        &self,
        chain: &[Certificate],
        path: &crate::ValidatedPath,
        now_unix: u64,
    ) -> DeviationRunResult {
        let raw = self.runner.run_path(chain, path, now_unix);
        // Use the leaf cert for scope matching on path-level deviations.
        // If the chain is empty (shouldn't happen after validate_path), fall
        // back to no scope matching (treat as Any).
        match chain.first() {
            Some(leaf) => self.apply_deviations(raw, leaf, now_unix),
            None => DeviationRunResult {
                findings: raw,
                deviated: vec![],
            },
        }
    }

    /// Internal: partition a `Vec<Finding>` by whether a deviation applies.
    fn apply_deviations(
        &self,
        raw: Vec<crate::Finding>,
        cert: &Certificate,
        now_unix: u64,
    ) -> DeviationRunResult {
        let mut result = DeviationRunResult::default();
        for finding in raw {
            // Only attempt to apply deviations to actionable findings.
            // Pass and NotApplicable findings are never waived.
            if !finding.result.is_finding() {
                result.findings.push(finding);
                continue;
            }
            match self.store.find_deviation(&finding.lint_id, cert, now_unix) {
                None => {
                    result.findings.push(finding);
                }
                Some(dev) => {
                    result.deviated.push(DeviatedFinding {
                        lint_id: finding.lint_id,
                        citation: finding.citation,
                        original_result: finding.result,
                        deviation_id: dev.id.clone(),
                        action: dev.action.clone(),
                        justification: dev.justification.clone(),
                        evidence_uri: dev.evidence_uri.clone(),
                        cert_index: finding.cert_index,
                        evaluated_at_unix: finding.evaluated_at_unix,
                    });
                }
            }
        }
        result
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn make_deviation(id: &str, lint_id: &str) -> Deviation {
        Deviation {
            id: id.to_string(),
            target_lint: lint_id.to_string(),
            scope: DeviationScope::Any,
            effective_start: None,
            effective_end: None,
            action: DeviationAction::DowngradeSeverityTo(Severity::Info),
            justification: "test justification".to_string(),
            authorized_by: "test-author@example.com".to_string(),
            evidence_uri: None,
        }
    }

    fn load_cert() -> Certificate {
        use der::Decode as _;
        Certificate::from_der(include_bytes!(
            "../../pkix-path/tests/fixtures/policy-checks/webpki-self-signed-365d.der"
        ))
        .expect("fixture is valid DER")
    }

    // -----------------------------------------------------------------------
    // is_active_at tests
    // Oracle: the time-range semantics in Deviation::is_active_at doc comment.
    // -----------------------------------------------------------------------

    #[test]
    fn deviation_active_at_no_bounds() {
        let d = make_deviation("d1", "test.lint");
        // No bounds: always active.
        assert!(d.is_active_at(0));
        assert!(d.is_active_at(u64::MAX));
    }

    #[test]
    fn deviation_active_after_start() {
        let d = Deviation {
            effective_start: Some(100),
            effective_end: None,
            ..make_deviation("d2", "test.lint")
        };
        assert!(!d.is_active_at(99), "before start must not be active");
        assert!(d.is_active_at(100), "at start must be active");
        assert!(d.is_active_at(200), "after start must be active");
    }

    #[test]
    fn deviation_expires_at_end() {
        let d = Deviation {
            effective_start: None,
            effective_end: Some(200),
            ..make_deviation("d3", "test.lint")
        };
        assert!(d.is_active_at(199), "before end must be active");
        assert!(
            !d.is_active_at(200),
            "at end must NOT be active (exclusive)"
        );
        assert!(!d.is_active_at(201), "after end must not be active");
    }

    #[test]
    fn deviation_active_within_range() {
        let d = Deviation {
            effective_start: Some(100),
            effective_end: Some(200),
            ..make_deviation("d4", "test.lint")
        };
        assert!(!d.is_active_at(99));
        assert!(d.is_active_at(100));
        assert!(d.is_active_at(150));
        assert!(d.is_active_at(199));
        assert!(!d.is_active_at(200));
    }

    // -----------------------------------------------------------------------
    // DeviationScope::matches tests
    // Oracle: the scope-matching rules in the DeviationScope doc comment.
    // -----------------------------------------------------------------------

    #[test]
    fn scope_any_matches_any_cert() {
        let cert = load_cert();
        assert!(DeviationScope::Any.matches(&cert));
    }

    #[test]
    fn scope_issuer_dn_contains_case_insensitive() {
        let cert = load_cert();
        // The webpki-self-signed-365d cert has a CN we can match.
        // Get the issuer string to find what's in it.
        let issuer = cert.tbs_certificate.issuer.to_string();
        // Take the first word of the issuer for a partial match.
        let word = issuer.split_whitespace().next().unwrap_or("cert");
        // IssuerDnContains requires a pre-lowercased substring; the match
        // is case-insensitive because the cert's issuer string is lowercased
        // at match time. Both lowercase and originally-cased input must match
        // once lowercased at construction.
        let scope_lower = DeviationScope::IssuerDnContains(word.to_lowercase());
        let scope_upper = DeviationScope::IssuerDnContains(word.to_uppercase().to_lowercase());
        assert!(scope_lower.matches(&cert), "lowercase match must succeed");
        assert!(
            scope_upper.matches(&cert),
            "lowercased-at-construction match must succeed"
        );
    }

    #[test]
    fn scope_issuer_dn_contains_no_match() {
        let cert = load_cert();
        let scope = DeviationScope::IssuerDnContains("XYZ_NONEXISTENT_ISSUER_9999".to_string());
        assert!(!scope.matches(&cert));
    }

    /// `DeviationStore::add` normalizes `IssuerDnContains` to lowercase so that
    /// callers who pass a mixed-case substring get a working deviation rather than
    /// a silently inactive one.
    #[test]
    fn deviation_store_add_normalizes_issuer_dn_contains_to_lowercase() {
        let cert = load_cert();
        let issuer = cert.tbs_certificate.issuer.to_string();
        let word = issuer
            .split(|c: char| !c.is_alphanumeric())
            .find(|w| !w.is_empty())
            .unwrap_or("test");
        let uppercase_word = word.to_uppercase();

        // Only run the assertion when the word has a meaningful uppercase form.
        if uppercase_word == word.to_lowercase() {
            return;
        }

        // Add a deviation whose scope uses an UPPERCASE substring.
        let mut store = DeviationStore::new();
        let deviation = Deviation {
            scope: DeviationScope::IssuerDnContains(uppercase_word.clone()),
            ..make_deviation("norm-test", "test.lint")
        };
        store.add(deviation).expect("add must succeed");

        // The stored substring must have been normalized to lowercase.
        match &store.all()[0].scope {
            DeviationScope::IssuerDnContains(s) => {
                assert_eq!(
                    *s,
                    uppercase_word.to_lowercase(),
                    "DeviationStore::add must lowercase IssuerDnContains substring"
                );
            }
            other => panic!("expected IssuerDnContains, got {other:?}"),
        }

        // And the normalized deviation must match the cert.
        assert!(
            store.all()[0].scope.matches(&cert),
            "normalized IssuerDnContains must match cert"
        );
    }

    // -----------------------------------------------------------------------
    // IssuerDnExact scope tests
    //
    // Oracle: IssuerDnExact uses pkix_path::names_match (RFC 4518 normalization).
    // A cert's issuer DN must match the stored DN via that same function.
    // -----------------------------------------------------------------------

    #[test]
    fn scope_issuer_dn_exact_matches_cert_issuer() {
        let cert = load_cert();
        // Use the cert's own issuer DN as the exact match — must succeed.
        let scope = DeviationScope::IssuerDnExact(cert.tbs_certificate.issuer.clone());
        assert!(
            scope.matches(&cert),
            "IssuerDnExact with cert's own issuer must match"
        );
    }

    #[test]
    fn scope_issuer_dn_exact_does_not_match_different_dn() {
        use der::Decode as _;
        let cert = load_cert();
        // Use the cert's subject DN as the "issuer" — for a self-signed cert subject==issuer,
        // so use a different cert's issuer if available. Since we only have one fixture
        // that is self-signed (subject == issuer), we test non-match by constructing
        // an IssuerDnExact with a DIFFERENT cert's issuer.
        //
        // Load the smime fixture (different cert, different DN).
        let other_cert = Certificate::from_der(include_bytes!(
            "../../pkix-path/tests/fixtures/policy-checks/smime-self-signed-365d.der"
        ))
        .expect("fixture is valid DER");
        // Use smime cert's issuer as the scope — should not match the webpki cert.
        let scope = DeviationScope::IssuerDnExact(other_cert.tbs_certificate.issuer.clone());
        // If both certs have the same issuer DN, the test is vacuous. Check first.
        let same = pkix_path::names_match(
            &cert.tbs_certificate.issuer,
            &other_cert.tbs_certificate.issuer,
        );
        if !same {
            assert!(
                !scope.matches(&cert),
                "IssuerDnExact with different issuer must not match"
            );
        }
        // If same (both self-signed with identical DNs), the test passes vacuously —
        // the fixtures happen to have the same issuer, and that's acceptable.
    }

    // -----------------------------------------------------------------------
    // SerialRange scope tests
    //
    // Oracle: serial_cmp implements DER positive integer comparison.
    // Boundary conditions are tested independently of the cert fixture.
    // -----------------------------------------------------------------------

    #[test]
    fn serial_cmp_greater() {
        use core::cmp::Ordering;
        // 0x02 > 0x01
        assert_eq!(serial_cmp(&[0x02], &[0x01]), Ordering::Greater);
        // longer byte sequence (more digits) is larger
        assert_eq!(serial_cmp(&[0x01, 0x00], &[0xFF]), Ordering::Greater);
    }

    #[test]
    fn serial_cmp_less() {
        use core::cmp::Ordering;
        // 0x01 < 0x02
        assert_eq!(serial_cmp(&[0x01], &[0x02]), Ordering::Less);
        // shorter (after strip) is smaller
        assert_eq!(serial_cmp(&[0xFF], &[0x01, 0x00]), Ordering::Less);
    }

    #[test]
    fn serial_cmp_equal() {
        use core::cmp::Ordering;
        // identical
        assert_eq!(serial_cmp(&[0x05], &[0x05]), Ordering::Equal);
    }

    #[test]
    fn serial_cmp_leading_zeros_stripped() {
        use core::cmp::Ordering;
        // 0x00 0x01 = 1, 0x01 = 1 — equal after stripping leading zero on a.
        assert_eq!(serial_cmp(&[0x00, 0x01], &[0x01]), Ordering::Equal);
        // is_ge / is_le on Equal are both true (matches old serial_lex_{ge,le} behavior).
        assert!(serial_cmp(&[0x00, 0x01], &[0x01]).is_ge());
        assert!(serial_cmp(&[0x00, 0x01], &[0x01]).is_le());
    }

    #[test]
    fn scope_serial_range_matches_cert_in_range() {
        let cert = load_cert();
        let serial = cert.tbs_certificate.serial_number.as_bytes().to_vec();
        // Range is [serial, serial] — cert's own serial, must match.
        let scope = DeviationScope::SerialRange {
            issuer: cert.tbs_certificate.issuer.clone(),
            start: serial.clone(),
            end: serial,
        };
        assert!(
            scope.matches(&cert),
            "cert's own serial must be within [serial, serial]"
        );
    }

    #[test]
    fn scope_serial_range_excludes_cert_outside_range() {
        let cert = load_cert();
        let serial = cert.tbs_certificate.serial_number.as_bytes();
        // Range is [serial+1, serial+2] — cert's serial is below, must not match.
        // Construct a start that is definitely higher: 0xFF repeated.
        let start = vec![0xFF; serial.len() + 1]; // much larger than any fixed serial
        let end = vec![0xFF; serial.len() + 2];
        let scope = DeviationScope::SerialRange {
            issuer: cert.tbs_certificate.issuer.clone(),
            start,
            end,
        };
        assert!(
            !scope.matches(&cert),
            "cert serial below range start must not match"
        );
    }

    #[test]
    fn scope_serial_range_wrong_issuer_no_match() {
        use der::Decode as _;
        let cert = load_cert();
        let other_cert = Certificate::from_der(include_bytes!(
            "../../pkix-path/tests/fixtures/policy-checks/smime-self-signed-365d.der"
        ))
        .expect("fixture is valid DER");
        let serial = cert.tbs_certificate.serial_number.as_bytes().to_vec();
        // Use the other cert's issuer — should not match cert.
        let scope = DeviationScope::SerialRange {
            issuer: other_cert.tbs_certificate.issuer.clone(),
            start: vec![0x00],
            end: vec![0xFF; serial.len() + 2], // large enough to include any serial
        };
        let same_issuer = pkix_path::names_match(
            &cert.tbs_certificate.issuer,
            &other_cert.tbs_certificate.issuer,
        );
        if !same_issuer {
            assert!(
                !scope.matches(&cert),
                "wrong issuer in SerialRange must not match"
            );
        }
    }

    // -----------------------------------------------------------------------
    // DeviationStore tests
    // Oracle: the store contract in DeviationStore doc comments.
    // -----------------------------------------------------------------------

    #[test]
    fn store_add_and_retrieve() {
        let mut store = DeviationStore::new();
        store
            .add(make_deviation("d1", "test.lint.a"))
            .expect("add should succeed");
        store
            .add(make_deviation("d2", "test.lint.b"))
            .expect("add should succeed");
        assert_eq!(store.all().len(), 2);
    }

    #[test]
    fn store_rejects_empty_justification() {
        let mut store = DeviationStore::new();
        let result = store.add(Deviation {
            justification: String::new(),
            ..make_deviation("d1", "test.lint")
        });
        assert_eq!(
            result,
            Err(DeviationAddError::EmptyField("justification".into())),
            "empty justification must return EmptyField error"
        );
    }

    #[test]
    fn store_rejects_empty_authorized_by() {
        let mut store = DeviationStore::new();
        let result = store.add(Deviation {
            authorized_by: String::new(),
            ..make_deviation("d1", "test.lint")
        });
        assert_eq!(
            result,
            Err(DeviationAddError::EmptyField("authorized_by".into())),
            "empty authorized_by must return EmptyField error"
        );
    }

    #[test]
    fn store_rejects_duplicate_id() {
        let mut store = DeviationStore::new();
        store
            .add(make_deviation("d1", "test.lint.a"))
            .expect("first add should succeed");
        let result = store.add(make_deviation("d1", "test.lint.b")); // same id → error
        assert!(result.is_err(), "duplicate id must return Err");
        assert_eq!(
            result.unwrap_err(),
            DeviationAddError::DuplicateId("d1".to_string())
        );
    }

    #[test]
    fn store_find_deviation_matches() {
        let cert = load_cert();
        let now: u64 = 1_000_000;
        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                effective_start: None,
                effective_end: None,
                ..make_deviation("d1", "test.lint.a")
            })
            .expect("add should succeed");
        let found = store.find_deviation("test.lint.a", &cert, now);
        assert!(found.is_some());
        assert_eq!(found.unwrap().id, "d1");
    }

    #[test]
    fn store_find_deviation_no_match_wrong_lint() {
        let cert = load_cert();
        let now: u64 = 1_000_000;
        let mut store = DeviationStore::new();
        store
            .add(make_deviation("d1", "test.lint.a"))
            .expect("add should succeed");
        assert!(store.find_deviation("test.lint.b", &cert, now).is_none());
    }

    #[test]
    fn store_find_deviation_expired_not_matched() {
        let cert = load_cert();
        let now: u64 = 1_000;
        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                effective_end: Some(500), // expired at 500
                ..make_deviation("d1", "test.lint.a")
            })
            .expect("add should succeed");
        // At now=1000, the deviation has expired.
        assert!(store.find_deviation("test.lint.a", &cert, now).is_none());
    }

    #[test]
    fn store_expired_at_reports_expired_deviations() {
        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                effective_end: Some(500),
                ..make_deviation("d1", "test.lint.a")
            })
            .expect("add should succeed");
        store
            .add(Deviation {
                effective_end: None, // never expires
                ..make_deviation("d2", "test.lint.b")
            })
            .expect("add should succeed");
        let expired: Vec<_> = store.expired_at(1000).collect();
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0].id, "d1");
    }

    #[test]
    fn deviated_finding_effective_severity() {
        let f = DeviatedFinding {
            lint_id: std::borrow::Cow::Borrowed("test.lint"),
            citation: std::borrow::Cow::Borrowed("test citation"),
            original_result: LintResult::Error("original"),
            deviation_id: "d1".to_string(),
            action: DeviationAction::DowngradeSeverityTo(Severity::Info),
            justification: "test justification".to_string(),
            evidence_uri: None,
            cert_index: None,
            evaluated_at_unix: 0,
        };
        assert_eq!(f.effective_severity(), Some(Severity::Info));

        let f2 = DeviatedFinding {
            action: DeviationAction::Suppress,
            ..f
        };
        assert_eq!(f2.effective_severity(), None);
    }

    // -----------------------------------------------------------------------
    // DeviationRunner tests
    // Oracle: DeviationRunner contract from doc comments.
    // -----------------------------------------------------------------------

    /// A lint that always returns Error — used to test deviation application.
    struct AlwaysError;
    impl crate::Lint for AlwaysError {
        fn id(&self) -> &'static str {
            "test.always_error"
        }
        fn citation(&self) -> &'static str {
            "test"
        }
        fn severity(&self) -> crate::Severity {
            crate::Severity::Error
        }
        fn scope(&self) -> crate::Scope {
            crate::Scope::Certificate
        }
        fn applies_to(&self) -> crate::SubjectKind {
            crate::SubjectKind::Any
        }
        fn check_cert(
            &self,
            _cert: &Certificate,
            _kind: crate::SubjectKind,
            _now: u64,
        ) -> crate::LintResult {
            crate::LintResult::Error("always errors")
        }
    }

    /// A lint that always passes — used to verify non-deviated findings stay in findings.
    struct AlwaysPass;
    impl crate::Lint for AlwaysPass {
        fn id(&self) -> &'static str {
            "test.always_pass"
        }
        fn citation(&self) -> &'static str {
            "test"
        }
        fn severity(&self) -> crate::Severity {
            crate::Severity::Info
        }
        fn scope(&self) -> crate::Scope {
            crate::Scope::Certificate
        }
        fn applies_to(&self) -> crate::SubjectKind {
            crate::SubjectKind::Any
        }
        fn check_cert(
            &self,
            _cert: &Certificate,
            _kind: crate::SubjectKind,
            _now: u64,
        ) -> crate::LintResult {
            crate::LintResult::Pass
        }
    }

    #[test]
    fn deviation_runner_moves_deviated_finding_to_deviated() {
        let cert = load_cert();
        let now: u64 = 1_000_000;

        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                target_lint: "test.always_error".to_string(),
                ..make_deviation("d1", "test.always_error")
            })
            .expect("add should succeed");

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysError)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        // The error finding must be deviated, not in normal findings.
        assert!(
            result.findings.is_empty(),
            "deviated finding must not be in findings"
        );
        assert_eq!(
            result.deviated.len(),
            1,
            "deviated finding must be in deviated"
        );
        assert_eq!(result.deviated[0].lint_id, "test.always_error");
        assert_eq!(result.deviated[0].deviation_id, "d1");
        // Original result is preserved.
        assert!(matches!(
            result.deviated[0].original_result,
            crate::LintResult::Error(_)
        ));
    }

    #[test]
    fn deviation_runner_non_deviated_finding_stays_in_findings() {
        let cert = load_cert();
        let now: u64 = 1_000_000;

        // Deviation targets a different lint than what we're running.
        let mut store = DeviationStore::new();
        store
            .add(make_deviation("d1", "test.different_lint"))
            .expect("add should succeed");

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysPass)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        // Pass finding not matched by deviation: stays in findings.
        assert_eq!(result.findings.len(), 1);
        assert!(result.deviated.is_empty());
    }

    #[test]
    fn deviation_runner_expired_deviation_does_not_apply() {
        let cert = load_cert();
        let now: u64 = 2_000_000;

        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                effective_end: Some(1_000_000), // expired before now
                ..make_deviation("d1", "test.always_error")
            })
            .expect("add should succeed");

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysError)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        // Expired deviation: error finding stays in findings (not deviated).
        assert_eq!(result.findings.len(), 1);
        assert!(result.deviated.is_empty());
    }

    #[test]
    fn deviation_runner_suppress_action_sets_effective_severity_none() {
        let cert = load_cert();
        let now: u64 = 1_000_000;

        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                action: DeviationAction::Suppress,
                ..make_deviation("d1", "test.always_error")
            })
            .expect("add should succeed");

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysError)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        assert!(result.findings.is_empty());
        assert_eq!(result.deviated.len(), 1);
        // Suppressed findings have no effective severity.
        assert_eq!(result.deviated[0].effective_severity(), None);
    }

    /// `evidence_uri` flows from Deviation through to `DeviatedFinding`.
    ///
    /// Oracle: `DeviatedFinding.evidence_uri` must equal `Deviation.evidence_uri`.
    /// This is the field operators use to navigate to the waiver document.
    #[test]
    fn evidence_uri_flows_to_deviated_finding() {
        let cert = load_cert();
        let now: u64 = 1_000_000;
        let uri = "https://pkipolicy.agency.gov/waivers/2025-11-03";

        let mut store = DeviationStore::new();
        store
            .add(Deviation {
                evidence_uri: Some(uri.to_string()),
                ..make_deviation("d1", "test.always_error")
            })
            .expect("add should succeed");

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysError)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        assert_eq!(result.deviated.len(), 1);
        assert_eq!(
            result.deviated[0].evidence_uri.as_deref(),
            Some(uri),
            "evidence_uri must flow from Deviation to DeviatedFinding"
        );
        // justification also flows through.
        assert_eq!(result.deviated[0].justification, "test justification");
    }

    /// When `evidence_uri` is None, `DeviatedFinding.evidence_uri` is None.
    #[test]
    fn evidence_uri_none_when_deviation_has_no_uri() {
        let cert = load_cert();
        let now: u64 = 1_000_000;

        let mut store = DeviationStore::new();
        store
            .add(make_deviation("d1", "test.always_error"))
            .expect("add should succeed"); // evidence_uri: None

        let runner = crate::LintRunner::new(vec![Box::new(AlwaysError)]);
        let dev_runner = DeviationRunner::new(runner, store);
        let result = dev_runner.run_cert(&cert, crate::SubjectKind::Leaf, 0, now);

        assert_eq!(result.deviated.len(), 1);
        assert_eq!(result.deviated[0].evidence_uri, None);
    }
}