Skip to main content

zond_engine/diff/
host.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # What changed about one host
10//!
11//! A [`HostDelta`] is one machine as the two scans describe it: the record each
12//! side holds, what moved between them, and every endpoint that moved.
13//!
14//! ## Only the verdicts
15//!
16//! The status is compared and the evidence behind it is not: a host that was up
17//! by ARP and is up by TCP has not changed. Round-trip times, hop counters,
18//! measured routes and per-source operating-system evidence are left out for the
19//! same reason. They describe how well the scan saw the host.
20//!
21//! Two operating-system fingerprints are the same finding when they name the same
22//! system, whatever confidence each was recorded at. A current scan that
23//! identified no system reports nothing: it ran without the probes or got too
24//! little back to match. Hardware addresses and the vendor read off them follow
25//! the same rule, since a scan that did not reach the host's segment sees
26//! neither.
27
28use std::collections::{BTreeMap, BTreeSet};
29use std::net::IpAddr;
30
31use crate::diff::change::{Change, Presence};
32use crate::diff::port::{self, Clocks, PortDelta, PresenceFor};
33use crate::diff::scope::ScopeIndex;
34use crate::model::finding::{ClaimId, Finding, Severity};
35use crate::model::host::os::OsFingerprint;
36use crate::model::host::{
37    Filtering, Host, HostName, HostStatus, IpProtocolState, NameSource, NetworkRole,
38};
39use crate::model::mac::MacAddr;
40
41/// One host, as the two scans hold it.
42///
43/// Keyed by [`address`](Self::address), which is the current scan's primary
44/// address where it has a record and the baseline's where it does not.
45#[derive(Debug, Clone)]
46pub struct HostDelta {
47    address: IpAddr,
48    presence: Presence,
49    baseline: Option<Host>,
50    current: Option<Host>,
51    baseline_records: usize,
52    current_records: usize,
53    changes: Vec<HostChange>,
54    ports: Vec<PortDelta>,
55}
56
57impl HostDelta {
58    /// The address this host is reported under.
59    pub fn address(&self) -> IpAddr {
60        self.address
61    }
62
63    /// Which scans hold a record for this host, and what the other one says
64    /// about having covered its address.
65    pub fn presence(&self) -> Presence {
66        self.presence
67    }
68
69    /// The baseline scan's view of this host, if it has one.
70    ///
71    /// Where the baseline held more than one record for it, this is the records
72    /// merged with [`Host::merge`]. See [`is_regrouped`](Self::is_regrouped).
73    pub fn baseline(&self) -> Option<&Host> {
74        self.baseline.as_ref()
75    }
76
77    /// The current scan's view of this host, if it has one, merged the same way.
78    pub fn current(&self) -> Option<&Host> {
79        self.current.as_ref()
80    }
81
82    /// How many records the baseline held for this host, and how many the
83    /// current scan holds.
84    ///
85    /// `(1, 1)` in the ordinary case, and `(0, 1)` or `(1, 0)` for a host only
86    /// one scan has. Anything else is a regrouping.
87    pub fn records(&self) -> (usize, usize) {
88        (self.baseline_records, self.current_records)
89    }
90
91    /// Whether the two scans grouped this host's addresses differently: what one
92    /// holds as a single record the other holds as several.
93    ///
94    /// Typically one scan reached the link layer and the other did not, since
95    /// link-layer evidence is what shows two addresses are one machine. Both
96    /// sides are still compared, merged.
97    pub fn is_regrouped(&self) -> bool {
98        self.baseline_records > 1 || self.current_records > 1
99    }
100
101    /// Everything that moved about the host itself, in a fixed order.
102    pub fn changes(&self) -> &[HostChange] {
103        &self.changes
104    }
105
106    /// Every endpoint that moved, ascending by number and then transport.
107    ///
108    /// Endpoints identical in both scans are not here.
109    pub fn ports(&self) -> &[PortDelta] {
110        &self.ports
111    }
112
113    /// Whether anything is reported for this host at all.
114    pub fn is_empty(&self) -> bool {
115        self.presence.is_in_both() && self.changes.is_empty() && self.ports.is_empty()
116    }
117}
118
119/// Something that moved about a host.
120///
121/// `#[non_exhaustive]` because new protocols let a scan establish more about a
122/// host, and adding a variant should not need a major version.
123#[non_exhaustive]
124#[derive(Debug, Clone, PartialEq)]
125pub enum HostChange {
126    /// Whether the host answers changed. A host that stopped answering moves to
127    /// [`Unknown`](HostStatus::Unknown); only an intermediary saying so produces
128    /// [`Down`](HostStatus::Down).
129    Status(Change<HostStatus>),
130    /// The resolved name changed.
131    Hostname(Change<Option<String>>),
132    /// The names the host gave for itself changed, each list in the model's
133    /// order.
134    ///
135    /// Compared only within the protocols the current scan heard names in. A
136    /// scan that opened no SMB session or read no directory established nothing
137    /// about those names, so a quick scan against a thorough one does not report
138    /// them lost. [`Os`](Self::Os) follows the same rule.
139    Names {
140        /// Names the current scan heard and the baseline did not.
141        gained: Vec<HostName>,
142        /// Names the baseline heard, in a protocol the current scan also heard
143        /// names in, and the current scan did not.
144        lost: Vec<HostName>,
145    },
146    /// The addresses the host answers at changed, each list ascending.
147    Addresses {
148        /// Addresses the current scan found it at and the baseline did not.
149        gained: Vec<IpAddr>,
150        /// Addresses the baseline found it at and the current scan does not.
151        lost: Vec<IpAddr>,
152    },
153    /// What the host was identified as running changed, or was first identified.
154    ///
155    /// The same system at a different confidence is not a change, and a current
156    /// scan that identified nothing is not reported, so `after` is never `None`.
157    ///
158    /// Boxed because a pair of fingerprints is several times the size of any
159    /// other variant, and a change list is mostly the other variants.
160    Os(Box<Change<Option<OsFingerprint>>>),
161    /// The hardware addresses the host was seen at changed, each list ascending.
162    ///
163    /// Only a scan that reached the link layer sees these, so both lists are
164    /// empty when either scan did not.
165    Macs {
166        /// Addresses the current scan saw and the baseline did not.
167        gained: Vec<MacAddr>,
168        /// Addresses the baseline saw and the current scan does not.
169        lost: Vec<MacAddr>,
170    },
171    /// The hardware vendor the address resolves to changed or was first named.
172    /// A current scan that named none is not reported, so `after` is never
173    /// `None`.
174    Vendor(Change<Option<String>>),
175    /// The roles inferred for the host changed, each list ascending.
176    Roles {
177        /// Roles the current scan inferred and the baseline did not.
178        gained: Vec<NetworkRole>,
179        /// Roles the baseline inferred and the current scan does not.
180        lost: Vec<NetworkRole>,
181    },
182    /// What the filter in front of the host was shown to be doing changed, each
183    /// list ascending.
184    ///
185    /// A verdict about the network path, such as a stateful filter appearing or
186    /// one that stopped reassembling fragments.
187    ///
188    /// Each conclusion comes from a comparative probe that runs only when asked
189    /// for, so both lists are empty when
190    /// [`characterise`](crate::report::ScanSettings::characterise) was off in
191    /// either scan.
192    Filtering {
193        /// Conclusions the current scan drew and the baseline did not.
194        gained: Vec<Filtering>,
195        /// Conclusions the baseline drew and the current scan does not.
196        lost: Vec<Filtering>,
197    },
198    /// The IP protocols whose verdict moved, ascending by number.
199    ///
200    /// Only the protocols *both* scans established something about. One that only
201    /// one scan asked about is a difference in what was asked, read the same way
202    /// as [`PortState::Unasked`](crate::model::port::PortState::Unasked) in
203    /// [`port`]. A scan that named a protocol and never reached it holds
204    /// [`IpProtocolState::Unasked`] for it.
205    IpProtocols {
206        /// What moved, ascending by protocol number.
207        changed: Vec<IpProtocolChange>,
208    },
209    /// Findings that appeared on the host, findings the current scan stopped
210    /// claiming, and findings whose severity moved.
211    ///
212    /// Paired by [`ClaimId`], so a detection's own version bump does not read as
213    /// one finding going away and another arriving.
214    Findings {
215        /// Findings the current scan claims and the baseline did not.
216        appeared: Vec<Finding>,
217        /// Findings the baseline claimed and the current scan does not.
218        resolved: Vec<Finding>,
219        /// Findings both scans claim, where the severity moved.
220        reassessed: Vec<Reassessment>,
221    },
222}
223
224/// One IP protocol both scans established something about, graded differently.
225#[non_exhaustive]
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct IpProtocolChange {
228    /// The protocol number.
229    pub protocol: u8,
230    /// Where the verdict moved.
231    pub state: Change<IpProtocolState>,
232}
233
234/// One claim both scans make, graded differently.
235///
236/// A finding going from `Medium` to `Critical` is on both sides, so it shows up
237/// here and not in `appeared` or `resolved`.
238///
239/// Only the severity is compared. A detection re-running writes a fresh excerpt
240/// almost every time.
241#[non_exhaustive]
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct Reassessment {
244    /// The finding as the current scan states it.
245    pub finding: Finding,
246    /// Where the severity moved.
247    pub severity: Change<Severity>,
248}
249
250impl Reassessment {
251    /// `finding`, whose severity moved as `severity` says.
252    pub fn new(finding: Finding, severity: Change<Severity>) -> Self {
253        Self { finding, severity }
254    }
255}
256
257/// Compares one host's two records, either of which may be absent.
258///
259/// Each scope says whether that report walked this address, which decides
260/// whether an absent record is a host that went away or one nobody asked about.
261#[allow(clippy::too_many_arguments)]
262pub(crate) fn compare(
263    baseline: Option<&Host>,
264    current: Option<&Host>,
265    baseline_records: usize,
266    current_records: usize,
267    baseline_scope: &ScopeIndex,
268    current_scope: &ScopeIndex,
269    address: &IpAddr,
270    clocks: &Clocks,
271) -> HostDelta {
272    let address = *address;
273
274    // Each scope is asked about the record the *other* side holds, whose absence
275    // is in question. Where only one side has a record, both ask about it.
276    let known = current
277        .or(baseline)
278        .expect("a delta has a record on one side");
279    let baseline_coverage = baseline_scope.of_host(known);
280    let current_coverage = current_scope.of_host(baseline.or(current).expect("likewise"));
281
282    let presence = match (baseline, current) {
283        (Some(_), Some(_)) => Presence::Both,
284        (None, Some(_)) => Presence::Added {
285            before: baseline_coverage,
286        },
287        (Some(_), None) => Presence::Removed {
288            after: current_coverage,
289        },
290        (None, None) => unreachable!("a host delta has a record on at least one side"),
291    };
292
293    let changes = match (baseline, current) {
294        (Some(before), Some(after)) => changes_between(before, after),
295        _ => Vec::new(),
296    };
297
298    let ports = port::compare(
299        &baseline.map(collect_ports).unwrap_or_default(),
300        &current.map(collect_ports).unwrap_or_default(),
301        PresenceFor {
302            baseline: &|number, protocol| {
303                baseline_scope.endpoint(baseline_coverage, number, protocol)
304            },
305            current: &|number, protocol| current_scope.endpoint(current_coverage, number, protocol),
306        },
307        clocks,
308    );
309
310    HostDelta {
311        address,
312        presence,
313        baseline: baseline.cloned(),
314        current: current.cloned(),
315        baseline_records,
316        current_records,
317        changes,
318        ports,
319    }
320}
321
322/// A host's ports as a slice, so both sides of a comparison can be walked
323/// without re-running the iterator.
324fn collect_ports(host: &Host) -> Vec<&crate::model::port::Port> {
325    host.ports().collect()
326}
327
328/// Everything that moved between two records of the same host.
329fn changes_between(before: &Host, after: &Host) -> Vec<HostChange> {
330    let mut changes = Vec::new();
331
332    if let Some(status) = Change::between(before.status(), after.status()) {
333        changes.push(HostChange::Status(status));
334    }
335
336    if let Some(hostname) = Change::between(
337        before.hostname().map(str::to_owned),
338        after.hostname().map(str::to_owned),
339    ) {
340        changes.push(HostChange::Hostname(hostname));
341    }
342
343    // Only protocols the current scan heard names in. See `HostChange::Names`.
344    let heard: BTreeSet<NameSource> = after.names().map(HostName::source).collect();
345    let (gained, lost) = difference(
346        before
347            .names()
348            .filter(|name| heard.contains(&name.source()))
349            .cloned(),
350        after.names().cloned(),
351    );
352    if !gained.is_empty() || !lost.is_empty() {
353        changes.push(HostChange::Names { gained, lost });
354    }
355
356    let (gained, lost) = difference(before.ips().iter().copied(), after.ips().iter().copied());
357    if !gained.is_empty() || !lost.is_empty() {
358        changes.push(HostChange::Addresses { gained, lost });
359    }
360
361    // Only a current scan that identified the system can say it changed. The
362    // baseline's identification stays readable on the delta's baseline record.
363    if let Some(now) = after.os()
364        && !same_system(before.os(), Some(now))
365    {
366        changes.push(HostChange::Os(Box::new(Change::new(
367            before.os().cloned(),
368            Some(now.clone()),
369        ))));
370    }
371
372    // A record with no hardware addresses is a scan that did not reach the
373    // host's segment.
374    let seen_on_link = |host: &Host| {
375        host.hardware()
376            .is_some_and(|hardware| !hardware.macs().is_empty())
377    };
378    if seen_on_link(before) && seen_on_link(after) {
379        let (gained, lost) = difference(
380            before
381                .hardware()
382                .into_iter()
383                .flat_map(|hardware| hardware.macs().keys().copied()),
384            after
385                .hardware()
386                .into_iter()
387                .flat_map(|hardware| hardware.macs().keys().copied()),
388        );
389        if !gained.is_empty() || !lost.is_empty() {
390            changes.push(HostChange::Macs { gained, lost });
391        }
392    }
393
394    // Same rule as the operating system: a current scan naming none says nothing.
395    if let Some(now) = after.vendor()
396        && before.vendor() != Some(now)
397    {
398        changes.push(HostChange::Vendor(Change::new(
399            before.vendor().map(str::to_owned),
400            Some(now.to_owned()),
401        )));
402    }
403
404    let (gained, lost) = difference(
405        before.network_roles().iter().copied(),
406        after.network_roles().iter().copied(),
407    );
408    if !gained.is_empty() || !lost.is_empty() {
409        changes.push(HostChange::Roles { gained, lost });
410    }
411
412    let (gained, lost) = difference(
413        before.filtering().iter().copied(),
414        after.filtering().iter().copied(),
415    );
416    if !gained.is_empty() || !lost.is_empty() {
417        changes.push(HostChange::Filtering { gained, lost });
418    }
419
420    let changed = ip_protocols_between(before, after);
421    if !changed.is_empty() {
422        changes.push(HostChange::IpProtocols { changed });
423    }
424
425    let (appeared, resolved, reassessed) = findings_between(before.findings(), after.findings());
426    if !appeared.is_empty() || !resolved.is_empty() || !reassessed.is_empty() {
427        changes.push(HostChange::Findings {
428            appeared,
429            resolved,
430            reassessed,
431        });
432    }
433
434    changes
435}
436
437/// The IP protocols whose verdict moved between two records of one host.
438///
439/// A protocol either scan holds at
440/// [`Unasked`](crate::model::host::IpProtocolState::Unasked), or does not hold at
441/// all, is left out: that scan established nothing about it.
442fn ip_protocols_between(before: &Host, after: &Host) -> Vec<IpProtocolChange> {
443    let established = |host: &Host, number: &u8| {
444        host.ip_protocols()
445            .get(number)
446            .copied()
447            .filter(IpProtocolState::is_established)
448    };
449
450    before
451        .ip_protocols()
452        .keys()
453        .filter_map(|number| {
454            let was = established(before, number)?;
455            let is = established(after, number)?;
456            Change::between(was, is).map(|state| IpProtocolChange {
457                protocol: *number,
458                state,
459            })
460        })
461        .collect()
462}
463
464/// The findings one subject gained and lost between two scans.
465///
466/// Paired on [`ClaimId`], so a detection re-running with a fresh excerpt for the
467/// same claim is not a change.
468pub(super) fn findings_between<'a>(
469    before: impl Iterator<Item = &'a Finding>,
470    after: impl Iterator<Item = &'a Finding>,
471) -> (Vec<Finding>, Vec<Finding>, Vec<Reassessment>) {
472    let before: BTreeMap<ClaimId, &Finding> = before.map(|f| (f.claim_id(), f)).collect();
473    let after: BTreeMap<ClaimId, &Finding> = after.map(|f| (f.claim_id(), f)).collect();
474
475    let appeared = after
476        .iter()
477        .filter(|(claim, _)| !before.contains_key(*claim))
478        .map(|(_, finding)| (*finding).clone())
479        .collect();
480    let resolved = before
481        .iter()
482        .filter(|(claim, _)| !after.contains_key(*claim))
483        .map(|(_, finding)| (*finding).clone())
484        .collect();
485    let reassessed = after
486        .iter()
487        .filter_map(|(claim, finding)| {
488            let was = before.get(claim)?;
489            Change::between(was.severity(), finding.severity()).map(|severity| Reassessment {
490                finding: (*finding).clone(),
491                severity,
492            })
493        })
494        .collect();
495
496    (appeared, resolved, reassessed)
497}
498
499/// Whether two fingerprints name the same system.
500///
501/// Compares the identification only, ignoring accuracy figures and the evidence
502/// string.
503fn same_system(before: Option<&OsFingerprint>, after: Option<&OsFingerprint>) -> bool {
504    match (before, after) {
505        (None, None) => true,
506        (Some(before), Some(after)) => {
507            before.name() == after.name()
508                && before.family() == after.family()
509                && before.device() == after.device()
510                && before.generation() == after.generation()
511                && before.vendor() == after.vendor()
512                && before.kernel() == after.kernel()
513                && before.arch() == after.arch()
514                && before.cpes() == after.cpes()
515        }
516        _ => false,
517    }
518}
519
520/// What one set gained and lost against another, both ascending.
521fn difference<T: Ord + Clone>(
522    before: impl Iterator<Item = T>,
523    after: impl Iterator<Item = T>,
524) -> (Vec<T>, Vec<T>) {
525    let before: BTreeSet<T> = before.collect();
526    let after: BTreeSet<T> = after.collect();
527
528    let gained = after.difference(&before).cloned().collect();
529    let lost = before.difference(&after).cloned().collect();
530    (gained, lost)
531}
532
533// ╔════════════════════════════════════════════╗
534// ║ ████████╗███████╗███████╗████████╗███████╗ ║
535// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
536// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
537// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
538// ║    ██║   ███████╗███████║   ██║   ███████║ ║
539// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
540// ╚════════════════════════════════════════════╝
541
542#[cfg(test)]
543mod tests {
544    use std::net::Ipv4Addr;
545
546    use super::*;
547    use crate::model::confidence::Confidence;
548    use crate::model::finding::{DetectionClass, DetectionId, Reference, Severity, Version};
549
550    fn host(last: u8) -> Host {
551        let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, last)));
552        host.set_status(HostStatus::Up);
553        host
554    }
555
556    fn finding(id: &str, title: &str, severity: Severity) -> Finding {
557        Finding::new(
558            DetectionId::new(id, Version::new(1, 0, 0), "hash").expect("a valid detection id"),
559            title,
560            severity,
561            Confidence::Certain,
562            DetectionClass::Passive,
563        )
564        .expect("a titled finding")
565    }
566
567    fn findings_change(
568        changes: &[HostChange],
569    ) -> Option<(&[Finding], &[Finding], &[Reassessment])> {
570        changes.iter().find_map(|change| match change {
571            HostChange::Findings {
572                appeared,
573                resolved,
574                reassessed,
575            } => Some((
576                appeared.as_slice(),
577                resolved.as_slice(),
578                reassessed.as_slice(),
579            )),
580            _ => None,
581        })
582    }
583
584    /// A filter that appeared in front of a host is a change to the network.
585    /// `characterise` draws each conclusion from a comparative probe, so it is a
586    /// fact about the path.
587    #[test]
588    fn a_filter_that_appeared_in_front_of_a_host_is_reported() {
589        use crate::model::host::Filtering;
590
591        let before = host(1);
592        let mut after = host(1);
593        after.add_filtering(Filtering::StatefulFilter);
594
595        let changes = changes_between(&before, &after);
596        let filtering = changes
597            .iter()
598            .find_map(|change| match change {
599                HostChange::Filtering { gained, lost } => Some((gained, lost)),
600                _ => None,
601            })
602            .expect("a filtering change");
603
604        assert_eq!(filtering.0, &[Filtering::StatefulFilter]);
605        assert!(filtering.1.is_empty());
606
607        // Two scans that both went without the probe report nothing.
608        assert!(
609            changes_between(&host(1), &host(1))
610                .iter()
611                .all(|change| !matches!(change, HostChange::Filtering { .. }))
612        );
613    }
614
615    /// A name is compared only in a protocol the current scan heard. A rescan
616    /// that asked no directory said nothing about what the directory calls
617    /// itself, so a thorough baseline's names do not read as gone.
618    #[test]
619    fn a_name_is_compared_only_in_a_protocol_the_current_scan_heard() {
620        use crate::model::host::NameKind;
621
622        let name = |kind, source, name| HostName::new(kind, source, name).expect("a name");
623        let old_host = name(NameKind::Host, NameSource::Ntlm, "dc01.corp.example");
624        let new_host = name(NameKind::Host, NameSource::Ntlm, "dc02.corp.example");
625        let directory = name(NameKind::Domain, NameSource::Ldap, "corp.example");
626
627        let mut before = host(1);
628        before.record_name(old_host.clone());
629        before.record_name(directory);
630        let mut after = host(1);
631        after.record_name(new_host.clone());
632
633        let changes = changes_between(&before, &after);
634        let names = changes
635            .iter()
636            .find_map(|change| match change {
637                HostChange::Names { gained, lost } => Some((gained, lost)),
638                _ => None,
639            })
640            .expect("the renamed machine is a change");
641        assert_eq!(names.0, &[new_host]);
642        assert_eq!(
643            names.1,
644            &[old_host],
645            "the directory's domain is not lost: nothing asked it"
646        );
647
648        assert!(
649            changes_between(&before, &host(1))
650                .iter()
651                .all(|change| !matches!(change, HostChange::Names { .. })),
652            "a scan that heard no names says nothing about them"
653        );
654    }
655
656    /// A system the current scan did not identify is not a change: the scan ran
657    /// without operating-system probes or got too little back to match. A
658    /// different system named is still a change.
659    #[test]
660    fn a_system_the_current_scan_did_not_identify_is_not_a_change() {
661        let mut before = host(1);
662        before.set_os(OsFingerprint::new("Linux", 90).with_family("Linux"));
663
664        let unidentified = host(1);
665        assert!(
666            changes_between(&before, &unidentified)
667                .iter()
668                .all(|change| !matches!(change, HostChange::Os(_))),
669            "{:?}",
670            changes_between(&before, &unidentified)
671        );
672
673        let mut other = host(1);
674        other.set_os(OsFingerprint::new("Windows", 90).with_family("Windows"));
675        assert!(
676            changes_between(&before, &other)
677                .iter()
678                .any(|change| matches!(change, HostChange::Os(_)))
679        );
680        assert!(
681            changes_between(&unidentified, &before)
682                .iter()
683                .any(|change| matches!(change, HostChange::Os(_))),
684            "a system identified where none was is still reported"
685        );
686    }
687
688    /// A current scan that did not reach the host's segment loses none of its
689    /// hardware. A scan from beyond a router records no hardware addresses or
690    /// vendor, and that is not the host losing them.
691    #[test]
692    fn a_scan_that_did_not_reach_the_segment_loses_no_hardware() {
693        let mac = MacAddr::new(0x02, 0, 0, 0, 0, 1);
694        use crate::model::host::hardware::{HardwareDescription, HardwareInfo};
695
696        let mut hardware = HardwareInfo::new(mac);
697        hardware.merge(
698            HardwareInfo::described(HardwareDescription {
699                vendor: Some("Example Devices"),
700                ..HardwareDescription::default()
701            })
702            .expect("a vendor is a description"),
703        );
704        let mut before = host(1);
705        before.set_hardware(hardware);
706        assert_eq!(before.vendor(), Some("Example Devices"), "the fixture");
707
708        let changes = changes_between(&before, &host(1));
709        assert!(
710            changes
711                .iter()
712                .all(|change| !matches!(change, HostChange::Macs { .. } | HostChange::Vendor(_))),
713            "{changes:?}"
714        );
715
716        let mut replaced = host(1);
717        replaced.record_mac(MacAddr::new(0x02, 0, 0, 0, 0, 2));
718        let changes = changes_between(&before, &replaced);
719        assert!(
720            changes
721                .iter()
722                .any(|change| matches!(change, HostChange::Macs { .. })),
723            "another address seen on the segment is still a change: {changes:?}"
724        );
725    }
726
727    #[test]
728    fn a_host_that_did_not_move_reports_nothing() {
729        let before = host(1);
730        let after = host(1);
731        assert!(changes_between(&before, &after).is_empty());
732    }
733
734    /// A finding arriving is a change, even on a host where nothing else moved.
735    #[test]
736    fn a_finding_that_appeared_is_reported() {
737        let before = host(1);
738        let mut after = host(1);
739        after.add_finding(finding("cve", "Log4Shell", Severity::Critical));
740
741        let changes = changes_between(&before, &after);
742        let (appeared, resolved, _) = findings_change(&changes).expect("a findings change");
743        assert_eq!(appeared.len(), 1);
744        assert_eq!(appeared[0].title(), "Log4Shell");
745        assert!(resolved.is_empty());
746    }
747
748    #[test]
749    fn a_finding_that_went_away_is_reported_as_resolved() {
750        let mut before = host(1);
751        before.add_finding(finding("cve", "Log4Shell", Severity::Critical));
752        let after = host(1);
753
754        let changes = changes_between(&before, &after);
755        let (appeared, resolved, _) = findings_change(&changes).expect("a findings change");
756        assert!(appeared.is_empty());
757        assert_eq!(resolved.len(), 1);
758        assert_eq!(resolved[0].title(), "Log4Shell");
759    }
760
761    #[test]
762    fn the_same_finding_on_both_sides_is_not_a_change() {
763        let mut before = host(1);
764        before.add_finding(finding("cve", "Log4Shell", Severity::Critical));
765        let mut after = host(1);
766        after.add_finding(finding("cve", "Log4Shell", Severity::Critical));
767
768        assert!(findings_change(&changes_between(&before, &after)).is_none());
769    }
770
771    /// A detection publishing a new version of itself keeps the same
772    /// [`ClaimId`], so it is the same claim.
773    #[test]
774    fn a_detection_version_bump_is_not_a_finding_appearing() {
775        let mut before = host(1);
776        before.add_finding(
777            Finding::new(
778                DetectionId::new("cve", Version::new(1, 0, 0), "hash").unwrap(),
779                "Log4Shell",
780                Severity::Critical,
781                Confidence::Certain,
782                DetectionClass::Passive,
783            )
784            .unwrap()
785            .with_reference(Reference::cve("CVE-2021-44228").unwrap()),
786        );
787        let mut after = host(1);
788        after.add_finding(
789            Finding::new(
790                DetectionId::new("cve", Version::new(2, 0, 0), "other").unwrap(),
791                "Log4Shell, restated",
792                Severity::Critical,
793                Confidence::Certain,
794                DetectionClass::Passive,
795            )
796            .unwrap()
797            .with_reference(Reference::cve("CVE-2021-44228").unwrap()),
798        );
799
800        assert!(
801            findings_change(&changes_between(&before, &after)).is_none(),
802            "the same CVE under one detection is one claim across versions"
803        );
804    }
805
806    #[test]
807    fn a_severity_that_moved_under_one_claim_is_reported_as_a_reassessment() {
808        let mut before = host(1);
809        before.add_finding(finding("audit", "Deprecated TLS", Severity::Medium));
810        let mut after = host(1);
811        after.add_finding(finding("audit", "Deprecated TLS", Severity::Critical));
812
813        let changes = changes_between(&before, &after);
814        let (appeared, resolved, reassessed) =
815            findings_change(&changes).expect("a findings change");
816        assert!(
817            appeared.is_empty() && resolved.is_empty(),
818            "the claim is on both sides, so it neither appeared nor resolved"
819        );
820        assert_eq!(reassessed.len(), 1);
821        assert_eq!(reassessed[0].severity.before, Severity::Medium);
822        assert_eq!(reassessed[0].severity.after, Severity::Critical);
823        assert_eq!(reassessed[0].finding.title(), "Deprecated TLS");
824    }
825
826    /// A detection re-running writes a fresh excerpt almost every time. Only the
827    /// severity is compared, so that is not a change.
828    #[test]
829    fn an_excerpt_that_changed_under_one_claim_is_not_a_reassessment() {
830        use crate::model::finding::Excerpt;
831
832        let mut before = host(1);
833        before.add_finding(
834            finding("audit", "Deprecated TLS", Severity::Medium).with_excerpt(Excerpt::new("one")),
835        );
836        let mut after = host(1);
837        after.add_finding(
838            finding("audit", "Deprecated TLS", Severity::Medium).with_excerpt(Excerpt::new("two")),
839        );
840
841        assert!(findings_change(&changes_between(&before, &after)).is_none());
842    }
843
844    #[test]
845    fn two_findings_from_one_detection_are_told_apart_by_subject() {
846        let before = host(1);
847        let mut after = host(1);
848        after.add_finding(finding("audit", "Weak cipher", Severity::Medium));
849        after.add_finding(finding("audit", "Expired certificate", Severity::High));
850
851        let changes = changes_between(&before, &after);
852        let (appeared, _, _) = findings_change(&changes).expect("a findings change");
853        assert_eq!(appeared.len(), 2);
854    }
855}