zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Holds the exported document to the published schema.
//!
//! `assets/schema/zond-report-v1.schema.json` ships with the crate and is what
//! a consumer validates against. A schema nobody checks drifts: a field added to
//! a DTO, a `null` that becomes a string, an enum that gains a variant, and the
//! file on disk stops describing the thing it claims to.
//!
//! The schema is strict, with every object closed and every field required
//! except the handful a writer omits when it has nothing to say, and these tests
//! run the real exporter against it. Adding a field to a DTO without describing
//! it here fails the build.
//!
//! That handful is itself pinned, by
//! `the_schema_marks_optional_exactly_the_fields_a_writer_leaves_out`. The
//! module documentation of [`schema`](super::schema) tells a consumer what an
//! absent field means, and a `skip_serializing_if` added without a thought for
//! that sentence is how the two stop agreeing.

use boon::{Compiler, Schemas};
use regex::Regex;
use serde_json::Value;
use std::collections::BTreeSet;

use crate::config::{OsDetection, ScanEffort, ServiceDetection};
use crate::diff::{Coverage, Significance};
use crate::export::diff::schema::{coverage_name, significance_name};
use crate::export::schema::{SCHEMA_VERSION, scan_effort_name, send_mode_name};
use crate::export::{ExportOptions, Exporter, JsonExporter, Redaction, fixture};
use crate::model::confidence::Confidence;
use crate::model::finding::{DetectionClass, Severity};
use crate::model::host::status::StatusProtocol;
use crate::model::host::{
    Filtering, HostStatus, IpProtocolState, NameKind, NameSource, NetworkRole,
};
use crate::model::port::{PortState, Protocol};
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::model::tls::{Interruption, SuiteFault, SuiteStrength, TlsVersion};
use crate::record::wire::{
    attachment_source_name, confidence_name, detection_class_name, filtering_name,
    host_status_name, ip_protocol_state_name, liveness_skip_name, name_kind_name, name_source_name,
    network_role_name, pass_name, port_state_name, protocol_name, scan_kind_name,
    scanner_kind_name, severity_name, stop_reason_name,
};
use crate::report::{AttachmentSource, LivenessSkip, Pass, ScanKind, ScannerKind, StopReason};
use crate::transport::probe::SendMode;

/// The published schemas, compiled into the test binary so a test cannot pass
/// against a file that was not shipped.
const SCHEMA: &str = include_str!("../../assets/schema/zond-report-v1.schema.json");
const LINES_SCHEMA: &str = include_str!("../../assets/schema/zond-lines-v1.schema.json");
const DIFF_SCHEMA: &str = include_str!("../../assets/schema/zond-diff-v1.schema.json");

/// The identifiers the schemas declare for themselves.
const SCHEMA_URL: &str = "https://zond.rs/schema/zond-report-v1.schema.json";
const LINES_SCHEMA_URL: &str = "https://zond.rs/schema/zond-lines-v1.schema.json";
const DIFF_SCHEMA_URL: &str = "https://zond.rs/schema/zond-diff-v1.schema.json";

/// A compiled validator over one of the published schemas.
struct Validator {
    schemas: Schemas,
    index: boon::SchemaIndex,
}

impl Validator {
    /// A validator over the single-document schema.
    fn new() -> Self {
        Self::over(SCHEMA_URL)
    }

    /// A validator over the record-per-line schema.
    ///
    /// Validates one record, not a file: JSON Lines is not one JSON document.
    fn lines() -> Self {
        Self::over(LINES_SCHEMA_URL)
    }

    /// A validator over the comparison schema.
    fn diff() -> Self {
        Self::over(DIFF_SCHEMA_URL)
    }

    /// Compiles both schemas and points a validator at one of them.
    ///
    /// All three are registered whichever is being compiled. The lines and
    /// comparison schemas are written in terms of the report schema's
    /// definitions and cannot resolve without it.
    fn over(url: &str) -> Self {
        let mut schemas = Schemas::new();
        let mut compiler = Compiler::new();

        for (id, text) in [
            (SCHEMA_URL, SCHEMA),
            (LINES_SCHEMA_URL, LINES_SCHEMA),
            (DIFF_SCHEMA_URL, DIFF_SCHEMA),
        ] {
            let document: Value =
                serde_json::from_str(text).expect("the schema file is valid JSON");
            compiler
                .add_resource(id, document)
                .expect("the schema file is a usable resource");
        }

        let index = compiler
            .compile(url, &mut schemas)
            .expect("the schema file compiles");

        Self { schemas, index }
    }

    /// Fails with the validator's own explanation, which names the offending
    /// path.
    fn check(&self, document: &Value) {
        if let Err(error) = self.schemas.validate(document, self.index) {
            panic!("the exported document does not match the published schema:\n{error:#}");
        }
    }

    /// Whether a document validates, for the tests that assert rejection.
    fn accepts(&self, document: &Value) -> bool {
        self.schemas.validate(document, self.index).is_ok()
    }
}

/// Exports a report and parses it back.
fn document(options: ExportOptions) -> Value {
    let mut bytes = Vec::new();
    JsonExporter::new(options)
        .export(&fixture::report(), &mut bytes)
        .expect("the export succeeds");

    serde_json::from_slice(&bytes).expect("the export parses as JSON")
}

/// The schema has to be a schema before it can pin anything.
#[test]
fn the_published_schema_compiles() {
    let _ = Validator::new();
}

/// The version the code emits and the version the schema pins are the same
/// number, or one of them was bumped without the other.
#[test]
fn the_schema_pins_the_version_the_code_emits() {
    let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");

    assert_eq!(
        schema["properties"]["schema_version"]["const"],
        Value::from(SCHEMA_VERSION)
    );
}

