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
// 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

//! # Report Export
//!
//! Turns a finished [`ScanReport`] into a document somebody else can read: a
//! file on disk, a body in an HTTP response, a stream into another tool.
//!
//! ## Why the engine owns this
//!
//! A file written by the CLI, by a library consumer and by a web UI has to be
//! the same file, or the format is not a format. The schema and its
//! implementation live here, once, and a front end chooses only a format and a
//! destination.
//!
//! ## The shape of the thing
//!
//! - [`schema`] holds the data transfer objects. They are the wire format,
//!   written by hand rather than derived from the engine's working types. See
//!   that module for what the boundary buys.
//! - [`Exporter`] is the one trait a format implements. It takes a report and
//!   somewhere to write, and it streams.
//! - [`ExportOptions`] carries policy that is not the format's business, most
//!   of all [`Redaction`].
//!
//! ## Writing your own
//!
//! [`Exporter`] is public, and the DTOs are public and `Serialize`. A consumer
//! who wants PDF output or their own branded HTML writes an exporter in their
//! own crate, with their own templating engine, and this crate takes on no
//! dependency for it. There is no plugin system: dynamic loading in a process
//! holding raw-socket privileges buys nothing a trait does not.
//!
//! ```
//! use std::io::{self, Write};
//! use zond_engine::report::ScanReport;
//! use zond_engine::export::{ExportError, Exporter};
//!
//! /// Writes one line per host: the address and how many ports it had.
//! struct Tally;
//!
//! impl Exporter for Tally {
//!     fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError> {
//!         for host in report.hosts() {
//!             writeln!(out, "{} {}", host.primary_ip(), host.port_count())?;
//!         }
//!         Ok(())
//!     }
//! }
//! ```
//!
//! ## Always to a writer, never to a string
//!
//! [`Exporter::export`] writes into a `dyn Write` and nothing in this module
//! returns a `String`. A /16 with a host on every address is a document larger
//! than anything worth holding in memory, and writing incrementally means a
//! consumer piping output somewhere sees the first host before the last one is
//! scanned out of the report.
//!
//! ## Features
//!
//! The DTOs and the trait are always available, costing nothing beyond `serde`,
//! which the engine already depends on. Each concrete format sits behind a cargo
//! feature so a consumer who wants none of them pays for none. `export-json` is
//! on by default.

pub mod diff;
pub mod redact;
pub mod schema;

#[cfg(any(
    feature = "export-json",
    feature = "export-jsonl",
    feature = "export-html"
))]
pub(crate) mod write;

#[cfg(feature = "export-json")]
pub mod json;

#[cfg(feature = "export-jsonl")]
pub mod jsonl;

#[cfg(feature = "export-csv")]
pub mod csv;

#[cfg(feature = "export-html")]
pub mod html;

#[cfg(feature = "export-nmap")]
pub mod nmap;

#[cfg(test)]
pub(crate) mod fixture;

#[cfg(all(test, feature = "export-json"))]
mod conformance;

use std::borrow::Cow;
use std::fmt;
use std::io::Write;
use std::path::Path;

use crate::diff::HostDelta;
use crate::model::host::{Host, HostName};
use crate::model::mac::MacAddr;
use crate::report::ScanReport;

#[cfg(feature = "export-json")]
pub use json::JsonExporter;

#[cfg(feature = "export-jsonl")]
pub use jsonl::JsonLinesExporter;

#[cfg(feature = "export-csv")]
pub use csv::CsvExporter;

#[cfg(feature = "export-html")]
pub use html::HtmlExporter;

#[cfg(feature = "export-nmap")]
pub use nmap::NmapXmlExporter;

/// What went wrong while writing a report out.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ExportError {
    /// The destination refused the write: a full disk, a closed pipe, a
    /// permissions problem.
    #[error("writing the report failed: {0}")]
    Io(#[from] std::io::Error),

    /// The report could not be rendered in the target format.
    ///
    /// Separate from [`Io`](Self::Io) because the two call for opposite
    /// responses: a failed write may succeed against a different destination,
    /// while a failed render will not.
    #[error("rendering the report as {format} failed: {message}")]
    Render {
        /// The format that could not represent the report.
        format: &'static str,
        /// What could not be represented.
        message: String,
    },
}

