zond_engine/diff/change.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//! # The building blocks of every delta
10//!
11//! [`Change`] is a field that moved, [`Presence`] is a record that one side has
12//! and the other lacks, and [`Coverage`] is what a report says about whether it
13//! looked. Host, port, service and certificate deltas are all built from these.
14
15use std::fmt;
16
17/// A value that differs between the two scans.
18///
19/// Every field-level difference takes this shape. A field that is always present
20/// carries the values directly, as `Change<PortState>`; a field that may be absent
21/// carries `Option`s, as `Change<Option<String>>`, where `before: None` reads as
22/// gained and `after: None` as lost.
23///
24/// The changes a comparison builds never hold two equal values:
25/// [`between`](Self::between) returns `None` when nothing moved.
26///
27/// ```
28/// use zond_engine::diff::Change;
29///
30/// assert_eq!(Change::between(80, 80), None);
31///
32/// let moved = Change::between(Some("1.18.0"), Some("1.24.0")).unwrap();
33/// assert!(moved.is_replacement());
34/// assert_eq!(moved.before, Some("1.18.0"));
35/// ```
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37pub struct Change<T> {
38 /// What the baseline scan found.
39 pub before: T,
40 /// What the current scan found.
41 pub after: T,
42}
43
44impl<T> Change<T> {
45 /// The change from `before` to `after`, or `None` if they are equal.
46 pub fn between(before: T, after: T) -> Option<Self>
47 where
48 T: PartialEq,
49 {
50 (before != after).then_some(Self { before, after })
51 }
52
53 /// A change between two values a caller has already established differ.
54 ///
55 /// For fields whose equality is not the derived one. An operating system
56 /// identified at 80% and then at 92% confidence is the same finding, so the
57 /// host comparison decides equality itself and builds the change here.
58 pub fn new(before: T, after: T) -> Self {
59 Self { before, after }
60 }
61
62 /// The change with each side passed through `f`.
63 pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> Change<U> {
64 Change {
65 before: f(self.before),
66 after: f(self.after),
67 }
68 }
69}
70
71impl<T> Change<Option<T>> {
72 /// Whether the current scan found something the baseline did not.
73 pub fn is_gain(&self) -> bool {
74 self.before.is_none() && self.after.is_some()
75 }
76
77 /// Whether the baseline found something the current scan did not.
78 pub fn is_loss(&self) -> bool {
79 self.before.is_some() && self.after.is_none()
80 }
81
82 /// Whether both scans found something and the two differ.
83 pub fn is_replacement(&self) -> bool {
84 self.before.is_some() && self.after.is_some()
85 }
86}
87
88impl<T: fmt::Display> fmt::Display for Change<T> {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 write!(f, "{} -> {}", self.before, self.after)
91 }
92}
93
94/// Which of the two scans holds a record, and what the other one says about
95/// having looked.
96///
97/// A host missing from tonight's scan is gone if tonight's scan covered its
98/// address, and merely unobserved if it did not. The coverage travels with the
99/// presence so a consumer can tell the two apart.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub enum Presence {
102 /// Both scans have a record. The difference between them, if any, is in the
103 /// delta's change list.
104 Both,
105 /// Only the current scan has a record, and `before` is what the baseline
106 /// says about whether it covered this target.
107 ///
108 /// [`Coverage::Covered`] makes this a real appearance. Anything else makes
109 /// it a target the baseline never asked about.
110 Added {
111 /// What the baseline scan says about having covered this target.
112 before: Coverage,
113 },
114 /// Only the baseline has a record, and `after` is what the current scan says
115 /// about whether it covered this target.
116 ///
117 /// [`Coverage::Covered`] makes this a real disappearance. Anything else
118 /// makes it a target the current scan never asked about.
119 Removed {
120 /// What the current scan says about having covered this target.
121 after: Coverage,
122 },
123}
124
125impl Presence {
126 /// Whether both scans hold a record.
127 pub fn is_in_both(&self) -> bool {
128 matches!(self, Presence::Both)
129 }
130
131 /// Whether the record is only in the current scan.
132 pub fn is_added(&self) -> bool {
133 matches!(self, Presence::Added { .. })
134 }
135
136 /// Whether the record is only in the baseline scan.
137 pub fn is_removed(&self) -> bool {
138 matches!(self, Presence::Removed { .. })
139 }
140
141 /// What the scan lacking a record says about having covered the target.
142 ///
143 /// `None` when both scans hold one.
144 pub fn counterpart_coverage(&self) -> Option<Coverage> {
145 match self {
146 Presence::Both => None,
147 Presence::Added { before } => Some(*before),
148 Presence::Removed { after } => Some(*after),
149 }
150 }
151
152 /// Whether the scan lacking a record is known to have covered the target,
153 /// which makes an appearance or disappearance a finding about the network.
154 /// True when both scans hold a record.
155 pub fn is_confirmed(&self) -> bool {
156 self.counterpart_coverage()
157 .is_none_or(|coverage| coverage == Coverage::Covered)
158 }
159}
160
161/// What a report says about whether it looked at a target.
162///
163/// Mostly read off the [`TargetScope`](crate::report::TargetScope) of the
164/// report's phases, which record the ranges a scan walked after its exclusion
165/// policy and the ranges that policy withheld. A report with no scope, such as one
166/// rebuilt from a foreign scanner's output or from a scan that stopped before
167/// writing a phase, answers [`Unstated`](Self::Unstated).
168///
169/// [`Unreached`](Self::Unreached) comes from the record itself and overrules the
170/// scope: a scope says what a scan set out to walk, while a port recorded
171/// [`Unasked`](crate::model::port::PortState::Unasked) or an address a phase names
172/// as [`undecided`](crate::report::ScanPhase::undecided) says how far it got.
173#[non_exhaustive]
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum Coverage {
176 /// The report says a phase walked this target.
177 Covered,
178 /// The report says an exclusion policy withheld this target. The scan was
179 /// forbidden to look, so nothing here is evidence about the network.
180 Withheld,
181 /// The report states what it walked, and this target was not in it.
182 OutOfScope,
183 /// The scan named this target and ran short before probing it. The record
184 /// says so by carrying the endpoint at
185 /// [`PortState::Unasked`](crate::model::port::PortState::Unasked), or by
186 /// naming the address among a phase's
187 /// [`undecided`](crate::report::ScanPhase::undecided) ones where no phase
188 /// reached a verdict on it.
189 ///
190 /// This keeps a scan cut short by its wall clock from reporting every port it
191 /// did not reach as closed.
192 Unreached,
193 /// The report does not say what it covered, so whether it looked is unknown.
194 Unstated,
195}
196
197impl Coverage {
198 /// Every answer, in declaration order.
199 ///
200 /// The export conformance suite checks this against the exported comparison
201 /// schema's list, so a new answer cannot ship without a schema name that
202 /// consumers' validators accept.
203 pub const ALL: &'static [Self] = &[
204 Self::Covered,
205 Self::Withheld,
206 Self::OutOfScope,
207 Self::Unreached,
208 Self::Unstated,
209 ];
210
211 /// Whether the report is known to have walked the target.
212 pub fn is_covered(&self) -> bool {
213 matches!(self, Coverage::Covered)
214 }
215
216 /// Whether the report is known not to have walked the target, for either
217 /// reason.
218 ///
219 /// [`Unreached`](Self::Unreached) answers false here and to
220 /// [`is_covered`](Self::is_covered).
221 pub fn is_excluded(&self) -> bool {
222 matches!(self, Coverage::Withheld | Coverage::OutOfScope)
223 }
224}
225
226impl fmt::Display for Coverage {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 match self {
229 Coverage::Covered => write!(f, "covered"),
230 Coverage::Withheld => write!(f, "withheld"),
231 Coverage::OutOfScope => write!(f, "out of scope"),
232 Coverage::Unreached => write!(f, "unreached"),
233 Coverage::Unstated => write!(f, "unstated"),
234 }
235 }
236}
237
238// ╔════════════════════════════════════════════╗
239// ║ ████████╗███████╗███████╗████████╗███████╗ ║
240// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
241// ║ ██║ █████╗ ███████╗ ██║ ███████╗ ║
242// ║ ██║ ██╔══╝ ╚════██║ ██║ ╚════██║ ║
243// ║ ██║ ███████╗███████║ ██║ ███████║ ║
244// ║ ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚══════╝ ║
245// ╚════════════════════════════════════════════╝
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 /// A delta's change list holds only changes.
252 #[test]
253 fn a_value_that_did_not_move_is_not_a_change() {
254 assert!(Change::between(1, 1).is_none());
255 assert!(Change::between(Some("ssh"), Some("ssh")).is_none());
256 assert!(Change::between(None::<&str>, None).is_none());
257 }
258
259 #[test]
260 fn a_value_that_moved_carries_both_sides() {
261 let change = Change::between(1, 2).expect("a change");
262 assert_eq!(change.before, 1);
263 assert_eq!(change.after, 2);
264 }
265
266 #[test]
267 fn an_optional_field_reads_as_gain_loss_or_replacement() {
268 let gained = Change::new(None, Some("ssh"));
269 assert!(gained.is_gain() && !gained.is_loss() && !gained.is_replacement());
270
271 let lost = Change::new(Some("ssh"), None);
272 assert!(lost.is_loss() && !lost.is_gain() && !lost.is_replacement());
273
274 let replaced = Change::new(Some("ssh"), Some("http"));
275 assert!(replaced.is_replacement() && !replaced.is_gain() && !replaced.is_loss());
276 }
277
278 #[test]
279 fn mapping_a_change_keeps_both_sides_in_place() {
280 let mapped = Change::new(1u8, 2u8).map(|n| n * 10);
281 assert_eq!((mapped.before, mapped.after), (10, 20));
282 }
283
284 #[test]
285 fn a_record_in_both_scans_raises_no_coverage_question() {
286 assert!(Presence::Both.is_in_both());
287 assert_eq!(Presence::Both.counterpart_coverage(), None);
288 assert!(Presence::Both.is_confirmed());
289 }
290
291 /// An appearance is a finding about the network only when the scan that
292 /// lacked the record is known to have looked.
293 #[test]
294 fn an_appearance_is_confirmed_only_where_the_baseline_covered_the_target() {
295 let looked = Presence::Added {
296 before: Coverage::Covered,
297 };
298 assert!(looked.is_added() && looked.is_confirmed());
299
300 for unconfirmed in [Coverage::Withheld, Coverage::OutOfScope, Coverage::Unstated] {
301 let presence = Presence::Added {
302 before: unconfirmed,
303 };
304 assert!(
305 !presence.is_confirmed(),
306 "{unconfirmed:?} does not confirm an appearance"
307 );
308 }
309 }
310
311 #[test]
312 fn a_disappearance_asks_the_same_question_of_the_later_scan() {
313 let looked = Presence::Removed {
314 after: Coverage::Covered,
315 };
316 assert!(looked.is_removed() && looked.is_confirmed());
317
318 let did_not = Presence::Removed {
319 after: Coverage::OutOfScope,
320 };
321 assert!(!did_not.is_confirmed());
322 }
323
324 #[test]
325 fn only_covered_ground_counts_as_covered() {
326 assert!(Coverage::Covered.is_covered());
327 for other in [Coverage::Withheld, Coverage::OutOfScope, Coverage::Unstated] {
328 assert!(!other.is_covered(), "{other:?} is not coverage");
329 }
330 assert!(Coverage::Withheld.is_excluded());
331 assert!(!Coverage::Unstated.is_excluded());
332 }
333}