/// Every enumerated value in the report document, as the schema lists it and as
/// this build spells it, compared both ways.
///
/// A variant the engine can write and the schema does not accept produces
/// documents no consumer's validator takes, and the document tests below cannot
/// see it since they exercise whichever variant the fixture happens to carry.
///
/// The reverse direction matters as much: a name the schema advertises and the
/// engine cannot produce is a promise to a third party writing this format that
/// both report readers then refuse.
///
/// Only the enums whose type publishes an `ALL` are here, and every closed enum
/// in the schema has one except `port_scope`, whose variants carry data. An
/// exhaustive list written out in this file would be a third copy of the
/// variants, which is the arrangement this test exists to catch, so a new enum
/// in the document should arrive with an `ALL`.
///
/// `reason.protocol` is compared through [`StatusProtocol::ALL`], which holds
/// its built-in names. The one variant it leaves out carries a strategy-chosen
/// name and is the schema's other `anyOf` arm, a `custom:` prefix, which is a
/// pattern rather than an enumeration.
fn enumerations() -> Vec<(&'static str, Vec<String>)> {
    let named = |names: Vec<&'static str>| names.into_iter().map(str::to_owned).collect();

    vec![
        (
            "/$defs/settings/properties/tcp_technique/enum",
            named(TcpScanTechnique::ALL.iter().map(|t| t.name()).collect()),
        ),
        (
            "/$defs/accepted_version/properties/version/enum",
            named(TlsVersion::ALL.iter().map(|v| v.name()).collect()),
        ),
        (
            "/$defs/unfinished_version/properties/version/enum",
            named(TlsVersion::ALL.iter().map(|v| v.name()).collect()),
        ),
        (
            "/$defs/unfinished_version/properties/interruption/enum",
            named(Interruption::ALL.iter().map(|i| i.name()).collect()),
        ),
        (
            "/$defs/accepted_suite/properties/strength/enum",
            named(SuiteStrength::ALL.iter().map(|s| s.name()).collect()),
        ),
        (
            "/$defs/accepted_suite/properties/faults/items/enum",
            named(SuiteFault::ALL.iter().map(|f| f.name()).collect()),
        ),
        (
            "/$defs/settings/properties/sctp_technique/enum",
            named(SctpScanTechnique::ALL.iter().map(|t| t.name()).collect()),
        ),
        (
            "/$defs/settings/properties/send_mode/enum",
            named(SendMode::ALL.iter().copied().map(send_mode_name).collect()),
        ),
        (
            "/$defs/settings/properties/os_detection/enum",
            named(OsDetection::ALL.iter().map(|d| d.name()).collect()),
        ),
        (
            "/$defs/settings/properties/service_detection/enum",
            named(ServiceDetection::ALL.iter().map(|d| d.name()).collect()),
        ),
        (
            "/$defs/settings/properties/detection/enum",
            named(
                DetectionClass::ALL
                    .iter()
                    .copied()
                    .map(detection_class_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/retry/properties/effort/enum",
            named(
                ScanEffort::ALL
                    .iter()
                    .copied()
                    .map(scan_effort_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/host/properties/status/enum",
            named(
                HostStatus::ALL
                    .iter()
                    .copied()
                    .map(host_status_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/host/properties/names/items/properties/source/enum",
            named(
                NameSource::ALL
                    .iter()
                    .copied()
                    .map(name_source_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/host/properties/names/items/properties/kind/enum",
            named(NameKind::ALL.iter().copied().map(name_kind_name).collect()),
        ),
        (
            "/$defs/host/properties/roles/items/enum",
            named(
                NetworkRole::ALL
                    .iter()
                    .copied()
                    .map(network_role_name)
                    .collect(),
            ),
        ),
        (
            // Inside an `anyOf`. The other arm is the `custom:` prefix a
            // strategy-supplied name is written under, a pattern rather than an
            // enumeration.
            "/$defs/reason/properties/protocol/anyOf/0/enum",
            StatusProtocol::ALL
                .iter()
                .map(|protocol| crate::record::wire::status_protocol_name(protocol).into_owned())
                .collect(),
        ),
        (
            "/$defs/host/properties/filtering/items/enum",
            named(Filtering::ALL.iter().copied().map(filtering_name).collect()),
        ),
        (
            "/$defs/host/properties/ip_protocols/items/properties/state/enum",
            named(
                IpProtocolState::ALL
                    .iter()
                    .copied()
                    .map(ip_protocol_state_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/port/properties/state/enum",
            named(
                PortState::ALL
                    .iter()
                    .copied()
                    .map(port_state_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/protocol/enum",
            named(Protocol::ALL.iter().copied().map(protocol_name).collect()),
        ),
        (
            "/$defs/finding/properties/severity/enum",
            named(Severity::ALL.iter().copied().map(severity_name).collect()),
        ),
        (
            "/$defs/finding/properties/confidence/enum",
            named(
                Confidence::ALL
                    .iter()
                    .copied()
                    .map(confidence_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/finding/properties/class/enum",
            named(
                DetectionClass::ALL
                    .iter()
                    .copied()
                    .map(detection_class_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/phase/properties/passes_cut/items/enum",
            named(Pass::ALL.iter().copied().map(pass_name).collect()),
        ),
        (
            "/$defs/phase/properties/kind/enum",
            named(ScanKind::ALL.iter().copied().map(scan_kind_name).collect()),
        ),
        (
            "/$defs/phase/properties/liveness_skipped/enum",
            named(
                LivenessSkip::ALL
                    .iter()
                    .copied()
                    .map(liveness_skip_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/scanner_kind/enum",
            named(
                ScannerKind::ALL
                    .iter()
                    .copied()
                    .map(scanner_kind_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/probe_stats/properties/stop_reason/enum",
            named(
                StopReason::ALL
                    .iter()
                    .copied()
                    .map(stop_reason_name)
                    .collect(),
            ),
        ),
        (
            "/$defs/attachment/properties/source/enum",
            named(
                AttachmentSource::ALL
                    .iter()
                    .copied()
                    .map(attachment_source_name)
                    .collect(),
            ),
        ),
    ]
}

/// Every enumerated value in the comparison document, the same way.
///
/// A shorter list than the report's, because a comparison is built out of the
/// report's own vocabulary and re-uses its names for everything it carries over.
/// What is its own is the coverage answer and the significance grade, neither of
/// which exists anywhere else.
///
/// [`Presence`](crate::diff::Presence) is the other closed enum in the document
/// and is not here, for the reason `port_scope` is not in the report's list: two
/// of its three variants carry data, so it publishes no `ALL`.
fn diff_enumerations() -> Vec<(&'static str, Vec<String>)> {
    let coverage: Vec<String> = Coverage::ALL
        .iter()
        .copied()
        .map(|coverage| coverage_name(coverage).to_owned())
        .collect();

    let significance: Vec<String> = Significance::ALL
        .iter()
        .copied()
        .map(|significance| significance_name(significance).to_owned())
        .collect();

    // Both answers are asked of a host and of an endpoint, and the grade again of
    // the document as a whole, so each list is spelled several times and every
    // copy is held to the same build.
    vec![
        (
            "/$defs/host_delta/properties/coverage/oneOf/0/enum",
            coverage.clone(),
        ),
        (
            "/$defs/port_delta/properties/coverage/oneOf/0/enum",
            coverage,
        ),
        ("/properties/significance/enum", significance.clone()),
        (
            "/$defs/host_delta/properties/significance/enum",
            significance.clone(),
        ),
        (
            "/$defs/port_delta/properties/significance/enum",
            significance,
        ),
    ]
}

#[test]
fn the_comparison_schema_lists_exactly_the_enumerated_values_the_engine_writes() {
    let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("valid JSON");
    check_enumerations(&schema, diff_enumerations());
}

#[test]
fn the_schema_lists_exactly_the_enumerated_values_the_engine_writes() {
    let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
    check_enumerations(&schema, enumerations());
}

/// Holds one document's schema to one build's vocabulary, both ways.
fn check_enumerations(schema: &Value, enumerations: Vec<(&'static str, Vec<String>)>) {
    for (pointer, emitted) in enumerations {
        let accepted: BTreeSet<String> = schema
            .pointer(pointer)
            .unwrap_or_else(|| panic!("the schema has no enumeration at {pointer}"))
            .as_array()
            .unwrap_or_else(|| panic!("{pointer} is not a list of names"))
            .iter()
            .map(|value| {
                value
                    .as_str()
                    .unwrap_or_else(|| panic!("{pointer} holds something that is not a name"))
                    .to_owned()
            })
            .collect();

        let emitted: BTreeSet<String> = emitted.into_iter().collect();

        assert_eq!(
            emitted.difference(&accepted).collect::<Vec<_>>(),
            Vec::<&String>::new(),
            "{pointer} does not accept a value this build can write"
        );
        assert_eq!(
            accepted.difference(&emitted).collect::<Vec<_>>(),
            Vec::<&String>::new(),
            "{pointer} advertises a value this build cannot write, which a third \
             party producing this format would find refused on the way back in"
        );
    }
}

/// A fully populated report: every optional block present, a failed strategy, an
/// instrumented scanner, a certificate, nested script output.
#[test]
fn a_full_report_matches_the_schema() {
    Validator::new().check(&document(ExportOptions::new()));
}

/// A scan that altered no packets, read no zombie's counter and found no
/// managed equipment, which is most scans.
///
/// Every test above exports the fixture that has one of everything, so the
/// schema's `required` lists are only exercised where nothing is missing. A field
/// the schema demands and this document omits would pass all of them and fail in
/// a consumer's validator.
#[test]
fn an_ordinary_report_matches_the_schema() {
    let plain = fixture::compared().0;
    let mut bytes = Vec::new();
    JsonExporter::new(ExportOptions::new())
        .export(&plain, &mut bytes)
        .expect("the export succeeds");
    let document: Value = serde_json::from_slice(&bytes).expect("the export parses as JSON");

    // Otherwise this validates the same document the test above does.
    let settings = &document["phases"][0]["settings"];
    assert!(settings["evasion"].is_null(), "the fixture altered packets");
    assert!(settings["idle_scan"].is_null(), "the fixture read a zombie");
    assert!(
        document["phases"][0]["attachments"].is_null(),
        "the fixture found managed equipment"
    );

    Validator::new().check(&document);
}

/// The fields a writer leaves out, as the schema lists them.
///
/// Everything else the document carries is present whatever its value: `null` for
/// nothing, `[]` for nothing in a list. These are the exception, and
/// [`schema`](super::schema) promises a consumer that reading an absent one as
/// the empty value is always correct. A `skip_serializing_if` added to a field
/// not on this list breaks that promise silently.
#[test]
fn the_schema_marks_optional_exactly_the_fields_a_writer_leaves_out() {
    /// `$defs` entry, or `report` for the document itself, then field.
    const OMITTED: &[(&str, &str)] = &[
        // A version whose every accepted suite is one this build carries, which
        // is every version against every server anyone has configured.
        ("accepted_version", "unrecognised"),
        ("attachment", "device_mac"),
        ("attachment", "device_name"),
        ("attachment", "management_address"),
        ("attachment", "native_vlan"),
        ("attachment", "port"),
        // A strategy that failed rather than one a limit cut short, which is
        // what every entry of a document predating the mark meant.
        ("failure", "cut_short"),
        ("finding", "cpe"),
        ("finding", "cpes"),
        ("finding", "excerpt"),
        ("finding", "remediation"),
        // A rule names whichever parts of a box it knows, and most name one or
        // two: a vendor and a model, or a family and nothing else.
        ("hardware", "cpe23"),
        ("hardware", "family"),
        // The three a service states about a box and an address block never
        // reaches. Absent from most records because most rules name none of
        // them, and `serial_number` is absent from every redacted document.
        ("hardware", "model"),
        ("hardware", "product"),
        ("hardware", "serial_number"),
        ("hardware", "version"),
        ("origin", "label"),
        ("phase", "attachments"),
        // A phase that found no host rationing its ICMP errors leaves this out,
        // which is every phase that asked no UDP ports of one.
        ("phase", "icmp_rate_limited"),
        // A port phase a liveness pass preceded leaves this out, which is most
        // of them, and so does every phase that is not a port scan.
        ("phase", "liveness_skipped"),
        // Every phase that closed leaves this out, which is all but the last
        // of a sitting killed before it ended.
        ("phase", "open"),
        ("phase", "origin"),
        // A phase no stop cut a pass of, which is nearly every phase.
        ("phase", "passes_cut"),
        // A phase that reached everything the way its privilege says leaves this
        // out, which is most phases and every unprivileged one.
        ("phase", "reached_by_connect"),
        // A phase that declined nothing leaves this out rather than writing an
        // empty list, which is what most phases do.
        ("phase", "refusals"),
        // A phase no route of the scanning host refused an address to, which
        // is nearly every phase.
        ("phase", "refused_by_route"),
        // Every phase but a port phase standing in for a liveness pass the
        // engine dropped leaves this out, and so does such a phase that heard
        // something from every address it asked.
        ("phase", "silent"),
        // A phase nobody stopped leaves this out, which is most of them.
        ("phase", "stopped"),
        // A phase that ran out of time on no host leaves this out rather than
        // writing an empty list, which is every phase that set no per-host
        // budget.
        ("phase", "timed_out"),
        // A phase that reached a verdict on every address it was asked about
        // leaves this out, which is every finished sweep and every port scan.
        ("phase", "undecided"),
        // A phase that did not stand in for a liveness pass leaves this out,
        // and so does one that heard something from every address it asked.
        ("phase", "unheard_probes"),
        // A phase whose walk ran to its end leaves this out, and so does every
        // phase that is not a port scan.
        ("phase", "unreached"),
        // What the report as a whole left open, left out where nothing is, as
        // the phases' own lists are: a scan that finished everything it was
        // asked has none of the three.
        ("report", "timed_out"),
        ("report", "undecided"),
        ("report", "unreached"),
        ("scope", "listened"),
        // A port on a scan that did not enumerate, which is the default.
        ("security", "accepts"),
        // A port whose every walk finished, which is every port a scan did
        // not enumerate and nearly every one it did.
        ("security", "unfinished"),
        ("settings", "evasion"),
        ("settings", "excluded_ports"),
        ("settings", "idle_scan"),
    ];

    /// The two objects that are a technique's own profile, where every field
    /// describes one part of it and any part may be absent.
    const OMITTED_WHOLESALE: &[&str] = &["evasion", "idle_scan"];

    let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
    let definitions = schema["$defs"]
        .as_object()
        .expect("the schema defines types");

    let mut optional: Vec<(String, String)> = Vec::new();
    // The document itself, beside the types it is built from.
    let report = String::from("report");
    for (name, definition) in definitions.iter().chain([(&report, &schema)]) {
        let Some(properties) = definition["properties"].as_object() else {
            continue;
        };
        let required: BTreeSet<&str> = definition["required"]
            .as_array()
            .map(|names| names.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();

        if OMITTED_WHOLESALE.contains(&name.as_str()) {
            assert!(
                required.is_empty(),
                "`{name}` describes one technique's profile and every part of it \
                 is optional; `{required:?}` says otherwise"
            );
            continue;
        }

        for field in properties.keys() {
            if !required.contains(field.as_str()) {
                optional.push((name.clone(), field.clone()));
            }
        }
    }
    optional.sort();

    let expected: Vec<(String, String)> = OMITTED
        .iter()
        .map(|(object, field)| ((*object).to_string(), (*field).to_string()))
        .collect();

    assert_eq!(
        optional, expected,
        "the schema's optional fields are not the ones `schema`'s module \
         documentation tells a consumer to expect"
    );
}

/// Redaction rewrites hostnames and hardware addresses. It must not rewrite
/// them into something the schema no longer accepts.
#[test]
fn a_redacted_report_matches_the_schema() {
    Validator::new().check(&document(
        ExportOptions::new().with_redaction(Redaction::Standard),
    ));
}

/// If the schema accepted anything, passing it would prove nothing. This checks
/// that it rejects.
#[test]
fn the_schema_rejects_a_document_it_should_reject() {
    let validator = Validator::new();

    let mut missing_field = document(ExportOptions::new());
    missing_field
        .as_object_mut()
        .expect("an object")
        .remove("summary");
    assert!(
        !validator.accepts(&missing_field),
        "a report with no summary must not validate"
    );

    let mut unknown_field = document(ExportOptions::new());
    unknown_field["hosts"][0]["surprise"] = Value::from("undocumented");
    assert!(
        !validator.accepts(&unknown_field),
        "a field the schema does not describe must not validate - that failure \
         is what stops the schema drifting away from the DTO"
    );

    let mut float_timestamp = document(ExportOptions::new());
    float_timestamp["generated_at"] = Value::from(1_770_000_000.5);
    assert!(
        !validator.accepts(&float_timestamp),
        "an epoch float must not pass where an RFC 3339 string is promised"
    );

    let mut rounded_count = document(ExportOptions::new());
    rounded_count["phases"][0]["targets"]["addresses"] = Value::from(256);
    assert!(
        !validator.accepts(&rounded_count),
        "a count that can exceed 2^53 must be a string, not a number"
    );
}

/// Every line of a JSON Lines export has to validate on its own. A record that
/// only means something in the context of the file is a record that cannot be
/// split, filtered or concatenated, which is most of the reason for the format.
#[cfg(feature = "export-jsonl")]
#[test]
fn every_exported_line_matches_the_lines_schema() {
    let validator = Validator::lines();

    for options in [
        ExportOptions::new(),
        ExportOptions::new().with_redaction(Redaction::Standard),
    ] {
        let mut bytes = Vec::new();
        crate::export::JsonLinesExporter::new(options)
            .export(&fixture::report(), &mut bytes)
            .expect("the export succeeds");

        let text = String::from_utf8(bytes).expect("utf-8");
        let mut records = 0;
        for line in text.lines() {
            let record: Value = serde_json::from_str(line).expect("a line parses on its own");
            validator.check(&record);
            records += 1;
        }

        assert_eq!(records, 4, "a report record and three hosts");
    }
}

/// The lines schema is written in terms of the report schema, so it rejects on
/// the same grounds, and also rejects a record naming no type.
#[cfg(feature = "export-jsonl")]
#[test]
fn the_lines_schema_rejects_a_record_it_should_reject() {
    let validator = Validator::lines();

    let host = document(ExportOptions::new())["hosts"][0].clone();
    assert!(
        !validator.accepts(&host),
        "a host object with no `type` is not a record"
    );

    let mut mislabelled = host.clone();
    mislabelled["type"] = Value::from("report");
    assert!(
        !validator.accepts(&mislabelled),
        "a host wearing the report tag must not validate as either"
    );

    let mut tagged = host;
    tagged["type"] = Value::from("host");
    assert!(validator.accepts(&tagged), "a tagged host is a host record");

    let mut surprising = tagged;
    surprising["surprise"] = Value::from("undocumented");
    assert!(
        !validator.accepts(&surprising),
        "a field the schema does not describe must not validate"
    );
}

// ---------------------------------------------------------------------------
// The comparison document
// ---------------------------------------------------------------------------

/// Exports a comparison and parses it back.
fn comparison(
    baseline: &crate::report::ScanReport,
    current: &crate::report::ScanReport,
    options: ExportOptions,
) -> Value {
    use crate::diff::ScanDiff;
    use crate::export::diff::{DiffExporter, JsonDiffExporter};

    let diff = ScanDiff::between(baseline, current);
    let mut bytes = Vec::new();
    JsonDiffExporter::new(options)
        .export(&diff, &mut bytes)
        .expect("the export succeeds");

    serde_json::from_slice(&bytes).expect("the export parses as JSON")
}

#[test]
fn the_published_comparison_schema_compiles() {
    let _ = Validator::diff();
}

/// The version the code emits and the version the schema pins are the same
/// number, counted apart from the report's.
#[test]
fn the_comparison_schema_pins_the_version_the_code_emits() {
    let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("valid JSON");

    assert_eq!(
        schema["properties"]["schema_version"]["const"],
        Value::from(crate::format::DIFF_SCHEMA_VERSION)
    );
}

/// A comparison carrying one of every kind of change is a document the published
/// schema accepts.
#[test]
fn a_comparison_matches_the_published_schema() {
    let (before, after) = fixture::compared();
    let document = comparison(&before, &after, ExportOptions::new());
    Validator::diff().check(&document);
}

/// Two scans that found the same things still produce a document, and it is a
/// valid one: a consumer polling nightly gets the same shape whether or not
/// anything moved.
#[test]
fn an_unchanged_comparison_matches_the_published_schema() {
    let report = fixture::report();
    let document = comparison(&report, &report, ExportOptions::new());

    Validator::diff().check(&document);
    assert_eq!(document["unchanged"], Value::Bool(true));
    assert_eq!(document["hosts"].as_array().map(Vec::len), Some(0));
}

/// Redaction is an export-time policy here as it is for a report, and a
/// comparison leaks the same fields if it is not applied.
#[test]
fn a_redacted_comparison_masks_what_a_redacted_report_masks() {
    let (before, after) = fixture::compared();
    let document = comparison(
        &before,
        &after,
        ExportOptions::new().with_redaction(Redaction::Standard),
    );

    Validator::diff().check(&document);

    let rendered = document.to_string();
    assert!(
        !rendered.contains("router.local") && !rendered.contains("gateway.local"),
        "a hostname survived redaction into the comparison"
    );
    assert!(
        document
            .pointer("/hosts/0/changes")
            .is_some_and(|changes| changes.to_string().contains("name_gained"))
            && !rendered.contains("ROUTER")
            && !rendered.contains("GATEWAY"),
        "a name the host gave for itself survived redaction into the comparison"
    );
    assert!(
        !rendered.contains("2c:cf:67:00:00:01"),
        "a hardware address survived redaction into the comparison"
    );
}

/// What a phase carries worth masking is its attachment, which names a device
/// and its hardware address.
///
/// Neither is less identifying for describing a switch rather than a
/// workstation: a switch name is an internal hostname and a chassis address is a
/// real MAC. Both sit outside the `hosts` array, where every other redaction test
/// looks. The JSON Lines writer is checked alongside because it renders the
/// header through a different type.
#[test]
fn redaction_masks_the_switch_a_phase_says_it_was_plugged_into() {
    let report = fixture::report();
    let options = ExportOptions::new().with_redaction(Redaction::Standard);

    let attachment = report.phases()[0]
        .attachments()
        .first()
        .expect("the fixture records one");
    let name = attachment.device_name().expect("a device name");
    let mac = attachment
        .device_mac()
        .expect("a device address")
        .to_string();

    let mut json = Vec::new();
    JsonExporter::new(options.clone())
        .export(&report, &mut json)
        .expect("the report exports");
    let json = String::from_utf8(json).expect("valid UTF-8");

    assert!(
        !json.contains(name),
        "the switch's name survived redaction: {json}"
    );
    assert!(
        !json.contains(&mac),
        "the switch's hardware address survived redaction"
    );
    assert!(
        json.contains("GigabitEthernet1/0/14"),
        "the port is not a name or an address and is what the finding is for"
    );

    let mut lines = Vec::new();
    crate::export::JsonLinesExporter::new(options)
        .export(&report, &mut lines)
        .expect("the report exports");
    let lines = String::from_utf8(lines).expect("valid UTF-8");

    assert!(
        !lines.contains(name) && !lines.contains(&mac),
        "the header of a record-per-line document leaked what the single \
         document masked"
    );
}

/// Every token the change vocabulary can emit is a value the published schema
/// accepts.
///
/// The document tests above exercise whichever changes the fixtures happen to
/// produce, so a token added to `ChangeDto` could ship past all of them while
/// producing documents no consumer's validator accepts.
#[test]
fn every_change_the_fixtures_produce_is_a_token_the_schema_accepts() {
    let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("valid JSON");
    let accepted: Vec<&str> = schema["$defs"]["change"]["properties"]["kind"]["enum"]
        .as_array()
        .expect("the schema names the tokens it accepts")
        .iter()
        .filter_map(Value::as_str)
        .collect();

    let (before, after) = fixture::compared();
    let document = comparison(&before, &after, ExportOptions::new());
    let mut seen = 0usize;

    for host in document["hosts"].as_array().expect("hosts") {
        for change in host["changes"].as_array().expect("changes") {
            let kind = change["kind"].as_str().expect("a token");
            assert!(accepted.contains(&kind), "'{kind}' is not in the schema");
            seen += 1;
        }
        for port in host["ports"].as_array().expect("ports") {
            for change in port["changes"].as_array().expect("changes") {
                let kind = change["kind"].as_str().expect("a token");
                assert!(accepted.contains(&kind), "'{kind}' is not in the schema");
                seen += 1;
            }
        }
    }

    assert!(seen > 0, "the fixtures produced no changes to check");
}

/// The change kinds the comparison exporter emits, read out of its own source.
///
/// Every kind reaches the document through one of these constructors, and
/// [`ChangeDto::set`] names two. Reading the source avoids needing one of every
/// change constructed by hand, which would rot faster than the list it checks.
fn emitted_change_kinds() -> BTreeSet<String> {
    const SOURCE: &str = include_str!("diff/schema.rs");

    let pattern = Regex::new(
        r#"Self::(?:between|gained|lost|optional|set)\(\s*"([a-z_]+)"(?:\s*,\s*"([a-z_]+)")?"#,
    )
    .expect("a valid pattern");

    let mut kinds = BTreeSet::new();
    for captures in pattern.captures_iter(SOURCE) {
        for group in [1, 2] {
            if let Some(kind) = captures.get(group) {
                kinds.insert(kind.as_str().to_string());
            }
        }
    }
    kinds
}

/// The kinds the published schema will accept.
fn accepted_change_kinds() -> BTreeSet<String> {
    let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("the schema parses");
    schema["$defs"]["change"]["properties"]["kind"]["enum"]
        .as_array()
        .expect("the kind enum is a list")
        .iter()
        .map(|kind| kind.as_str().expect("every kind is a string").to_string())
        .collect()
}

/// The exporter and the schema name the same set of change kinds.
///
/// `a_comparison_matches_the_published_schema` sees only the kinds the fixture
/// produces, so a kind the fixture omits is a kind nothing checks: the exporter
/// could emit one the schema rejects while the conformance suite stays green.
#[test]
fn the_schema_accepts_exactly_the_change_kinds_the_exporter_emits() {
    let emitted = emitted_change_kinds();
    let accepted = accepted_change_kinds();

    assert!(
        !emitted.is_empty(),
        "the source scan found no change kinds, so it is checking nothing"
    );

    let unlisted: Vec<&String> = emitted.difference(&accepted).collect();
    let unemitted: Vec<&String> = accepted.difference(&emitted).collect();

    assert!(
        unlisted.is_empty(),
        "the exporter emits kinds the published schema rejects: {unlisted:?}"
    );
    assert!(
        unemitted.is_empty(),
        "the schema lists kinds nothing emits: {unemitted:?}"
    );
}

/// The two JSON encodings of a host name their fields the same way.
///
/// A `Host` reaches a file twice: as a [`HostRecord`](crate::record::HostRecord)
/// in the journal, and as a `HostDto` in an exported report. They differ in
/// encoding on purpose, since a duration is a `Duration` in one and an integer of
/// microseconds in the other, and the exported document carries derived fields
/// the journal has no reason to store. Where both name the same thing they have
/// to spell it the same way, or a consumer who reads both learns two vocabularies
/// for one domain.
///
/// This compares the field names the two emit. The encoding differences listed
/// below are the only permitted divergence.
#[test]
fn the_journal_and_the_report_spell_a_host_the_same_way() {
    use crate::record::HostRecord;

    /// Fields one side carries and the other has no reason to.
    ///
    /// Each is a decision rather than an oversight, named here so that adding a
    /// field to one side without the other fails this test until somebody says
    /// which it is.
    const RECORD_ONLY: &[&str] = &[
        // The document carries the OS verdict and not the sources behind it.
        "os_evidence",
        // Round-trip samples, which the report renders as statistics instead.
        "rtts",
        "hop_counter",
        // Durations, which the report writes as integers of microseconds.
        "rtt",
        "elapsed",
        "first_reply",
        "last_reply",
        // The interface a link-local range is valid on, and only meaningful
        // with it. The journal and the report have to spell it the same way or a
        // resumed scan disagrees with the report of the scan it resumed.
        "zone",
        // The retry policy, flattened here and nested under `retry` there.
        "retry_effort",
        "retry_max_attempts",
        "retry_timeout_scale",
        "retry_dampen_silent_hosts",
        // serde's own encoding of `SystemTime` and `Duration`. The report writes
        // an RFC 3339 string and an integer of microseconds instead, both of
        // which a person can read.
        "secs_since_epoch",
        "nanos_since_epoch",
        "secs",
        "nanos",
        // A finding's detection identity, nested here and flattened into
        // `id`, `version` and `content_hash` there.
        "detection",
        // Part of `os_evidence`, which the report does not carry.
        "source",
    ];

    /// Fields the report derives for a reader that the journal does not store.
    const REPORT_ONLY: &[&str] = &[
        "alive",
        "families",
        "at",
        "decoration",
        "fe80",
        "mac",
        "vendor",
        "redaction",
        "family",
        "complete",
        "kind",
        "position",
        "data",
        "trip",
        "samples",
        "jitter_us",
        "rtt_avg_us",
        "rtt_max_us",
        "rtt_median_us",
        "rtt_min_us",
        "rtt_us",
        "elapsed_us",
        "first_reply_us",
        "last_reply_us",
        "probe_stats",
        "retry",
        "services",
        "systems",
        // What an accepted cipher suite is worth. The journal stores each suite
        // by its wire number alone and the report spells out the name, the
        // grade and the faults, all of which are derived from the number by the
        // build doing the reading. Storing them would let a record disagree with
        // the engine that reads it back, which is the one thing a derivation
        // cannot do.
        "code",
        "strength",
        "faults",
        "deprecated",
    ];

    let report = fixture::report();
    let host = report.hosts().next().expect("the fixture has a host");

    let recorded: Value =
        serde_json::to_value(HostRecord::from(host)).expect("a host records as JSON");
    let exported = &document(ExportOptions::new())["hosts"][0];

    let record_names = field_names(&recorded);
    let export_names = field_names(exported);

    let unmatched_record: Vec<&String> = record_names
        .difference(&export_names)
        .filter(|name| !RECORD_ONLY.contains(&name.as_str()))
        .collect();
    let unmatched_export: Vec<&String> = export_names
        .difference(&record_names)
        .filter(|name| !REPORT_ONLY.contains(&name.as_str()))
        .collect();

    assert!(
        unmatched_record.is_empty(),
        "the journal names fields the report does not, and they are not listed as \
         journal-only: {unmatched_record:?}"
    );
    assert!(
        unmatched_export.is_empty(),
        "the report names fields the journal does not, and they are not listed as \
         report-only: {unmatched_export:?}"
    );
}

/// Every field name in a JSON value, at any depth.
fn field_names(value: &Value) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    fn walk(value: &Value, names: &mut BTreeSet<String>) {
        match value {
            Value::Object(map) => {
                for (key, child) in map {
                    names.insert(key.clone());
                    walk(child, names);
                }
            }
            Value::Array(items) => items.iter().for_each(|item| walk(item, names)),
            _ => {}
        }
    }
    walk(value, &mut names);
    names
}

/// **Every string the schema declares is one the hostile fixture poisons.**
///
/// The escaping tests — `no_field_of_a_hostile_report_reaches_the_page_unescaped`
/// and its siblings for XML and CSV — are only as wide as
/// [`fixture::hostile`](crate::export::fixture::hostile). A field the fixture
/// leaves clean is a field those tests walk straight past, and the report says
/// nothing about it either way.
///
/// Most string properties are the engine's own — enum names, timestamps,
/// addresses — but not all: `device_name`, `device_mac` and
/// `management_address` come from LLDP and CDP, which are unauthenticated by
/// design and so are written by whoever is on the segment; `extrainfo` comes
/// from a service banner and `kernel` from a fingerprint. Whether the escaping
/// covers a field is established only for the fields the fixture poisons.
///
/// So this is the census that keeps the two in step: a string property added to
/// the schema fails here until the fixture carries a hostile value in it.
/// [`ENGINE_WRITTEN`] is the exemption list, and it is short on purpose.
#[test]
fn the_hostile_fixture_poisons_every_string_the_schema_declares() {
    /// Properties no stranger's bytes can reach, for one of two reasons.
    ///
    /// Most are the engine's own: enum names, timestamps, versions, the
    /// operator's settings. Nothing remote touches them.
    ///
    /// The rest are the more interesting kind — **stranger-chosen, but parsed
    /// into a type before they are ever a string.** `device_mac` and
    /// `management_address` arrive in an LLDP or CDP advertisement, which is to
    /// say from whoever is on the segment, and are read into a `MacAddr` and an
    /// `IpAddr` at the frame reader. What reaches a document is this crate
    /// rendering that value back, so the type is the escaping and a hostile
    /// string cannot survive the trip. Their neighbour `device_name` is a free
    /// string and is *not* exempt.
    const ENGINE_WRITTEN: &[&str] = &[
        "algorithm",
        "at",
        "class",
        "code",
        "confidence",
        "digest",
        "device_mac",
        "digest_algorithm",
        "end",
        "engine_version",
        "excluded_ports",
        "family",
        "first_seen",
        "flags",
        "generated_at",
        "kind",
        "label",
        "last_seen",
        "link",
        "mac",
        "macs",
        "management_address",
        "name",
        "primary_ip",
        "produced_by",
        "protocol",
        "public_key",
        "reason",
        "scanner",
        "severity",
        "signature",
        "source_ip",
        "spec",
        "spoof_mac",
        "start",
        "started_at",
        "state",
        "status",
        "stop_reason",
        "targets",
        "timestamp",
        "validity_end",
        "validity_start",
        "version",
        "withheld",
        "zombie",
        "zone",
    ];

    let mut bytes = Vec::new();
    JsonExporter::new(ExportOptions::new())
        .export(&fixture::hostile(), &mut bytes)
        .expect("the hostile export succeeds");
    let document: Value = serde_json::from_slice(&bytes).expect("it parses as JSON");

    // Every string-valued property the schema declares, by name.
    fn declared(value: &Value, out: &mut BTreeSet<String>) {
        let Some(map) = value.as_object() else {
            return;
        };
        if let Some(Value::Object(properties)) = map.get("properties") {
            for (name, property) in properties {
                let is_string = property.get("type").and_then(Value::as_str) == Some("string")
                    || property
                        .get("type")
                        .and_then(Value::as_array)
                        .is_some_and(|any| any.iter().any(|t| t.as_str() == Some("string")));
                if is_string {
                    out.insert(name.clone());
                }
                declared(property, out);
            }
        }
        for key in ["items", "additionalProperties", "$defs", "definitions"] {
            if let Some(sub) = map.get(key) {
                declared(sub, out);
            }
        }
        if let Some(Value::Object(defs)) = map.get("$defs") {
            for sub in defs.values() {
                declared(sub, out);
            }
        }
        for key in ["oneOf", "anyOf", "allOf"] {
            if let Some(Value::Array(items)) = map.get(key) {
                for item in items {
                    declared(item, out);
                }
            }
        }
    }

    // Every property the hostile document carries a poisoned value in.
    fn poisoned(value: &Value, out: &mut BTreeSet<String>) {
        match value {
            Value::Object(map) => {
                for (name, sub) in map {
                    if sub
                        .as_str()
                        .is_some_and(|text| text.contains(fixture::HOSTILE))
                    {
                        out.insert(name.clone());
                    }
                    if let Value::Array(items) = sub
                        && items
                            .iter()
                            .any(|i| i.as_str().is_some_and(|t| t.contains(fixture::HOSTILE)))
                    {
                        out.insert(name.clone());
                    }
                    poisoned(sub, out);
                }
            }
            Value::Array(items) => {
                for item in items {
                    poisoned(item, out);
                }
            }
            _ => {}
        }
    }

    let schema: Value = serde_json::from_str(SCHEMA).expect("the schema file is valid JSON");
    let mut names = BTreeSet::new();
    declared(&schema, &mut names);
    let mut carried = BTreeSet::new();
    poisoned(&document, &mut carried);

    let clean: Vec<&String> = names
        .iter()
        .filter(|name| !carried.contains(*name) && !ENGINE_WRITTEN.contains(&name.as_str()))
        .collect();

    assert!(
        clean.is_empty(),
        "the schema declares these strings and the hostile fixture leaves them clean, so no \
         escaping test covers them: {clean:?}\n\nEither give the field a hostile value in \
         `fixture::hostile`, or — if no remote host can influence it — add it to \
         ENGINE_WRITTEN with that reasoning."
    );
}

// ---------------------------------------------------------------------------
// Names in the host's own words
// ---------------------------------------------------------------------------

/// Every rendering of the [`fixture::named`] host this build can write, by
/// format: each report format, each comparison format over the earlier record
/// and this one, and over [`fixture::named_late`], whose earlier record names
/// the host only in its text, and each report format over the fold of
/// [`fixture::renamed`], which keeps the text of the record whose names it
/// replaced.
fn named_renderings(options: &ExportOptions) -> Vec<(String, String)> {
    use crate::diff::ScanDiff;
    use crate::export::diff::DiffExporter;
    use crate::merge::{Merge, MergeOptions};
    use crate::report::ScanReport;

    let mut rendered = Vec::new();
    let mut write = |format: String, export: &dyn Fn(&mut Vec<u8>)| {
        let mut bytes = Vec::new();
        export(&mut bytes);
        rendered.push((format, String::from_utf8(bytes).expect("utf-8")));
    };
    let mut reports = |label: &str, report: &ScanReport| {
        for format in crate::export::ExportFormat::all() {
            write(format!("{label}{}", format.extension()), &|bytes| {
                format
                    .exporter(options.clone())
                    .export(report, bytes)
                    .expect("the report exports");
            });
        }
    };

    let (before, after) = fixture::named();
    reports("", &after);

    let (old, new) = fixture::renamed();
    let mut merge = Merge::new(MergeOptions::default());
    merge.add(old).add(new);
    reports("merged ", &merge.finish());

    let (unnamed, _) = fixture::named_late();
    for (label, baseline) in [("", &before), (" named late", &unnamed)] {
        let diff = ScanDiff::between(baseline, &after);
        write(format!("diff json{label}"), &|bytes| {
            crate::export::diff::JsonDiffExporter::new(options.clone())
                .export(&diff, bytes)
                .expect("the comparison exports");
        });
        #[cfg(feature = "export-html")]
        write(format!("diff html{label}"), &|bytes| {
            crate::export::diff::HtmlDiffExporter::new(options.clone())
                .export(&diff, bytes)
                .expect("the comparison exports");
        });
    }

    rendered
}

/// `text` as a reader searching it for a name sees it: without the NULs a
/// reply read byte for byte carries between the letters of a UTF-16 name,
/// however the format wrote them, dropped them or drew them, and in one case.
fn as_searched(text: &str) -> String {
    text.replace(r#"<span class="ctl">U+0000</span>"#, "")
        .replace("\\u0000", "")
        .replace("&#x0;", "")
        .replace("&#0;", "")
        .replace('\0', "")
        .to_lowercase()
}

/// A name the host gave reaches a report inside the text of its own replies
/// as well as in its fields: the raw bytes of an SMB reply in a finding's
/// excerpt, a banner, a title a detection filled from the reply, a service's
/// extra information, a certificate issuer named for the machine. Redaction
/// that masks the fields and leaves the text has masked nothing, so every
/// format, the comparisons and a merge included, is searched for each name,
/// in any case and with the NULs of its UTF-16 spelling taken out.
///
/// A comparison or a merge holds text from records that did not all know the
/// host by the same names, so each is rendered from a pair in which the
/// record whose words name the host is not the one that states the names.
#[test]
fn no_format_carries_a_name_the_host_gave_under_redaction() {
    let names: Vec<String> = [fixture::NAMED_HOST, fixture::NAMED_DOMAIN]
        .iter()
        .map(|name| name.to_lowercase())
        .collect();

    for (format, text) in named_renderings(&ExportOptions::new()) {
        let searched = as_searched(&text);
        assert!(
            names.iter().all(|name| searched.contains(name)),
            "the unredacted {format} does not carry the names, so this test checks nothing"
        );
    }

    // Every leak at once, so a failure says which formats share it.
    let redacted = ExportOptions::new().with_redaction(Redaction::Standard);
    let leaks: Vec<String> = named_renderings(&redacted)
        .into_iter()
        .flat_map(|(format, text)| {
            let searched = as_searched(&text);
            names
                .iter()
                .filter(move |name| searched.contains(name.as_str()))
                .map(move |name| format!("the redacted {format} still names `{name}`"))
        })
        .collect();
    assert!(leaks.is_empty(), "{leaks:#?}");
}

/// Every path under a host record at which the schema declares a free
/// string, as `host.ports[].service.product`: a property of type `string`, or
/// an array of them, reached through every reference. A property that is only
/// one of a fixed set of words is left out, since no host can put a name in
/// it.
fn host_string_paths() -> BTreeSet<String> {
    fn walk(
        node: &Value,
        path: &str,
        defs: &Value,
        within: &mut Vec<String>,
        out: &mut BTreeSet<String>,
    ) {
        if let Some(reference) = node.get("$ref").and_then(Value::as_str) {
            let name = reference
                .rsplit('/')
                .next()
                .expect("a reference names a definition");
            if !within.iter().any(|seen| seen == name) {
                within.push(name.to_owned());
                walk(&defs[name], path, defs, within, out);
                within.pop();
            }
            return;
        }
        for key in ["oneOf", "anyOf", "allOf"] {
            if let Some(Value::Array(branches)) = node.get(key) {
                for branch in branches {
                    walk(branch, path, defs, within, out);
                }
            }
        }
        let is_string = match node.get("type") {
            Some(Value::String(kind)) => kind == "string",
            Some(Value::Array(kinds)) => kinds.iter().any(|kind| kind == "string"),
            _ => false,
        };
        if is_string {
            out.insert(path.to_owned());
        }
        if let Some(items) = node.get("items") {
            walk(items, &format!("{path}[]"), defs, within, out);
        }
        if let Some(Value::Object(properties)) = node.get("properties") {
            for (name, property) in properties {
                walk(property, &format!("{path}.{name}"), defs, within, out);
            }
        }
    }

    let schema: Value = serde_json::from_str(SCHEMA).expect("the schema file is valid JSON");
    let defs = &schema["$defs"];
    let mut paths = BTreeSet::new();
    walk(&defs["host"], "host", defs, &mut Vec::new(), &mut paths);
    paths
}

/// Every path in a rendered host record at which a string names the
/// [`fixture::named`] host, spelled as [`host_string_paths`] spells them.
fn host_paths_naming(host: &Value) -> BTreeSet<String> {
    fn walk(value: &Value, path: &str, out: &mut BTreeSet<String>) {
        match value {
            Value::Object(map) => {
                for (key, sub) in map {
                    walk(sub, &format!("{path}.{key}"), out);
                }
            }
            Value::Array(items) => {
                for item in items {
                    walk(item, &format!("{path}[]"), out);
                }
            }
            Value::String(text) => {
                let searched = as_searched(text);
                if [fixture::NAMED_HOST, fixture::NAMED_DOMAIN]
                    .iter()
                    .any(|name| searched.contains(&name.to_lowercase()))
                {
                    out.insert(path.to_owned());
                }
            }
            _ => {}
        }
    }

    let mut paths = BTreeSet::new();
    walk(host, "host", &mut paths);
    paths
}

/// **Every free string the schema declares for a host carries the host's
/// name in the fixture, or is one no host can fill.**
///
/// `no_format_carries_a_name_the_host_gave_under_redaction` is only as wide
/// as [`fixture::named`]: a field the fixture leaves without a name is a
/// field it walks straight past, and a platform identifier a correlated
/// finding carried reached a redacted report that way. So this is the census
/// that keeps the two in step: a string added to the host record fails here
/// until the fixture names the host in it, or until it is listed below with
/// the reason no host can.
///
/// Then the report masks each rather than dropping it: the finding survives
/// with its claim, and the binary reply that justified it is replaced by a
/// note saying it was withheld, not left out as though there had been none.
#[test]
fn redaction_masks_the_host_s_words_in_every_field_its_replies_fill() {
    /// Strings in a host record that no host's reply and no rule reading one
    /// can fill, each for one of three reasons.
    ///
    /// The engine's own words and figures: timestamps, a detection's identity,
    /// which its author fixed before any host answered, the name a strategy
    /// gives its own evidence, and the name of an interface on the scanning
    /// machine.
    ///
    /// Values parsed into a type before they are ever a string: addresses,
    /// hardware addresses, a fingerprint, a suite's number, rendered back by
    /// this crate from the type.
    ///
    /// Values this crate chose from a closed set of its own, which a reply
    /// only selects among: a protocol version, a cipher suite, a key
    /// algorithm, and an application protocol, which the handshake refuses
    /// unless it is one this crate offered.
    const UNFILLABLE: &[&str] = &[
        "host.findings[].content_hash",
        "host.findings[].id",
        "host.findings[].version",
        "host.first_seen",
        "host.hardware.mac",
        "host.hardware.macs[]",
        "host.ip_protocols[].name",
        "host.ips[]",
        "host.last_seen",
        "host.path[].address",
        "host.ports[].discovery.reason",
        "host.ports[].discovery.source_ip",
        "host.ports[].discovery.timestamp",
        "host.ports[].findings[].content_hash",
        "host.ports[].findings[].id",
        "host.ports[].findings[].version",
        "host.ports[].security.accepts[].suites[].code",
        "host.ports[].security.accepts[].suites[].name",
        "host.ports[].security.accepts[].unrecognised[]",
        "host.ports[].security.alpn[]",
        "host.ports[].security.certificate.fingerprint_sha256",
        "host.ports[].security.certificate.pubkey_type",
        "host.ports[].security.certificate.validity_end",
        "host.ports[].security.certificate.validity_start",
        "host.ports[].security.cipher_suite",
        "host.ports[].security.tls_version",
        "host.primary_ip",
        "host.reasons[].protocol",
        "host.reasons[].source_ip",
        "host.zone",
    ];

    let (_, after) = fixture::named();
    let render = |options: ExportOptions| -> Value {
        let mut bytes = Vec::new();
        JsonExporter::new(options)
            .export(&after, &mut bytes)
            .expect("the report exports");
        serde_json::from_slice::<Value>(&bytes).expect("it parses")["hosts"][0].clone()
    };

    let declared = host_string_paths();
    let named = host_paths_naming(&render(ExportOptions::new()));
    let unfillable: BTreeSet<String> = UNFILLABLE.iter().map(|path| path.to_string()).collect();

    let stale: Vec<&String> = unfillable.difference(&declared).collect();
    assert!(
        stale.is_empty(),
        "the schema declares no such string, so the exemption is stale: {stale:?}"
    );
    let contradicted: Vec<&String> = unfillable.intersection(&named).collect();
    assert!(
        contradicted.is_empty(),
        "the fixture names the host in a string listed as one no host can fill: {contradicted:?}"
    );
    let unnamed: Vec<&String> = declared
        .iter()
        .filter(|path| !named.contains(*path) && !unfillable.contains(*path))
        .collect();
    assert!(
        unnamed.is_empty(),
        "the named fixture leaves these strings without the host's name, so no redaction \
         test covers them: {unnamed:?}\n\nEither name the host in them in \
         `fixture::named`, or, if no host can fill one, add it to UNFILLABLE with that \
         reasoning."
    );

    let host = render(ExportOptions::new().with_redaction(Redaction::Standard));
    let ports = host["ports"].as_array().expect("ports");
    let smb = ports
        .iter()
        .find(|port| port["port"] == 445)
        .expect("the SMB port");
    assert_eq!(smb["findings"][0]["title"], "SMBv1 is enabled on XXXXX");
    assert_eq!(
        smb["findings"][0]["excerpt"],
        crate::export::redact::WITHHELD_EXCERPT
    );
    assert_eq!(smb["service"]["extrainfo"], "workgroup: COXXXXXSO");
    assert_eq!(smb["service"]["cpes"][0], "cpe:/a:samba:samba:4.15:XXXXX");
    let banner = ports
        .iter()
        .find(|port| port["port"] == 40390)
        .expect("the port named by its banner");
    assert_eq!(banner["service"]["name"], "banner: zq7 node fsXXXXXle ok");
    assert_eq!(host["hardware"]["product"], "PowerEdge XXXXX");
    assert_eq!(
        host["os"]["cpes"][0],
        "cpe:/o:microsoft:windows_server_2019:XXXXX"
    );
    let details: Vec<&Value> = host["reasons"]
        .as_array()
        .expect("reasons")
        .iter()
        .map(|reason| &reason["details"])
        .collect();
    assert!(
        details.contains(&&Value::from("syn-ack from XXXXX")),
        "{details:?}"
    );
    let smtp = ports
        .iter()
        .find(|port| port["port"] == 25)
        .expect("the SMTP port");
    assert_eq!(
        smtp["findings"][0]["excerpt"],
        "220 fsXXXXXle Microsoft ESMTP MAIL Service ready"
    );
    let ssh = ports
        .iter()
        .find(|port| port["port"] == 22)
        .expect("the SSH port");
    let correlated = &ssh["findings"][0];
    assert_eq!(correlated["cpe"], "cpe:/a:openbsd:openssh:XXXXX");
    assert_eq!(correlated["cpes"][0], "cpe:/a:openbsd:openssh:XXXXX");
    assert_eq!(correlated["references"][0]["value"], "CVE-2023-38408");
    assert_eq!(
        correlated["references"][1]["value"],
        "https://advisories.example/XXXXX"
    );
}