/// One output format.
///
/// An exporter is a rendering of a report onto a writer. Every other decision it
/// needs, how much to redact or whether to indent, belongs to the value
/// implementing this trait and is chosen when that value is constructed, so a
/// consumer can implement it without reading this crate's options type.
pub trait Exporter {
    /// Writes `report` to `out`.
    ///
    /// Implementations must stream: the memory an export costs should be a
    /// function of the largest single host, not of the size of the scan.
    fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError>;
}

/// How much identifying detail to strip on the way out.
///
/// Redaction is an export-time policy rather than something a caller does to a
/// report afterwards, because afterwards is where it gets forgotten. A report
/// destined for a client, an auditor or a bug tracker is masked at the one point
/// where the data leaves the process.
///
/// ## What is masked and what is not
///
/// [`Standard`](Self::Standard) masks the two things that identify a person or a
/// device: names and hardware addresses. Hostnames keep their first and last
/// two characters, so `workstation` and `wifi-printer` stay distinguishable
/// without either being readable. MAC addresses keep their OUI, so the vendor
/// survives and the individual NIC does not.
///
/// A name is masked wherever a host's name appears, not only in the hostname:
/// the names a host gives for itself
/// ([`Host::names`](crate::model::host::Host::names)) and a certificate's
/// subject are masked the same way. That includes a domain or a forest, which
/// names the organisation running the machine and is the most identifying
/// string a report can carry.
///
/// A name is masked in free text too, wherever the host's own replies wrote
/// it: see [`HostRedaction`], which every exporter reads a host's record
/// through. A name the host stated but no protocol recorded as one cannot be
/// found there, and is the second residual leak below; an excerpt that is not
/// text is withheld whole for that reason. A comparison masks both of a
/// host's records by every name either scan knew it by, and a merged report
/// by every name any of its sources did, since the text of each record can
/// name the host by a name only the other states.
///
/// IP addresses are left alone. A report is a list of hosts, and a masking
/// scheme that hides which host is which collapses ten records on a /24 into ten
/// copies of the same string. The addresses are also what makes the findings
/// actionable to a recipient who already knows the network they asked to have
/// scanned.
///
/// Two residual leaks are worth stating. An IPv6 address formed the old EUI-64
/// way embeds the MAC that redaction masks elsewhere, so a report from a
/// network with EUI-64 addressing is not free of hardware identifiers however
/// this is set. And a name a host wrote into a text reply without any protocol
/// having stated it as a name, an HTTP banner naming a machine the scan found
/// no other name for, is text like any other and survives. A merged report
/// written plain and redacted when it is read back is such a report for every
/// name the merge did not keep, having no field that states it.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum Redaction {
    /// Export what the scan found, unchanged.
    #[default]
    None,
    /// Mask host and domain names and hardware addresses.
    Standard,
}

