pkix-lint 0.9.1

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
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
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
//! OSCAL Profile composition for pkix-lint.
//!
//! Implements OSCAL Profile resolution semantics — `import` references,
//! `include-controls` / `exclude-controls` filters, and
//! `modify.set-parameters` overrides — for callers who choose OSCAL
//! Profile JSON as their lint-bundle composition format. OSCAL Profile
//! semantics are one supported way to compose pkix-lint bundles, not the
//! mandated workspace mechanism: callers can equally compose bundles
//! directly via [`crate::LintRunner::filter_to_ids`] and
//! [`crate::LintRunner::apply_parameter_overrides`] without ever
//! producing an OSCAL document. See `pkix-lint/src/oscal/mod.rs` for the
//! framing.
//!
//! This module is the resolver. Given an OSCAL Profile
//! [`serde_json::Value`] and a `sources` map of referenced Catalogs
//! and Profiles, [`resolve_profile`] produces a [`ResolvedProfile`]
//! whose `control_ids` plug into [`crate::LintRunner::filter_to_ids`]
//! and whose `parameter_overrides` plug into
//! [`crate::LintRunner::apply_parameter_overrides`].
//!
//! # Composition examples
//!
//! Three composition shapes are supported (and pinned by tests in this
//! module):
//!
//! 1. **Plain Profile** — a Profile imports one Catalog and selects a
//!    subset of Controls.
//! 2. **Layered Profile** — a Profile imports several Catalogs (or
//!    Catalogs + a transitively-imported Profile), each with their own
//!    include/exclude filters, then layers `set-parameters` overrides on
//!    top.
//! 3. **Override Profile** — a Profile imports another Profile (which
//!    already imports a Catalog), inheriting its selections and adding
//!    targeted `exclude-controls` to disable specific Controls or
//!    additional `set-parameters` to tighten parameter values.
//!
//! # `import.href` resolution
//!
//! Each `imports[].href` is matched verbatim against the keys of the
//! `sources` map. Callers may use any href scheme they like — local
//! fragment identifiers (`"#rs.pkix.rfc5280"`), URIs
//! (`"file:///etc/pkix-lint/catalogs/rfc5280.json"`), or stable opaque
//! strings — provided the same string keys the corresponding entry in
//! `sources`. The resolver does not perform any I/O.
//!
//! # Cycle detection
//!
//! Profile-imports-Profile chains are walked recursively. The resolver
//! tracks the set of hrefs currently on the import stack and returns
//! [`ParseError::ProfileImportCycle`] if an import would revisit one,
//! preserving the offending href for the operator.
//!
//! # OSCAL Profile shape accepted
//!
//! The parser is intentionally narrow — it implements the directives
//! named in the PKIX-9vnx.7 acceptance criteria and the subset of the
//! OSCAL Profile model `pkix-lint` needs. Specifically:
//!
//! * `profile.imports[].href` — required string, looked up in `sources`.
//! * `profile.imports[].include-all` — when present (as `{}`), every
//!   Control id in the imported source is included before exclude
//!   filters apply.
//! * `profile.imports[].include-controls[].with-ids[]` — explicit ids to
//!   include. Multiple `include-controls` entries are unioned.
//! * `profile.imports[].exclude-controls[].with-ids[]` — explicit ids
//!   to drop *after* include filters. Multiple `exclude-controls` entries
//!   are unioned.
//! * `profile.modify.set-parameters[].param-id` and `values[0]` —
//!   parameter overrides addressed by the composite param id
//!   ([`crate::oscal::catalog`] emits Catalog Parameters with the
//!   composite id `<lint_id>.<param_id>`; Profile `modify.set-parameters`
//!   must reference that same id).
//!
//! Other OSCAL Profile fields (`merge.combine`, `modify.alters`,
//! `back-matter`, custom `merge.custom`) are not interpreted. Profiles
//! that rely on them must either drop those directives or compose them
//! with an external OSCAL toolchain first.
//!
//! # Provenance
//!
//! Added in PKIX-9vnx.7. Subsumes the scope of PKIX-9vnx.6.5 (the
//! standalone parameter-overrides extractor) — `set-parameters` is
//! handled here as part of the broader Profile-resolution flow.

use std::collections::{HashMap, HashSet};

use serde_json::Value;

use super::parse::{lint_ids_from_catalog, ParseError};

/// Output of [`resolve_profile`]: the ordered list of Control ids the
/// composed Profile selects, plus the parameter overrides it carries.
///
/// `control_ids` is in document order across imports, with duplicates
/// removed (first occurrence wins). `parameter_overrides` is in the
/// order the `modify.set-parameters` directives appear in the Profile,
/// after recursive resolution of imports — inner Profile overrides
/// precede outer Profile overrides, so an outer Profile that sets the
/// same parameter takes effect last.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResolvedProfile {
    /// Ordered set of OSCAL Control ids selected by the Profile.
    pub control_ids: Vec<String>,
    /// Parameter overrides extracted from `modify.set-parameters`
    /// directives, in resolution order.
    pub parameter_overrides: Vec<ParameterOverride>,
}

impl ResolvedProfile {
    /// Construct a [`ResolvedProfile`] with the listed control ids and
    /// parameter overrides.
    ///
    /// Use this constructor instead of struct-literal syntax so future
    /// fields (the OSCAL Profile model carries `merge.combine`,
    /// `modify.alters`, `back-matter` that are not interpreted today
    /// per this crate's rustdoc) remain non-breaking additions. The
    /// struct carries `#[non_exhaustive]`.
    #[must_use]
    pub fn new(control_ids: Vec<String>, parameter_overrides: Vec<ParameterOverride>) -> Self {
        Self {
            control_ids,
            parameter_overrides,
        }
    }
}

/// A single OSCAL `set-parameter` directive resolved against a Catalog.
///
/// `param_id` is the composite OSCAL Parameter id
/// (`<lint_id>.<param_id>`) emitted by
/// [`crate::oscal::catalog::catalog_from_lints`]. `value` is the first
/// entry of the directive's `values` array.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParameterOverride {
    /// Composite OSCAL Parameter id (`<lint_id>.<param_id>`).
    pub param_id: String,
    /// Override value, rendered as a string per the OSCAL Parameter
    /// model.
    pub value: String,
}

impl ParameterOverride {
    /// Construct a [`ParameterOverride`].
    ///
    /// Use this constructor instead of struct-literal syntax so future
    /// fields (the OSCAL Parameter model carries `constraint`,
    /// `guideline`, `select`, `link` shape mentioned in the
    /// [`crate::LintParameter`] rustdoc) remain non-breaking additions.
    /// The struct carries `#[non_exhaustive]`.
    #[must_use]
    pub fn new(param_id: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            param_id: param_id.into(),
            value: value.into(),
        }
    }
}

/// Resolve an OSCAL Profile [`Value`] into a flat list of selected
/// Control ids plus parameter overrides.
///
/// `profile` is the top-level OSCAL Profile JSON value (a JSON object
/// whose only top-level key is `"profile"`). `sources` maps every href
/// referenced transitively by the Profile to its source [`Value`],
/// which must itself be either an OSCAL Catalog
/// (`{"catalog": {...}}`) or another OSCAL Profile
/// (`{"profile": {...}}`).
///
/// # Errors
///
/// * [`ParseError::ProfileNotObject`] — the top-level value is not a
///   JSON object.
/// * [`ParseError::ProfileMissingWrapper`] — the required `profile`
///   key is absent or not an object.
/// * [`ParseError::ProfileImportsNotArray`] — `profile.imports` is
///   missing or not an array.
/// * [`ParseError::ProfileImportMissingHref`] / `ProfileImportHrefNotString`
///   — an import is missing its `href` or has a non-string href.
/// * [`ParseError::ProfileImportUnresolved`] — an import's href has no
///   entry in `sources`.
/// * [`ParseError::ProfileImportCycle`] — Profile-imports-Profile
///   chain visits the same href twice.
/// * [`ParseError::ProfileImportSourceUnknown`] — a `sources` entry is
///   neither a Catalog nor a Profile.
/// * [`ParseError::ProfileIncludeControlsNotArray`] /
///   `ProfileExcludeControlsNotArray` — directive value is not an
///   array.
/// * [`ParseError::ProfileWithIdsNotArray`] — a
///   `with-ids` slot is not an array of strings.
/// * [`ParseError::ProfileSetParameterMissingId` /
///   `ProfileSetParameterValuesNotArray` /
///   `ProfileSetParameterValuesEmpty`] — a `set-parameters` entry is
///   malformed.
/// * Plus any [`ParseError`] surfaced from
///   [`lint_ids_from_catalog`] when an imported Catalog is malformed.
///
/// # OSCAL spec references
///
/// - NIST OSCAL v1.1.2 Profile model:
///   <https://pages.nist.gov/OSCAL/concepts/layer/control/profile/>
pub fn resolve_profile(
    profile: &Value,
    sources: &HashMap<String, Value>,
) -> Result<ResolvedProfile, ParseError> {
    let mut stack: HashSet<String> = HashSet::new();
    resolve_profile_inner(profile, sources, &mut stack)
}

fn resolve_profile_inner(
    profile: &Value,
    sources: &HashMap<String, Value>,
    stack: &mut HashSet<String>,
) -> Result<ResolvedProfile, ParseError> {
    let obj = profile.as_object().ok_or(ParseError::ProfileNotObject)?;
    let prof = obj
        .get("profile")
        .and_then(|p| p.as_object())
        .ok_or(ParseError::ProfileMissingWrapper)?;
    // PKIX-7f92.33: validate metadata.oscal-version before walking
    // the imports list. Profile inheritance has version-dependent
    // shape (include-controls, modify, set-parameters all gained
    // fields across versions), so accepting an unknown version risks
    // silent semantic drift on nested imports.
    super::parse::check_oscal_version(prof)?;
    let imports = prof
        .get("imports")
        .and_then(|i| i.as_array())
        .ok_or(ParseError::ProfileImportsNotArray)?;

    let mut control_ids: Vec<String> = Vec::new();
    let mut seen_ids: HashSet<String> = HashSet::new();
    let mut parameter_overrides: Vec<ParameterOverride> = Vec::new();

    for (import_index, import) in imports.iter().enumerate() {
        let import_obj = import
            .as_object()
            .ok_or(ParseError::ProfileImportNotObject {
                index: import_index,
            })?;
        let href_value = import_obj
            .get("href")
            .ok_or(ParseError::ProfileImportMissingHref {
                index: import_index,
            })?;
        let href = href_value
            .as_str()
            .ok_or(ParseError::ProfileImportHrefNotString {
                index: import_index,
            })?;
        if href.is_empty() {
            return Err(ParseError::ProfileImportHrefEmpty {
                index: import_index,
            });
        }

        let source = sources
            .get(href)
            .ok_or_else(|| ParseError::ProfileImportUnresolved {
                index: import_index,
                href: href.to_owned(),
            })?;

        // Recurse if the source is itself a Profile; otherwise treat as a
        // Catalog. Distinguish via the wrapper key.
        let source_obj =
            source
                .as_object()
                .ok_or_else(|| ParseError::ProfileImportSourceUnknown {
                    index: import_index,
                    href: href.to_owned(),
                })?;

        let (mut available_ids, mut nested_overrides) = if source_obj.contains_key("profile") {
            if !stack.insert(href.to_owned()) {
                return Err(ParseError::ProfileImportCycle {
                    href: href.to_owned(),
                });
            }
            let nested = resolve_profile_inner(source, sources, stack)?;
            stack.remove(href);
            (nested.control_ids, nested.parameter_overrides)
        } else if source_obj.contains_key("catalog") {
            let ids = lint_ids_from_catalog(source)?;
            (ids, Vec::new())
        } else {
            return Err(ParseError::ProfileImportSourceUnknown {
                index: import_index,
                href: href.to_owned(),
            });
        };

        // Apply include filters. `include-all` includes everything from
        // the source; otherwise `include-controls[].with-ids[]` selects
        // explicit ids. Absent either, OSCAL semantics include nothing
        // from this import.
        let include_all = import_obj.get("include-all").is_some();
        let include_directives = import_obj.get("include-controls");
        let included: Vec<String> = if include_all {
            available_ids.clone()
        } else if let Some(directives) = include_directives {
            let entries =
                directives
                    .as_array()
                    .ok_or(ParseError::ProfileIncludeControlsNotArray {
                        index: import_index,
                    })?;
            let mut wanted: HashSet<String> = HashSet::new();
            for (entry_index, entry) in entries.iter().enumerate() {
                let entry_obj =
                    entry
                        .as_object()
                        .ok_or(ParseError::ProfileWithIdsEntryNotObject {
                            index: import_index,
                            entry_index,
                        })?;
                if let Some(with_ids) = entry_obj.get("with-ids") {
                    let ids = with_ids
                        .as_array()
                        .ok_or(ParseError::ProfileWithIdsNotArray {
                            index: import_index,
                            entry_index,
                        })?;
                    for id_val in ids {
                        let id_str = id_val.as_str().ok_or(ParseError::ProfileWithIdNotString {
                            index: import_index,
                            entry_index,
                        })?;
                        wanted.insert(id_str.to_owned());
                    }
                }
            }
            // Preserve the source order; only keep ids present in the
            // source (silently drop wanted ids that aren't in the
            // source — operators see this via the `filter_to_ids`
            // round-trip failing later if it matters).
            available_ids.retain(|id| wanted.contains(id));
            available_ids.clone()
        } else {
            // Neither `include-all` nor `include-controls` present:
            // nothing included from this import.
            Vec::new()
        };

        // Apply exclude filters after include.
        let mut excluded: HashSet<String> = HashSet::new();
        if let Some(directives) = import_obj.get("exclude-controls") {
            let entries =
                directives
                    .as_array()
                    .ok_or(ParseError::ProfileExcludeControlsNotArray {
                        index: import_index,
                    })?;
            for (entry_index, entry) in entries.iter().enumerate() {
                let entry_obj =
                    entry
                        .as_object()
                        .ok_or(ParseError::ProfileWithIdsEntryNotObject {
                            index: import_index,
                            entry_index,
                        })?;
                if let Some(with_ids) = entry_obj.get("with-ids") {
                    let ids = with_ids
                        .as_array()
                        .ok_or(ParseError::ProfileWithIdsNotArray {
                            index: import_index,
                            entry_index,
                        })?;
                    for id_val in ids {
                        let id_str = id_val.as_str().ok_or(ParseError::ProfileWithIdNotString {
                            index: import_index,
                            entry_index,
                        })?;
                        excluded.insert(id_str.to_owned());
                    }
                }
            }
        }

        for id in included {
            if excluded.contains(&id) {
                continue;
            }
            if seen_ids.insert(id.clone()) {
                control_ids.push(id);
            }
        }

        // Inner Profile overrides precede outer overrides — so set_parameter
        // applied in the outer-loop order will leave the outermost value
        // last-set, which matches OSCAL "outer wins" semantics for layered
        // Profiles.
        parameter_overrides.append(&mut nested_overrides);
    }

    // Walk modify.set-parameters[] on this Profile (outermost layer).
    if let Some(modify) = prof.get("modify").and_then(|m| m.as_object()) {
        if let Some(set_params) = modify.get("set-parameters") {
            let entries = set_params
                .as_array()
                .ok_or(ParseError::ProfileSetParametersNotArray)?;
            for (entry_index, entry) in entries.iter().enumerate() {
                let entry_obj = entry
                    .as_object()
                    .ok_or(ParseError::ProfileSetParameterNotObject { entry_index })?;
                let param_id = entry_obj
                    .get("param-id")
                    .and_then(|v| v.as_str())
                    .ok_or(ParseError::ProfileSetParameterMissingId { entry_index })?;
                if param_id.is_empty() {
                    return Err(ParseError::ProfileSetParameterIdEmpty { entry_index });
                }
                let values = entry_obj
                    .get("values")
                    .and_then(|v| v.as_array())
                    .ok_or(ParseError::ProfileSetParameterValuesNotArray { entry_index })?;
                if values.is_empty() {
                    return Err(ParseError::ProfileSetParameterValuesEmpty { entry_index });
                }
                let value = values[0]
                    .as_str()
                    .ok_or(ParseError::ProfileSetParameterValueNotString { entry_index })?;
                parameter_overrides.push(ParameterOverride {
                    param_id: param_id.to_owned(),
                    value: value.to_owned(),
                });
            }
        }
    }

    Ok(ResolvedProfile {
        control_ids,
        parameter_overrides,
    })
}