impl Redaction {
    /// Applies the policy to a hostname, or to any other name a report
    /// carries for a host or its domain.
    ///
    /// Borrows when nothing is masked, so an unredacted export of a large scan
    /// does not allocate a string per host to hand back what it was given.
    pub fn hostname<'a>(self, name: &'a str) -> Cow<'a, str> {
        match self {
            Redaction::None => Cow::Borrowed(name),
            Redaction::Standard => Cow::Owned(redact::hostname(name)),
        }
    }

    /// Applies the policy to a hardware address.
    ///
    /// Returns an owned string either way: a [`MacAddr`] has no textual form to
    /// borrow.
    pub fn mac(self, mac: &MacAddr) -> String {
        match self {
            Redaction::None => mac.to_string(),
            Redaction::Standard => redact::mac_addr(mac),
        }
    }

    /// Whether this policy masks anything at all.
    pub fn is_active(self) -> bool {
        !matches!(self, Redaction::None)
    }

    /// The policy as it applies to `host`'s record, for the free text its
    /// replies filled.
    pub fn for_host(self, host: &Host) -> HostRedaction {
        self.for_hosts([host])
    }

    /// The policy as it applies to both records a comparison holds of one
    /// host, masking the names either scan knew it by in the text of both: a
    /// name the later scan dropped is still the host's name in the earlier
    /// one's text, and a reply the earlier scan kept can name the machine
    /// before any service stated the name the later scan records. Every part
    /// of a comparison that renders either record reads it through this one.
    pub fn for_delta(self, delta: &HostDelta) -> HostRedaction {
        self.for_hosts(delta.baseline().into_iter().chain(delta.current()))
    }

    fn for_hosts<'h>(self, hosts: impl IntoIterator<Item = &'h Host>) -> HostRedaction {
        HostRedaction {
            redaction: self,
            needles: if self.is_active() {
                redact::Needle::for_names(hosts.into_iter().flat_map(host_names))
            } else {
                Vec::new()
            },
        }
    }
}

/// The redaction policy as it applies to one host's record: the names that
/// host is known by, masked wherever its own replies wrote them.
///
/// A name reaches a report in two ways. The host's hostname and the names it
/// gave for itself ([`Host::names`]) are fields, masked by
/// [`Redaction::hostname`]. The same names also sit inside text the host sent:
/// a finding's excerpt of the reply, a title a detection filled from it, a
/// service's extra information, an issuer naming the machine that issued it.
/// This finds them there, in every form a reply holds them in: as written, in
/// any case, and in UTF-16LE read a byte to a character, which is how SMB,
/// NTLM and Kerberos carry a name. Each is replaced by the mask its field
/// shows, so a reader still sees which name a line spoke of. The first label
/// of a dotted name is found on its own as well, being the machine's name as
/// a banner gives it, and so is each label after it but the top-level one, as
/// a directory spells a domain in `DC=` parts. A label of under three
/// characters, or a generic one such as the `com` of `example.com.au`, is
/// left, being no one's name.
///
/// An excerpt that is not text is withheld whole under redaction rather than
/// searched ([`excerpt`](Self::excerpt)). A binary reply holds names in forms
/// no search of the text can be sure of, and names the scan never recorded.
///
/// Every exporter in this crate reads a host's free text through one of
/// these: a finding's title, excerpt, remediation, platform identifiers and
/// links, a service's product, version and extra information, an operating
/// system's name and evidence, a certificate's issuer, the hardware's vendor,
/// product, family, model and version, and the details of the evidence that
/// the host is up. A front end printing
/// any of them reads them through one too.
///
/// # Examples
/// ```
/// use zond_engine::export::Redaction;
/// use zond_engine::model::host::{Host, HostName, NameKind, NameSource};
///
/// let mut host = Host::new("192.0.2.10".parse().unwrap());
/// host.record_name(HostName::new(NameKind::NetbiosDomain, NameSource::Smb, "EXAMPLE").unwrap());
///
/// let masking = Redaction::Standard.for_host(&host);
/// assert_eq!(masking.text("Workgroup: EXAMPLE"), "Workgroup: EXXXXXXLE");
/// assert_eq!(masking.text("E\0X\0A\0M\0P\0L\0E\0"), "EXXXXXXLE");
/// assert_eq!(Redaction::None.for_host(&host).text("EXAMPLE"), "EXAMPLE");
/// ```
///
/// The [`Default`] masks nothing, for a part of a record rendered with no
/// policy in force.
#[derive(Debug, Clone, Default)]
pub struct HostRedaction {
    redaction: Redaction,
    needles: Vec<redact::Needle>,
}

impl HostRedaction {
    /// The policy in force, for the fields it applies to directly.
    pub fn redaction(&self) -> Redaction {
        self.redaction
    }