#[cfg(test)]
mod tests {
    //! Independent oracles:
    //!
    //! * The Profile JSON shapes are hand-constructed in tests and assert
    //!   on the output `control_ids` ordering and `parameter_overrides`
    //!   list. Within each individual test the hand-written Profile JSON
    //!   serves as the test oracle — the parser under test produces the
    //!   resolution, and the test compares against an independently
    //!   computed expected output (the set of ids the test author of
    //!   that JSON intended). This per-test oracle role does not imply
    //!   anything about OSCAL Profiles as a global workspace source of
    //!   truth; see `pkix-lint/src/oscal/mod.rs` for the stance.
    //! * Catalog inputs are constructed via the catalog emitter
    //!   ([`crate::oscal::catalog::catalog_from_lints`]) over known
    //!   `Lint` impls, so the Control id set of each Catalog is fixed by
    //!   the impls themselves (themselves tested independently).
    //! * Negative tests exercise each [`ParseError`] variant introduced
    //!   by Profile composition by passing a deliberately malformed JSON
    //!   shape and asserting the matching error type.
    //!
    //! End-to-end execution (Catalog → Profile resolve →
    //! `apply_parameter_overrides` → `filter_to_ids` → `run_chain`) is
    //! covered separately in pkix-lint-cabf's integration tests; here we
    //! focus on the resolver itself.

    use super::*;
    use crate::oscal::catalog::catalog_from_lints;
    use crate::rfc5280::Rfc5280MaxSerialLengthLint;
    use crate::{Lint, LintResult, Scope, Severity, SubjectKind};
    use serde_json::json;
    use x509_cert::Certificate;

    /// Minimal policy-shaped fixture Lint used as the "second catalog"
    /// in cross-catalog Profile tests. Mirrors the metadata shape of a
    /// CA/B Forum lint (spec_section_id set, spec_url None) without
    /// depending on pkix-lint-cabf content.
    #[derive(Clone)]
    struct PolicyShapedLint;
    impl Lint for PolicyShapedLint {
        fn id(&self) -> &'static str {
            "test.policy.shaped"
        }
        fn citation(&self) -> &'static str {
            "Test Policy §1.2.3"
        }
        fn severity(&self) -> Severity {
            Severity::Error
        }
        fn scope(&self) -> Scope {
            Scope::Certificate
        }
        fn applies_to(&self) -> SubjectKind {
            SubjectKind::Leaf
        }
        fn spec_section_id(&self) -> Option<&str> {
            Some("test-policy-1.2.3")
        }
        fn check_cert(
            &self,
            _cert: &Certificate,
            _kind: SubjectKind,
            _now_unix: u64,
        ) -> LintResult {
            LintResult::Pass
        }
    }

    fn rfc_catalog() -> Value {
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        catalog_from_lints(&lints, "rs.pkix.rfc5280", "0.1.0")
    }

    /// Stand-in second-catalog used by the layered-profile tests. Previously
    /// keyed off the CA/B Forum `ValidityMaxLint`; now uses a self-contained
    /// fixture so pkix-lint's tests do not depend on pkix-lint-cabf content.
    fn policy_catalog() -> Value {
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(PolicyShapedLint)];
        catalog_from_lints(&lints, "rs.pkix.policy.fixture", "0.1.0")
    }

    // -- Example 1: plain Profile, include-all from one Catalog --------

    #[test]
    fn plain_profile_include_all() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-000000000001",
                "metadata": { "title": "plain", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "back-matter": {}
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert_eq!(
            resolved.control_ids,
            vec!["rfc5280.cert.serial_number.max_octets".to_owned()]
        );
        assert!(resolved.parameter_overrides.is_empty());
    }

    #[test]
    fn plain_profile_explicit_include_controls() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-000000000002",
                "metadata": { "title": "explicit", "oscal-version": "1.1.2" },
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-controls": [
                            { "with-ids": ["rfc5280.cert.serial_number.max_octets"] }
                        ]
                    }
                ]
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert_eq!(
            resolved.control_ids,
            vec!["rfc5280.cert.serial_number.max_octets".to_owned()]
        );
    }

    // -- Example 2: layered Profile across two Catalogs ----------------

    #[test]
    fn layered_profile_imports_two_catalogs_with_overrides() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());
        sources.insert("#rs.pkix.policy.fixture".to_owned(), policy_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-000000000003",
                "metadata": { "title": "policy-fixture", "oscal-version": "1.1.2" },
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-all": {}
                    },
                    {
                        "href": "#rs.pkix.policy.fixture",
                        "include-all": {}
                    }
                ],
                "modify": {
                    "set-parameters": [
                        {
                            "param-id": "rfc5280.cert.serial_number.max_octets.max-octets",
                            "values": ["16"]
                        }
                    ]
                }
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert_eq!(
            resolved.control_ids,
            vec![
                "rfc5280.cert.serial_number.max_octets".to_owned(),
                "test.policy.shaped".to_owned(),
            ]
        );
        assert_eq!(
            resolved.parameter_overrides,
            vec![ParameterOverride {
                param_id: "rfc5280.cert.serial_number.max_octets.max-octets".to_owned(),
                value: "16".to_owned(),
            }]
        );
    }

    // -- Example 3: override Profile imports another Profile -----------

    #[test]
    fn override_profile_imports_profile_and_excludes_one_control() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());
        sources.insert("#rs.pkix.policy.fixture".to_owned(), policy_catalog());

        // Inner Profile: layered selection across the two Catalogs.
        let inner = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000abcd",
                "metadata": { "title": "inner", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} },
                    { "href": "#rs.pkix.policy.fixture", "include-all": {} }
                ]
            }
        });
        sources.insert("#pkix.profile.inner".to_owned(), inner);

        // Outer Profile: import inner, drop the policy-fixture control.
        let outer = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000ef00",
                "metadata": { "title": "outer-customer-deviation", "oscal-version": "1.1.2" },
                "imports": [
                    {
                        "href": "#pkix.profile.inner",
                        "include-all": {},
                        "exclude-controls": [
                            { "with-ids": ["test.policy.shaped"] }
                        ]
                    }
                ],
                "modify": {
                    "set-parameters": [
                        {
                            "param-id": "rfc5280.cert.serial_number.max_octets.max-octets",
                            "values": ["8"]
                        }
                    ]
                }
            }
        });

        let resolved = resolve_profile(&outer, &sources).expect("resolve");
        assert_eq!(
            resolved.control_ids,
            vec!["rfc5280.cert.serial_number.max_octets".to_owned()]
        );
        assert_eq!(
            resolved.parameter_overrides,
            vec![ParameterOverride {
                param_id: "rfc5280.cert.serial_number.max_octets.max-octets".to_owned(),
                value: "8".to_owned(),
            }]
        );
    }

    #[test]
    fn override_profile_inherits_inner_overrides_before_its_own() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let inner = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000a1a1",
                "metadata": { "title": "inner-with-override", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": {
                    "set-parameters": [
                        {
                            "param-id": "rfc5280.cert.serial_number.max_octets.max-octets",
                            "values": ["16"]
                        }
                    ]
                }
            }
        });
        sources.insert("#pkix.profile.inner".to_owned(), inner);

        let outer = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000a2a2",
                "metadata": { "title": "outer-with-tighter-override", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#pkix.profile.inner", "include-all": {} }
                ],
                "modify": {
                    "set-parameters": [
                        {
                            "param-id": "rfc5280.cert.serial_number.max_octets.max-octets",
                            "values": ["8"]
                        }
                    ]
                }
            }
        });

        let resolved = resolve_profile(&outer, &sources).expect("resolve");
        // Inner override appears first, outer second — caller applies in
        // order so outer wins.
        assert_eq!(
            resolved.parameter_overrides,
            vec![
                ParameterOverride {
                    param_id: "rfc5280.cert.serial_number.max_octets.max-octets".to_owned(),
                    value: "16".to_owned(),
                },
                ParameterOverride {
                    param_id: "rfc5280.cert.serial_number.max_octets.max-octets".to_owned(),
                    value: "8".to_owned(),
                },
            ]
        );
    }

    // -- Filter semantics ----------------------------------------------

    #[test]
    fn exclude_after_include_drops_id() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000ccdd",
                "metadata": { "title": "exclude-test", "oscal-version": "1.1.2" },
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-all": {},
                        "exclude-controls": [
                            { "with-ids": ["rfc5280.cert.serial_number.max_octets"] }
                        ]
                    }
                ]
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert!(resolved.control_ids.is_empty());
    }

    #[test]
    fn import_without_include_directive_yields_no_controls() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000bbcc",
                "metadata": { "title": "no-include", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280" }
                ]
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert!(resolved.control_ids.is_empty());
    }

    #[test]
    fn duplicate_id_across_imports_dedup_first_wins() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());
        sources.insert("#rs.pkix.rfc5280.alt".to_owned(), rfc_catalog());

        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-00000000dd11",
                "metadata": { "title": "dup", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} },
                    { "href": "#rs.pkix.rfc5280.alt", "include-all": {} }
                ]
            }
        });

        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert_eq!(
            resolved.control_ids,
            vec!["rfc5280.cert.serial_number.max_octets".to_owned()],
            "duplicate id from two imports should appear once"
        );
    }

    // -- Negative tests: each new ParseError variant -------------------

    #[test]
    fn err_profile_not_object() {
        let sources = HashMap::new();
        let err = resolve_profile(&Value::Null, &sources).unwrap_err();
        assert!(matches!(err, ParseError::ProfileNotObject));
    }

    #[test]
    fn err_profile_missing_wrapper() {
        let sources = HashMap::new();
        let v = json!({ "not-a-profile": {} });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(err, ParseError::ProfileMissingWrapper));
    }

    #[test]
    fn err_imports_not_array() {
        let sources = HashMap::new();
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": {} } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(err, ParseError::ProfileImportsNotArray));
    }

    /// Profile without metadata.oscal-version must surface
    /// MissingOscalVersion before any later shape check (PKIX-7f92.33).
    #[test]
    fn err_profile_missing_oscal_version() {
        let sources = HashMap::new();
        // Bare profile with imports but no metadata.
        let v = json!({ "profile": { "imports": [] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(err, ParseError::MissingOscalVersion));
    }

    /// Profile declaring oscal-version != 1.1.2 must be rejected
    /// (PKIX-7f92.33).
    #[test]
    fn err_profile_unsupported_oscal_version() {
        let sources = HashMap::new();
        for found in ["1.0.4", "1.2.0"] {
            let v = json!({
                "profile": {
                    "metadata": {"oscal-version": found},
                    "imports": []
                }
            });
            match resolve_profile(&v, &sources) {
                Err(ParseError::UnsupportedOscalVersion { found: got }) => {
                    assert_eq!(got, found);
                }
                other => panic!(
                    "expected UnsupportedOscalVersion for version {found}; got: {other:?}"
                ),
            }
        }
    }

    /// A nested imported Profile whose metadata.oscal-version is
    /// missing must also surface MissingOscalVersion — version checking
    /// recurses through profile imports.
    #[test]
    fn err_nested_profile_missing_oscal_version() {
        let mut sources = HashMap::new();
        sources.insert(
            "#inner-no-version".to_owned(),
            // Inner profile without metadata.oscal-version.
            json!({ "profile": { "imports": [] } }),
        );
        let outer = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [ { "href": "#inner-no-version" } ]
            }
        });
        let err = resolve_profile(&outer, &sources).unwrap_err();
        assert!(matches!(err, ParseError::MissingOscalVersion));
    }

    #[test]
    fn err_import_missing_href() {
        let sources = HashMap::new();
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ {} ] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileImportMissingHref { index: 0 }
        ));
    }

    #[test]
    fn err_import_href_not_string() {
        let sources = HashMap::new();
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": 7 } ] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileImportHrefNotString { index: 0 }
        ));
    }

    #[test]
    fn err_import_href_empty() {
        let sources = HashMap::new();
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "" } ] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileImportHrefEmpty { index: 0 }
        ));
    }

    #[test]
    fn err_import_unresolved() {
        let sources = HashMap::new();
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "#nope" } ] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        match err {
            ParseError::ProfileImportUnresolved { index: 0, href } => {
                assert_eq!(href, "#nope");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn err_import_source_unknown() {
        let mut sources = HashMap::new();
        sources.insert(
            "#weird".to_owned(),
            json!({ "neither-catalog-nor-profile": {} }),
        );
        let v = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "#weird" } ] } });
        let err = resolve_profile(&v, &sources).unwrap_err();
        match err {
            ParseError::ProfileImportSourceUnknown { index: 0, href } => {
                assert_eq!(href, "#weird");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn err_import_cycle() {
        let mut sources = HashMap::new();
        // Profile A imports Profile B; Profile B imports Profile A.
        sources.insert(
            "#a".to_owned(),
            json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "#b" } ] } }),
        );
        sources.insert(
            "#b".to_owned(),
            json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "#a" } ] } }),
        );
        let outer = json!({ "profile": { "metadata": {"oscal-version": "1.1.2"}, "imports": [ { "href": "#a" } ] } });
        let err = resolve_profile(&outer, &sources).unwrap_err();
        match err {
            ParseError::ProfileImportCycle { href } => {
                assert!(href == "#a" || href == "#b");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn err_include_controls_not_array() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-controls": {} }
                ]
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileIncludeControlsNotArray { index: 0 }
        ));
    }

    #[test]
    fn err_exclude_controls_not_array() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-all": {},
                        "exclude-controls": "string-not-array"
                    }
                ]
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileExcludeControlsNotArray { index: 0 }
        ));
    }

    #[test]
    fn err_with_ids_not_array() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-controls": [ { "with-ids": "not-an-array" } ]
                    }
                ]
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileWithIdsNotArray {
                index: 0,
                entry_index: 0
            }
        ));
    }

    #[test]
    fn err_with_id_not_string() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    {
                        "href": "#rs.pkix.rfc5280",
                        "include-controls": [ { "with-ids": [42] } ]
                    }
                ]
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileWithIdNotString {
                index: 0,
                entry_index: 0
            }
        ));
    }

    #[test]
    fn err_set_parameters_not_array() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": { "set-parameters": "nope" }
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(err, ParseError::ProfileSetParametersNotArray));
    }

    #[test]
    fn err_set_parameter_missing_id() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": { "set-parameters": [ { "values": ["x"] } ] }
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileSetParameterMissingId { entry_index: 0 }
        ));
    }

    #[test]
    fn err_set_parameter_values_empty() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": { "set-parameters": [ { "param-id": "x", "values": [] } ] }
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileSetParameterValuesEmpty { entry_index: 0 }
        ));
    }

    #[test]
    fn err_set_parameter_value_not_string() {
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());

        let v = json!({
            "profile": {
                "metadata": {"oscal-version": "1.1.2"},
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": { "set-parameters": [ { "param-id": "x", "values": [7] } ] }
            }
        });
        let err = resolve_profile(&v, &sources).unwrap_err();
        assert!(matches!(
            err,
            ParseError::ProfileSetParameterValueNotString { entry_index: 0 }
        ));
    }

    // -- End-to-end: Profile → resolve → apply → filter → run --------

    /// Drives the full composition path against a real fixture cert,
    /// independent of the Profile-parsing layer. Oracle: the fixture's
    /// serial length is independently established by
    /// `rfc5280::tests::default_lint_accepts_20_octet_serial` (20
    /// octets). Default lint must Pass; same lint with override
    /// max-octets=10 must Error. The Error variant comes from the
    /// rfc5280 lint impl, which is tested independently in its own
    /// module — this test asserts the *plumbing* from Profile JSON to
    /// lint state.
    #[test]
    fn end_to_end_profile_override_changes_runner_behavior() {
        use crate::{LintResult, LintRunner, SubjectKind};
        use x509_cert::Certificate;

        let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../pkix-path/tests/fixtures/policy-checks/")
            .join("leaf-rsa2048-sha1.der");
        let der = std::fs::read(&fixture_path)
            .unwrap_or_else(|e| panic!("read fixture {}: {e}", fixture_path.display()));
        let cert = <Certificate as der::Decode>::from_der(&der).expect("decode fixture");
        assert_eq!(
            cert.tbs_certificate.serial_number.as_bytes().len(),
            20,
            "fixture invariant: leaf-rsa2048-sha1.der has a 20-octet serial",
        );

        // Build a runner with the default rfc5280 max-serial-length
        // lint (default max-octets = 20).
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        let mut runner = LintRunner::new(lints);

        // Default runner: 20-octet serial passes the 20-octet cap.
        let baseline = runner.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        let baseline_result = baseline
            .iter()
            .find(|f| f.lint_id == "rfc5280.cert.serial_number.max_octets")
            .map(|f| f.result.clone())
            .expect("rfc5280 finding present");
        assert!(
            matches!(baseline_result, LintResult::Pass),
            "default cap (20) must pass a 20-octet serial; got {baseline_result:?}",
        );

        // Compose a Profile that tightens max-octets to 10.
        let mut sources = HashMap::new();
        sources.insert("#rs.pkix.rfc5280".to_owned(), rfc_catalog());
        let profile = json!({
            "profile": {
                "uuid": "00000000-0000-0000-0000-000000000099",
                "metadata": { "title": "e2e-tighten", "oscal-version": "1.1.2" },
                "imports": [
                    { "href": "#rs.pkix.rfc5280", "include-all": {} }
                ],
                "modify": {
                    "set-parameters": [
                        {
                            "param-id": "rfc5280.cert.serial_number.max_octets.max-octets",
                            "values": ["10"]
                        }
                    ]
                }
            }
        });
        let resolved = resolve_profile(&profile, &sources).expect("resolve");
        assert_eq!(resolved.parameter_overrides.len(), 1);

        runner
            .apply_parameter_overrides(&resolved.parameter_overrides)
            .expect("apply overrides");
        let filtered = runner
            .filter_to_ids(&resolved.control_ids)
            .expect("filter to ids");

        // Tightened runner: 20-octet serial must now Error.
        let findings = filtered.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        let tightened_result = findings
            .iter()
            .find(|f| f.lint_id == "rfc5280.cert.serial_number.max_octets")
            .map(|f| f.result.clone())
            .expect("rfc5280 finding present");
        match tightened_result {
            LintResult::Error(detail) => {
                assert!(detail.contains("20 octets"));
                assert!(detail.contains("10 octets"));
            }
            other => panic!("tightened cap (10) must error on a 20-octet serial; got {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_unknown_lint_errors() {
        use crate::LintRunner;

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "no.such.lint.somewhere.max-octets".to_owned(),
            value: "1".to_owned(),
        }];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        match err {
            ParseError::UnknownParameterOverride { param_id } => {
                assert_eq!(param_id, "no.such.lint.somewhere.max-octets");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_unknown_param_id_errors() {
        use crate::LintRunner;

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "rfc5280.cert.serial_number.max_octets.no-such-param".to_owned(),
            value: "1".to_owned(),
        }];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        match err {
            ParseError::InvalidParameterOverride { param_id, .. } => {
                assert_eq!(
                    param_id,
                    "rfc5280.cert.serial_number.max_octets.no-such-param"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_invalid_value_wraps_parameter_error() {
        use crate::LintRunner;

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "rfc5280.cert.serial_number.max_octets.max-octets".to_owned(),
            value: "not-a-number".to_owned(),
        }];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        match err {
            ParseError::InvalidParameterOverride { param_id, source } => {
                assert_eq!(param_id, "rfc5280.cert.serial_number.max_octets.max-octets");
                assert!(matches!(source, crate::ParameterError::InvalidValue { .. }));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_id_without_dot_errors() {
        use crate::LintRunner;

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(Rfc5280MaxSerialLengthLint::default())];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "no_dot_separator".to_owned(),
            value: "1".to_owned(),
        }];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        assert!(matches!(err, ParseError::UnknownParameterOverride { .. }));
    }

    // -----------------------------------------------------------------------
    // PKIX-hy2e.3 regression: dotted parameter ids must resolve via
    // longest-prefix-match against the registered lints, not via a
    // rightmost-dot split that assumes parameter ids have no dot.
    // -----------------------------------------------------------------------

    /// Test fixture: a lint whose only valid parameter id contains a dot.
    /// `set_parameter` returns `Ok` exclusively when `id == "thresholds.warn"`;
    /// any other id surfaces `ParameterError::UnknownParameter`. The runner
    /// wraps that as `InvalidParameterOverride`, so a successful
    /// `apply_parameter_overrides` call proves the composite id was split
    /// at the correct boundary.
    #[derive(Clone)]
    struct DottedParamLint;
    impl Lint for DottedParamLint {
        fn id(&self) -> &'static str {
            "test.dotted.param"
        }
        fn citation(&self) -> &'static str {
            "PKIX-hy2e.3 fixture"
        }
        fn severity(&self) -> crate::Severity {
            crate::Severity::Warn
        }
        fn scope(&self) -> crate::Scope {
            crate::Scope::Certificate
        }
        fn applies_to(&self) -> crate::SubjectKind {
            crate::SubjectKind::Leaf
        }
        fn set_parameter(
            &mut self,
            id: &str,
            _value: &str,
        ) -> Result<(), crate::ParameterError> {
            if id == "thresholds.warn" {
                Ok(())
            } else {
                Err(crate::ParameterError::UnknownParameter(id.to_owned()))
            }
        }
        fn check_cert(
            &self,
            _cert: &x509_cert::Certificate,
            _kind: crate::SubjectKind,
            _now_unix: u64,
        ) -> crate::LintResult {
            crate::LintResult::Pass
        }
    }

    #[test]
    fn apply_parameter_overrides_resolves_dotted_param_id() {
        // Regression for PKIX-hy2e.3. Composite param_id =
        // "test.dotted.param.thresholds.warn". Lint id =
        // "test.dotted.param". Parameter id = "thresholds.warn" (contains
        // a dot). Longest-prefix matching against the registered lint id
        // must yield param_id "thresholds.warn". The pre-fix
        // rsplit-once-on-dot logic would yield param_id "warn" instead,
        // which the fixture lint's set_parameter rejects, surfacing as
        // InvalidParameterOverride.
        use crate::LintRunner;

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(DottedParamLint)];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "test.dotted.param.thresholds.warn".to_owned(),
            value: "5".to_owned(),
        }];
        runner.apply_parameter_overrides(&overrides).expect(
            "longest-prefix match must split composite id at the lint-id boundary; \
             rsplit-once-on-dot would have produced param_id='warn' and triggered \
             InvalidParameterOverride",
        );
    }

    #[test]
    fn apply_parameter_overrides_longest_prefix_wins_on_lint_id_collision() {
        // Regression: when two registered lint ids overlap by prefix
        // (one is a strict prefix of the other), the longest prefix
        // must win.
        use crate::LintRunner;

        // First registered: short prefix lint.
        #[derive(Clone)]
        struct ShortPrefixLint;
        impl Lint for ShortPrefixLint {
            fn id(&self) -> &'static str {
                "test.prefix"
            }
            fn citation(&self) -> &'static str {
                "fixture"
            }
            fn severity(&self) -> crate::Severity {
                crate::Severity::Warn
            }
            fn scope(&self) -> crate::Scope {
                crate::Scope::Certificate
            }
            fn applies_to(&self) -> crate::SubjectKind {
                crate::SubjectKind::Leaf
            }
            fn set_parameter(
                &mut self,
                id: &str,
                _value: &str,
            ) -> Result<(), crate::ParameterError> {
                // The short-prefix lint rejects every id so we can
                // detect if longest-prefix-match accidentally routed
                // the override here.
                Err(crate::ParameterError::UnknownParameter(format!(
                    "short-prefix lint received id={id} — longest-prefix-match should have \
                     routed to test.prefix.long instead"
                )))
            }
            fn check_cert(
                &self,
                _cert: &x509_cert::Certificate,
                _kind: crate::SubjectKind,
                _now_unix: u64,
            ) -> crate::LintResult {
                crate::LintResult::Pass
            }
        }

        // Second registered: long prefix lint, accepts "knob".
        #[derive(Clone)]
        struct LongPrefixLint;
        impl Lint for LongPrefixLint {
            fn id(&self) -> &'static str {
                "test.prefix.long"
            }
            fn citation(&self) -> &'static str {
                "fixture"
            }
            fn severity(&self) -> crate::Severity {
                crate::Severity::Warn
            }
            fn scope(&self) -> crate::Scope {
                crate::Scope::Certificate
            }
            fn applies_to(&self) -> crate::SubjectKind {
                crate::SubjectKind::Leaf
            }
            fn set_parameter(
                &mut self,
                id: &str,
                _value: &str,
            ) -> Result<(), crate::ParameterError> {
                if id == "knob" {
                    Ok(())
                } else {
                    Err(crate::ParameterError::UnknownParameter(id.to_owned()))
                }
            }
            fn check_cert(
                &self,
                _cert: &x509_cert::Certificate,
                _kind: crate::SubjectKind,
                _now_unix: u64,
            ) -> crate::LintResult {
                crate::LintResult::Pass
            }
        }

        let lints: Vec<Box<dyn Lint>> =
            vec![Box::new(ShortPrefixLint), Box::new(LongPrefixLint)];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![ParameterOverride {
            param_id: "test.prefix.long.knob".to_owned(),
            value: "v".to_owned(),
        }];
        runner.apply_parameter_overrides(&overrides).expect(
            "longest-prefix match must route to test.prefix.long not test.prefix",
        );
    }

    #[test]
    fn apply_parameter_overrides_fails_fast_before_mutation() {
        // Regression for the Phase 1 / Phase 2 separation in
        // apply_parameter_overrides (closes part of PKIX-hy2e.3's scope;
        // PKIX-hy2e.6 covers the InvalidParameterOverride-atomicity
        // surface). A batch with one valid override followed by one
        // UnknownParameterOverride must surface the
        // UnknownParameterOverride WITHOUT calling set_parameter on the
        // first lint. The pre-fix code applied the valid one and then
        // errored on the unknown one mid-loop, leaving the runner
        // partially mutated.
        use crate::LintRunner;
        use std::sync::atomic::{AtomicBool, Ordering};

        // Per-test static. Re-runs in the same process must reset it.
        static APPLIED: AtomicBool = AtomicBool::new(false);
        APPLIED.store(false, Ordering::SeqCst);

        #[derive(Clone)]
        struct ObservableLint;
        impl Lint for ObservableLint {
            fn id(&self) -> &'static str {
                "test.observable.lint"
            }
            fn citation(&self) -> &'static str {
                "PKIX-hy2e.3 fail-fast fixture"
            }
            fn severity(&self) -> crate::Severity {
                crate::Severity::Warn
            }
            fn scope(&self) -> crate::Scope {
                crate::Scope::Certificate
            }
            fn applies_to(&self) -> crate::SubjectKind {
                crate::SubjectKind::Leaf
            }
            fn set_parameter(
                &mut self,
                _id: &str,
                _value: &str,
            ) -> Result<(), crate::ParameterError> {
                APPLIED.store(true, Ordering::SeqCst);
                Ok(())
            }
            fn check_cert(
                &self,
                _cert: &x509_cert::Certificate,
                _kind: crate::SubjectKind,
                _now_unix: u64,
            ) -> crate::LintResult {
                crate::LintResult::Pass
            }
        }

        let lints: Vec<Box<dyn Lint>> = vec![Box::new(ObservableLint)];
        let mut runner = LintRunner::new(lints);
        let overrides = vec![
            ParameterOverride {
                param_id: "test.observable.lint.any".to_owned(),
                value: "v".to_owned(),
            },
            ParameterOverride {
                param_id: "no.such.lint.id.anywhere".to_owned(),
                value: "v".to_owned(),
            },
        ];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        assert!(matches!(err, ParseError::UnknownParameterOverride { .. }));
        assert!(
            !APPLIED.load(Ordering::SeqCst),
            "Phase 1 must surface UnknownParameterOverride before any set_parameter call"
        );
    }

    // -----------------------------------------------------------------------
    // PKIX-hy2e.6 regression — atomic application on
    // InvalidParameterOverride. apply_parameter_overrides now clones
    // every affected lint, applies set_parameter on the clones, and
    // swaps in the clones only after every override has succeeded.
    // A mid-batch InvalidParameterOverride leaves the runner unchanged.
    // -----------------------------------------------------------------------

    /// Fixture: a lint whose parameter value is observable through
    /// `check_cert` — the lint emits an Error finding whose detail
    /// string echoes the current parameter value. This lets the test
    /// observe the REGISTERED lint's parameter state (not the clone's)
    /// after `apply_parameter_overrides` returns.
    ///
    /// `set_parameter` accepts any value except "REJECT"; REJECT
    /// triggers `ParameterError::InvalidValue`.
    #[derive(Clone)]
    struct EchoParamLint {
        value: String,
    }
    impl Lint for EchoParamLint {
        fn id(&self) -> &'static str {
            "test.echo.param"
        }
        fn citation(&self) -> &'static str {
            "PKIX-hy2e.6 atomicity fixture"
        }
        fn severity(&self) -> crate::Severity {
            crate::Severity::Warn
        }
        fn scope(&self) -> crate::Scope {
            crate::Scope::Certificate
        }
        fn applies_to(&self) -> crate::SubjectKind {
            crate::SubjectKind::Leaf
        }
        fn set_parameter(
            &mut self,
            id: &str,
            value: &str,
        ) -> Result<(), crate::ParameterError> {
            if id != "knob" {
                return Err(crate::ParameterError::UnknownParameter(id.to_owned()));
            }
            if value == "REJECT" {
                return Err(crate::ParameterError::InvalidValue {
                    id: id.to_owned(),
                    reason: "REJECT is a poison value for this fixture".to_owned(),
                });
            }
            self.value = value.to_owned();
            Ok(())
        }
        fn check_cert(
            &self,
            _cert: &x509_cert::Certificate,
            _kind: crate::SubjectKind,
            _now_unix: u64,
        ) -> crate::LintResult {
            crate::LintResult::error(format!("value={}", self.value))
        }
    }

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

    #[test]
    fn apply_parameter_overrides_atomic_on_invalid_value_keeps_default() {
        // Trigger: a batch of overrides where the LAST one rejects.
        // The first override would succeed if applied directly; with
        // atomicity, the runner must roll back to defaults so the
        // first override's value does NOT appear in subsequent
        // findings.
        //
        // Oracle: EchoParamLint::check_cert emits the current
        // parameter value verbatim in the Error detail string. We
        // observe the REGISTERED lint's state by running it against
        // a cert and reading the finding's detail.
        use crate::{LintRunner, LintResult, SubjectKind};

        let cert = load_atomicity_fixture_cert();
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(EchoParamLint {
            value: "default".to_string(),
        })];
        let mut runner = LintRunner::new(lints);

        // Pre-apply state: registered lint emits value=default.
        let findings = runner.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        match &findings[0].result {
            LintResult::Error(detail) => assert_eq!(detail.as_ref(), "value=default"),
            other => panic!("expected Error, got {other:?}"),
        }

        // Apply a batch where the first override succeeds and the
        // second rejects. Atomicity requires the first to roll back.
        let overrides = vec![
            ParameterOverride::new("test.echo.param.knob", "overridden"),
            ParameterOverride::new("test.echo.param.knob", "REJECT"),
        ];
        let err = runner.apply_parameter_overrides(&overrides).unwrap_err();
        assert!(
            matches!(err, ParseError::InvalidParameterOverride { .. }),
            "REJECT must produce InvalidParameterOverride; got {err:?}"
        );

        // Post-apply state: the registered lint must still report
        // value=default. If atomicity were broken (pre-PKIX-hy2e.6
        // behavior), the first override would have been committed
        // and the lint would emit value=overridden.
        let findings = runner.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        match &findings[0].result {
            LintResult::Error(detail) => assert_eq!(
                detail.as_ref(), "value=default",
                "atomicity violation: the registered lint slot was mutated by the \
                 failed apply. Expected default value preserved; got: {detail:?}"
            ),
            other => panic!("expected Error, got {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_commits_on_full_success() {
        // Positive control: a fully-successful apply must commit
        // every override into the registered slots.
        use crate::{LintRunner, LintResult, SubjectKind};

        let cert = load_atomicity_fixture_cert();
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(EchoParamLint {
            value: "default".to_string(),
        })];
        let mut runner = LintRunner::new(lints);

        runner
            .apply_parameter_overrides(&[ParameterOverride::new(
                "test.echo.param.knob",
                "committed-value",
            )])
            .expect("valid value must commit");

        let findings = runner.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        match &findings[0].result {
            LintResult::Error(detail) => {
                assert_eq!(
                    detail.as_ref(),
                    "value=committed-value",
                    "fully-successful apply must commit the new value into the \
                     registered slot"
                );
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    #[test]
    fn apply_parameter_overrides_atomic_on_invalid_value_keeps_previous_commit() {
        // Compound regression: an earlier successful apply committed
        // "first-value". A later batch where override #2 rejects
        // must NOT erase "first-value" from the registered lint.
        // (I.e., atomicity does not regress the lint to its
        // construction-time default — it preserves the most-recently-
        // committed value.)
        use crate::{LintRunner, LintResult, SubjectKind};

        let cert = load_atomicity_fixture_cert();
        let lints: Vec<Box<dyn Lint>> = vec![Box::new(EchoParamLint {
            value: "default".to_string(),
        })];
        let mut runner = LintRunner::new(lints);

        runner
            .apply_parameter_overrides(&[ParameterOverride::new(
                "test.echo.param.knob",
                "first-value",
            )])
            .expect("first apply must succeed");

        let _err = runner
            .apply_parameter_overrides(&[
                ParameterOverride::new("test.echo.param.knob", "second-value"),
                ParameterOverride::new("test.echo.param.knob", "REJECT"),
            ])
            .expect_err("second-apply with REJECT must fail");

        // Atomicity assertion: the registered lint still reports
        // "first-value" (the previously-committed value), not
        // "default" (the construction-time value) and not
        // "second-value" (the failed-batch's first override).
        let findings = runner.run_cert(&cert, SubjectKind::Leaf, 0, 0);
        match &findings[0].result {
            LintResult::Error(detail) => assert_eq!(
                detail.as_ref(),
                "value=first-value",
                "atomicity: a failed batch must preserve the previously-committed \
                 value, not regress to default and not commit the failed batch's \
                 partial state; got: {detail:?}"
            ),
            other => panic!("expected Error, got {other:?}"),
        }
    }
}