    /// Free text the host's replies filled, with every name it is known by
    /// masked. Borrows when nothing is masked.
    pub fn text<'a>(&self, text: &'a str) -> Cow<'a, str> {
        redact::names_in(text, &self.needles)
    }

    /// A finding's excerpt: masked as [`text`](Self::text) is where it is
    /// text, and replaced by a note saying it was withheld where it is not.
    pub fn excerpt<'a>(&self, excerpt: &'a str) -> Cow<'a, str> {
        if self.redaction.is_active() && redact::is_binary(excerpt) {
            Cow::Borrowed(redact::WITHHELD_EXCERPT)
        } else {
            self.text(excerpt)
        }
    }
}

/// Every name a host is known by: its hostname, the names it gave, and the
/// names a fold of its records set aside, which the text kept from those
/// records still holds.
fn host_names(host: &Host) -> impl Iterator<Item = &str> {
    host.hostname()
        .into_iter()
        .chain(host.names().map(HostName::name))
        .chain(host.set_aside_names())
}

/// Policy that applies to an export regardless of the format it lands in.
///
/// Non-exhaustive and [`Default`]-constructed, so a future option is an
/// additive change rather than a break for everyone who built one of these.
#[must_use]
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ExportOptions {
    /// How much identifying detail to strip.
    pub redaction: Redaction,
}

impl ExportOptions {
    /// Options that export everything, unchanged.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the redaction policy.
    pub fn with_redaction(mut self, redaction: Redaction) -> Self {
        self.redaction = redaction;
        self
    }
}

/// The formats this build can write.
///
/// Front ends pick a format from a file extension rather than from a flag, since
/// an output path such as `report.json` already says what the user wants. It
/// lives in the engine so every front end resolves the same extension to the
/// same format.
///
/// Which variants exist depends on the cargo features the crate was built with.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExportFormat {
    /// A single JSON document. The canonical format: everything the report
    /// holds, in the schema described by [`schema`].
    #[cfg(feature = "export-json")]
    Json,

    /// The same data as [`Json`](Self::Json), one record per line. Streamable,
    /// and a file cut off part way through is still readable.
    #[cfg(feature = "export-jsonl")]
    JsonLines,

    /// A flat table, one row per host and port. Lossy by design, for the
    /// spreadsheet and compliance audience.
    #[cfg(feature = "export-csv")]
    Csv,

    /// A single self-contained page: everything the report holds, laid out to
    /// be read rather than parsed, and to print.
    #[cfg(feature = "export-html")]
    Html,

    /// Nmap-compatible XML, for the ingest pipelines that already exist. Says
    /// `scanner="zond"`: it is nmap's format, not a claim to be nmap.
    #[cfg(feature = "export-nmap")]
    NmapXml,
}

impl ExportFormat {
    /// Resolves a file extension, case-insensitively and without a leading dot.
    ///
    /// Returns `None` for an extension no compiled-in format claims, which the
    /// caller should report as an unsupported format rather than silently
    /// writing JSON into a file named something else.
    pub fn from_extension(extension: &str) -> Option<Self> {
        match extension.to_ascii_lowercase().as_str() {
            #[cfg(feature = "export-json")]
            "json" => Some(ExportFormat::Json),
            // `ndjson` is the other name the same format goes by. The
            // canonical spelling stays `jsonl`.
            #[cfg(feature = "export-jsonl")]
            "jsonl" | "ndjson" => Some(ExportFormat::JsonLines),
            #[cfg(feature = "export-csv")]
            "csv" => Some(ExportFormat::Csv),
            #[cfg(feature = "export-html")]
            "html" | "htm" => Some(ExportFormat::Html),
            #[cfg(feature = "export-nmap")]
            "xml" => Some(ExportFormat::NmapXml),
            _ => None,
        }
    }

    /// Resolves a path by its extension.
    ///
    /// A path with no extension has no format rather than a default one. A
    /// caller who wrote `-o report` has not said what they want.
    pub fn from_path(path: &Path) -> Option<Self> {
        path.extension()
            .and_then(|extension| extension.to_str())
            .and_then(Self::from_extension)
    }

    /// The canonical file extension for this format, without a leading dot.
    pub fn extension(self) -> &'static str {
        match self {
            #[cfg(feature = "export-json")]
            ExportFormat::Json => "json",
            #[cfg(feature = "export-jsonl")]
            ExportFormat::JsonLines => "jsonl",
            #[cfg(feature = "export-csv")]
            ExportFormat::Csv => "csv",
            #[cfg(feature = "export-html")]
            ExportFormat::Html => "html",
            #[cfg(feature = "export-nmap")]
            ExportFormat::NmapXml => "xml",
        }
    }

    /// Every format this build can write.
    ///
    /// Front ends use this to describe their own capabilities, since a help
    /// text listing formats the binary was not built with is worse than none.
    pub fn all() -> &'static [ExportFormat] {
        &[
            #[cfg(feature = "export-json")]
            ExportFormat::Json,
            #[cfg(feature = "export-jsonl")]
            ExportFormat::JsonLines,
            #[cfg(feature = "export-csv")]
            ExportFormat::Csv,
            #[cfg(feature = "export-html")]
            ExportFormat::Html,
            #[cfg(feature = "export-nmap")]
            ExportFormat::NmapXml,
        ]
    }

    /// Builds an exporter for this format under the given options.
    pub fn exporter(self, options: ExportOptions) -> Box<dyn Exporter> {
        // A build with no format feature on has no match arm to hand the
        // options to, and an unused parameter would warn. Such a build cannot
        // reach here anyway: `ExportFormat` has no variants to construct.
        let _ = &options;

        match self {
            #[cfg(feature = "export-json")]
            ExportFormat::Json => Box::new(JsonExporter::new(options)),
            #[cfg(feature = "export-jsonl")]
            ExportFormat::JsonLines => Box::new(JsonLinesExporter::new(options)),
            #[cfg(feature = "export-csv")]
            ExportFormat::Csv => Box::new(CsvExporter::new(options)),
            #[cfg(feature = "export-html")]
            ExportFormat::Html => Box::new(HtmlExporter::new(options)),
            #[cfg(feature = "export-nmap")]
            ExportFormat::NmapXml => Box::new(NmapXmlExporter::new(options)),
        }
    }
}

impl fmt::Display for ExportFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.extension())
    }
}

/// Writes a report in the format named by `path`'s extension.
///
/// The convenience over [`ExportFormat::exporter`] is small and the consistency
/// is not: every front end that resolves a destination to a format should do it
/// the same way.
///
/// Returns `None` if the extension names no format this build supports, leaving
/// the caller to decide what to tell the user. The report is written to `out`,
/// not to `path`; opening the destination, and deciding whether overwriting it
/// is acceptable, stays with the caller.
pub fn export_to(
    path: &Path,
    report: &ScanReport,
    out: &mut dyn Write,
    options: ExportOptions,
) -> Option<Result<(), ExportError>> {
    let format = ExportFormat::from_path(path)?;
    Some(format.exporter(options).export(report, out))
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

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

    #[test]
    fn no_redaction_borrows_rather_than_copying() {
        let borrowed = Redaction::None.hostname("workstation");

        assert!(matches!(borrowed, Cow::Borrowed(_)));
        assert_eq!(borrowed, "workstation");
        assert!(!Redaction::None.is_active());
    }

    /// Masked hostnames must stay distinguishable from each other, or a report
    /// of ten devices becomes a report of one device ten times.
    #[test]
    fn standard_redaction_masks_but_keeps_records_apart() {
        let workstation = Redaction::Standard.hostname("workstation");
        let printer = Redaction::Standard.hostname("wifi-printer");

        assert_eq!(workstation, "woXXXXXon");
        assert_ne!(workstation, printer);
        assert!(Redaction::Standard.is_active());
    }

    /// The vendor has to survive masking. It is the OUI, which is what masking
    /// keeps, and a report without vendors is much less useful for no privacy
    /// gained.
    #[test]
    fn standard_redaction_keeps_the_oui_and_drops_the_device() {
        let mac = MacAddr::new(0x2c, 0xcf, 0x67, 0x00, 0x00, 0x01);

        assert_eq!(Redaction::None.mac(&mac), "2c:cf:67:00:00:01");
        assert_eq!(Redaction::Standard.mac(&mac), "2c:cf:67:XX:XX:XX");
    }

    /// Two records of one host folded into one keep one hostname and a
    /// bounded number of names, and the text of both. A name the fold did
    /// not keep is still the host's name in the text it kept, so the folded
    /// record masks it there as it masks the names it states.
    #[test]
    fn a_folded_record_masks_the_names_its_fold_did_not_keep() {
        use crate::model::host::{NameKind, NameSource};

        let address = "192.0.2.10".parse().expect("an address");
        let mut kept = Host::new(address);
        kept.set_hostname(Some("files.example".to_owned()));
        // A peer inventing a name per connection, until the ceiling on a
        // host's names turns one away.
        let invented = |n: usize| {
            HostName::new(NameKind::Host, NameSource::Ntlm, &format!("peer{n:03}")).expect("a name")
        };
        let mut n = 0;
        while kept.record_name(invented(n)) {
            n += 1;
        }

        let mut folded = Host::new(address);
        folded.set_hostname(Some("archive.example".to_owned()));
        folded.record_name(
            HostName::new(NameKind::NetbiosHost, NameSource::Netbios, "VAULT").expect("a name"),
        );
        kept.merge(folded);

        assert_eq!(kept.hostname(), Some("files.example"));
        assert!(kept.names().all(|name| name.name() != "VAULT"));
        let masked = Redaction::Standard
            .for_host(&kept)
            .text("archive.example is VAULT")
            .to_lowercase();
        assert!(
            !masked.contains("archive") && !masked.contains("vault"),
            "{masked}"
        );
        assert_eq!(
            Redaction::None.for_host(&kept).text("VAULT"),
            "VAULT",
            "nothing is masked without a policy"
        );
    }

    #[test]
    fn a_format_is_resolved_from_a_path_case_insensitively() {
        #[cfg(feature = "export-json")]
        {
            assert_eq!(
                ExportFormat::from_path(Path::new("/tmp/scan.JSON")),
                Some(ExportFormat::Json)
            );
            assert_eq!(ExportFormat::Json.extension(), "json");
            assert_eq!(ExportFormat::Json.to_string(), "json");
        }

        // A destination that names no format must not silently acquire one.
        assert_eq!(ExportFormat::from_path(Path::new("/tmp/scan")), None);
        assert_eq!(ExportFormat::from_extension("pdf"), None);
    }

    /// Anything [`ExportFormat::all`] advertises has to actually produce a
    /// document, or a front end built the same way lists a format it cannot
    /// write.
    #[test]
    fn every_advertised_format_can_build_an_exporter() {
        let report = super::fixture::report();

        for format in ExportFormat::all() {
            let mut sink = Vec::new();

            format
                .exporter(ExportOptions::new())
                .export(&report, &mut sink)
                .expect("an advertised format exports");

            assert!(!sink.is_empty(), "{format} produced nothing at all");
            assert_eq!(
                ExportFormat::from_extension(format.extension()),
                Some(*format),
                "{format} does not resolve from its own extension"
            );
        }
    }

    /// The path-driven entry point has to reach the same exporter a caller
    /// would have built by hand, or the two ways of exporting diverge.
    #[test]
    fn exporting_by_path_matches_exporting_by_format() {
        let report = super::fixture::report();

        for format in ExportFormat::all() {
            let name = format!("scan.{}", format.extension());

            let mut by_path = Vec::new();
            export_to(
                Path::new(&name),
                &report,
                &mut by_path,
                ExportOptions::new(),
            )
            .expect("the extension names a format")
            .expect("the export succeeds");

            assert!(!by_path.is_empty());
        }

        let mut sink = Vec::new();
        assert!(
            export_to(
                Path::new("scan.pdf"),
                &report,
                &mut sink,
                ExportOptions::new()
            )
            .is_none(),
            "an unsupported extension must not quietly produce a file"
        );
        assert!(sink.is_empty());
    }
}