Skip to main content

zond_engine/model/
finding.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 is wrong with what is running
10//!
11//! [`Evidence`](crate::fingerprint::Evidence) says what is running on a port and a
12//! [`Finding`] says what is wrong with it. Every kind of detection (a signature, a
13//! declarative flow, a sandboxed module, the built-in CVE correlator) produces this one
14//! type, so they compose without knowing about one another.
15//!
16//! A finding is a **positive claim, backed by evidence, about a subject the scan
17//! already holds**: a vulnerable service on a port, a weakness inferred across a host.
18//! The [`Host`](crate::model::host) or [`Port`](crate::model::port) it is about carries
19//! it. An absent finding is not a claim that the subject is clean: the detection did not
20//! run, or ran and did not fire.
21//!
22//! ## Two axes
23//!
24//! - [`Severity`]: how bad it is if true.
25//! - [`Confidence`]: how sure it is true, the same trust vocabulary fingerprinting uses.
26//!
27//! A single "risk" number cannot say *Critical but unverified*, which is the common
28//! case: a distribution backports a security fix without moving the version string, so
29//! a version-matched CVE is severe and uncertain at once.
30//!
31//! ## Provenance
32//!
33//! A finding always names the [`DetectionId`] that produced it: an id, a [`Version`],
34//! and the content hash of the detection body. The report records that stamp, so a
35//! finding stays reproducible and auditable after the scan, and a detection from a
36//! stranger can still answer for itself.
37
38use std::collections::BTreeSet;
39use std::fmt;
40use std::str::FromStr;
41
42use thiserror::Error;
43
44use crate::model::confidence::Confidence;
45use crate::model::port::Build;
46
47/// The most justifying text a finding retains, in bytes.
48///
49/// The excerpt is target-controlled and travels into every export and journal, so it is
50/// bounded: a multi-megabyte banner would be a denial of service on the report. The full
51/// bytes live in the journal's recorded exchange. Two kilobytes is more than a person
52/// reads to see why a finding fired.
53pub const MAX_EXCERPT_BYTES: usize = 2048;
54
55/// The most distinct findings one subject, meaning a single host or a single
56/// port, retains.
57///
58/// Findings deduplicate by claim, so a claim fired a thousand times occupies one slot.
59/// This bounds a flooding detection, or a correlation against a service with a vast CVE
60/// history. Above the finding count of any real subject.
61pub const MAX_FINDINGS_PER_SUBJECT: usize = 256;
62
63/// How bad a [`Finding`] is if it is true.
64///
65/// Ordered weakest to strongest, so findings rank by ordinary comparison. Independent of
66/// [`Confidence`]: a finding can be [`Critical`](Self::Critical) and only
67/// [`Probable`](Confidence::Probable). [`ALL`](Self::ALL) is the list to iterate.
68#[non_exhaustive]
69#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
70pub enum Severity {
71    /// A fact worth surfacing: an unencrypted service meant to be unencrypted, a
72    /// version banner, a reachable management port.
73    Info,
74    /// A weakness of little consequence on its own: information disclosure a
75    /// determined attacker gains anyway, a hardening step left undone.
76    Low,
77    /// A real weakness with a real precondition, exploitable given a foothold, a
78    /// position, or a second flaw to chain from.
79    Medium,
80    /// Directly exploitable, or a disclosure that hands an attacker materially
81    /// more than they had.
82    High,
83    /// Remote code execution, an authentication bypass, or a compromise that
84    /// needs nothing the internet does not already have.
85    Critical,
86}
87
88impl Severity {
89    /// The human label, capitalised for a report a person reads.
90    ///
91    /// Separate from the wire name in [`record::wire`](crate::record::wire): the label
92    /// may be reworded, the wire name may not.
93    pub const fn label(self) -> &'static str {
94        match self {
95            Self::Info => "Info",
96            Self::Low => "Low",
97            Self::Medium => "Medium",
98            Self::High => "High",
99            Self::Critical => "Critical",
100        }
101    }
102
103    /// Projects onto the `0..=100` scale, mirroring
104    /// [`Confidence::as_score`](crate::model::confidence::Confidence::as_score) so a
105    /// caller can put impact and certainty on one bar. The numbers are tunable;
106    /// the ordering is the invariant.
107    pub const fn as_score(self) -> u8 {
108        match self {
109            Self::Info => 0,
110            Self::Low => 25,
111            Self::Medium => 50,
112            Self::High => 75,
113            Self::Critical => 100,
114        }
115    }
116
117    /// Every severity, weakest first.
118    pub const ALL: &'static [Self] = &[
119        Self::Info,
120        Self::Low,
121        Self::Medium,
122        Self::High,
123        Self::Critical,
124    ];
125}
126
127/// The intrusiveness a detection ran under, recorded on the finding it produced.
128///
129/// How the finding was learned, not part of its claim: a weakness seen passively and
130/// then confirmed by an exploit is one finding. The class a detection declares is
131/// exactly the set of capabilities the operator's envelope serves it, so it is
132/// enforced: [`Passive`](Self::Passive) is given no way to touch the network.
133///
134/// Ordered least to most intrusive, so a policy can compare against a ceiling.
135#[non_exhaustive]
136#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
137pub enum DetectionClass {
138    /// Reads only what the scan already gathered. No new traffic.
139    Passive,
140    /// Exchanges bytes with the scanned socket, within a byte budget. Reads;
141    /// changes nothing.
142    ActiveBenign,
143    /// Causes a state change on the target: a write, a login that is logged, a
144    /// test record left behind.
145    ActiveMutating,
146    /// Attempts to trigger the weakness, not merely to detect it.
147    Exploit,
148    /// May degrade the target's service.
149    Dos,
150}
151
152impl DetectionClass {
153    /// How a class is written for a person to read.
154    ///
155    /// Lowercase except acronyms, by the rule
156    /// [`NetworkRole::label`](crate::model::host::NetworkRole::label) describes: so
157    /// `exploit` and `DoS`. [`Severity::label`] is Title Case, so a report showing both
158    /// axes shows `Critical` and `active-benign`.
159    pub const fn label(self) -> &'static str {
160        match self {
161            Self::Passive => "passive",
162            Self::ActiveBenign => "active-benign",
163            Self::ActiveMutating => "active-mutating",
164            Self::Exploit => "exploit",
165            Self::Dos => "DoS",
166        }
167    }
168
169    /// Every class, least-intrusive-first.
170    pub const ALL: &'static [Self] = &[
171        Self::Passive,
172        Self::ActiveBenign,
173        Self::ActiveMutating,
174        Self::Exploit,
175        Self::Dos,
176    ];
177}
178
179/// A detection's version, ordered so two accounts of one claim can reconcile in a merge
180/// ("the newer detection's verdict wins").
181///
182/// The `major.minor.patch` subset of semver, with no pre-release or build metadata,
183/// since it only has to say which of two is newer. `Ord` compares `major`, then
184/// `minor`, then `patch`.
185#[non_exhaustive]
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
187pub struct Version {
188    /// The leading component.
189    pub major: u16,
190    /// Breaks a tie on `major`.
191    pub minor: u16,
192    /// Breaks a tie on `major` and `minor`.
193    pub patch: u16,
194}
195
196impl Version {
197    /// A version from its three components.
198    pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
199        Self {
200            major,
201            minor,
202            patch,
203        }
204    }
205}
206
207/// Why a string is not a detection version.
208#[non_exhaustive]
209#[derive(Debug, Clone, PartialEq, Eq, Error)]
210#[error("'{input}' is not a version: expected three dot-separated numbers, as in `1.2.3`")]
211pub struct VersionParseError {
212    /// What the caller wrote.
213    pub input: String,
214}
215
216impl FromStr for Version {
217    type Err = VersionParseError;
218
219    /// Reads `"major.minor.patch"`.
220    ///
221    /// Strict: exactly three dot-separated unsigned integers, each in range. A caller
222    /// reading one from a file substitutes the earliest, least-trusted value on
223    /// failure.
224    fn from_str(text: &str) -> Result<Self, Self::Err> {
225        let fail = || VersionParseError {
226            input: text.to_string(),
227        };
228
229        let mut parts = text.split('.');
230        let mut number = || parts.next().ok_or_else(fail)?.parse().map_err(|_| fail());
231
232        let major = number()?;
233        let minor = number()?;
234        let patch = number()?;
235        if parts.next().is_some() {
236            return Err(fail());
237        }
238        Ok(Self::new(major, minor, patch))
239    }
240}
241
242impl fmt::Display for Version {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
245    }
246}
247
248/// An external reference a finding points at.
249///
250/// Typed by kind, which is what a consumer switches on: an NVD entry for a CVE, a MITRE
251/// definition for a CWE, or a bare link. A CVE is an opaque identifier, a CWE is a
252/// number (its MITRE URL is built from it), and a URL is arbitrary and untrusted.
253///
254/// `Ord` because a claim key needs the lowest CVE a finding carries; see
255/// [`Finding::claim_id`].
256#[non_exhaustive]
257#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
258pub enum Reference {
259    /// A CVE identifier, e.g. `CVE-2021-44228`. Validated for shape at
260    /// construction, never parsed into fields.
261    Cve(String),
262    /// A CWE weakness number, e.g. `79` for `CWE-79`.
263    Cwe(u32),
264    /// Any other reference, such as an advisory or a vendor bulletin. Untrusted, and
265    /// exported as inert escaped text, not a live link.
266    Url(String),
267}
268
269impl Reference {
270    /// A CVE reference, if `id` has the shape `CVE-YYYY-N` (a four-digit year and
271    /// at least one digit of sequence). Returns [`None`] otherwise, since a
272    /// malformed identifier is not a reference.
273    pub fn cve(id: impl Into<String>) -> Option<Self> {
274        let id = id.into();
275        is_cve_shaped(&id).then_some(Self::Cve(id))
276    }
277
278    /// A CWE reference from its number.
279    pub const fn cwe(number: u32) -> Self {
280        Self::Cwe(number)
281    }
282
283    /// An arbitrary URL reference.
284    pub fn url(url: impl Into<String>) -> Self {
285        Self::Url(url.into())
286    }
287}
288
289/// Whether `id` reads as `CVE-<4 digits>-<1+ digits>`.
290///
291/// A hand-rolled shape check, so the model needs no regex engine.
292fn is_cve_shaped(id: &str) -> bool {
293    let Some(rest) = id.strip_prefix("CVE-") else {
294        return false;
295    };
296    let Some((year, seq)) = rest.split_once('-') else {
297        return false;
298    };
299    year.len() == 4
300        && year.bytes().all(|b| b.is_ascii_digit())
301        && !seq.is_empty()
302        && seq.bytes().all(|b| b.is_ascii_digit())
303}
304
305/// What a finding is one of, where several detections cover one weakness
306/// between them.
307///
308/// Four detections reading an SSH server's KEXINIT may each flag something different: a
309/// cipher, a host key, a key exchange, a MAC. They stay four findings, each separately
310/// true and separately fixed, but to a reader they are one sentence. A detection may
311/// declare its group and how the group reads as a whole; what a front end does with
312/// that is up to it, and nothing merges.
313///
314/// Both halves are author-chosen and untrusted, like the detection's id and title.
315#[derive(Debug, Clone, PartialEq, Eq, Hash)]
316pub struct FindingGroup {
317    id: String,
318    summary: String,
319}
320
321impl FindingGroup {
322    /// A group from its identity and how it reads, or
323    /// [`FindingError::EmptyGroup`] if either is blank.
324    ///
325    /// The summary is a plural noun phrase a count can lead: `weak SSH algorithms
326    /// offered`, so four read as *4 weak SSH algorithms offered*. This is not checked.
327    pub fn new(id: impl Into<String>, summary: impl Into<String>) -> Result<Self, FindingError> {
328        let id = id.into();
329        let summary = summary.into();
330        if id.trim().is_empty() || summary.trim().is_empty() {
331            return Err(FindingError::EmptyGroup);
332        }
333        Ok(Self { id, summary })
334    }
335
336    /// The author-chosen identity every member shares. Untrusted; escape before
337    /// display.
338    pub fn id(&self) -> &str {
339        &self.id
340    }
341
342    /// How the group reads when its members are spoken of as one. Untrusted;
343    /// escape before display.
344    pub fn summary(&self) -> &str {
345        &self.summary
346    }
347}
348
349/// The bytes that made a detection fire, bounded and safe to carry everywhere.
350///
351/// A newtype, so the [`MAX_EXCERPT_BYTES`] bound is enforced at [`Excerpt::new`] and
352/// cannot be bypassed by a rebuild from a file or a value from a sandboxed module.
353/// Over-length input is truncated, so a real finding is never dropped for long
354/// evidence.
355#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
356pub struct Excerpt(String);
357
358impl Excerpt {
359    /// An excerpt from `text`, truncated to [`MAX_EXCERPT_BYTES`] on a character
360    /// boundary so the result is always valid UTF-8.
361    pub fn new(text: impl Into<String>) -> Self {
362        let mut text = text.into();
363        if text.len() > MAX_EXCERPT_BYTES {
364            let mut end = MAX_EXCERPT_BYTES;
365            while !text.is_char_boundary(end) {
366                end -= 1;
367            }
368            text.truncate(end);
369        }
370        Self(text)
371    }
372
373    /// The excerpt text.
374    pub fn as_str(&self) -> &str {
375        &self.0
376    }
377
378    /// Whether the excerpt carries nothing.
379    pub fn is_empty(&self) -> bool {
380        self.0.is_empty()
381    }
382}
383
384/// Which detection produced a [`Finding`], to which version, from which bytes.
385///
386/// The provenance stamp the report records: an author-chosen `id`, an ordered
387/// [`Version`], and the content hash of the detection body. The hash is an opaque
388/// string computed by the detection subsystem.
389///
390/// The `id` is **untrusted input** that reaches exported reports, so escape it like a
391/// scanned host's banner. The `zond:` prefix is reserved for built-in detections,
392/// enforced where detections are authored: by `build.rs` for those this project ships
393/// and by [`detect::flow::validate`](crate::detect::flow) for an operator's. It is not
394/// enforced here, since the built-in correlator's id lives in that namespace, nor on a
395/// report read back, where everything is the document's own claim.
396#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
397pub struct DetectionId {
398    id: String,
399    version: Version,
400    content_hash: String,
401}
402
403impl DetectionId {
404    /// A detection identity, or [`FindingError::EmptyId`] if `id` is blank.
405    ///
406    /// The content hash is opaque and may be empty (a detection under development need
407    /// not have one); the id may not.
408    pub fn new(
409        id: impl Into<String>,
410        version: Version,
411        content_hash: impl Into<String>,
412    ) -> Result<Self, FindingError> {
413        let id = id.into();
414        if id.trim().is_empty() {
415            return Err(FindingError::EmptyId);
416        }
417        Ok(Self {
418            id,
419            version,
420            content_hash: content_hash.into(),
421        })
422    }
423
424    /// The author-chosen identifier. Untrusted; escape before display.
425    pub fn id(&self) -> &str {
426        &self.id
427    }
428
429    /// The detection's version.
430    pub fn version(&self) -> Version {
431        self.version
432    }
433
434    /// The content hash of the detection body, or an empty string if none was
435    /// recorded.
436    pub fn content_hash(&self) -> &str {
437        &self.content_hash
438    }
439}
440
441/// Which of a finding's vulnerabilities are known to be exploited in the wild,
442/// and whose list says so.
443///
444/// Separate from the verdict: exploitation in the wild says nothing about whether this
445/// host is affected ([`Confidence`]) or how bad it would be ([`Severity`]). It tells a
446/// reader which claims to work through first, so it raises neither axis; a front end
447/// marks and orders by it.
448///
449/// Stamped with the list that said so (CISA's by default), since that is someone
450/// else's data on someone else's schedule.
451#[derive(Debug, Clone, PartialEq, Eq, Hash)]
452pub struct Exploitation {
453    by: DetectionId,
454    cves: Vec<String>,
455}
456
457impl Exploitation {
458    /// The CVE identifiers among `cves` that `by` lists as exploited, in the
459    /// order given and without repeats, or [`FindingError::NoExploitedCve`]
460    /// where none of them is one.
461    ///
462    /// Anything not shaped like a CVE identifier is left out, as with
463    /// [`Reference::cve`].
464    pub fn new(
465        by: DetectionId,
466        cves: impl IntoIterator<Item = impl Into<String>>,
467    ) -> Result<Self, FindingError> {
468        let mut kept: Vec<String> = Vec::new();
469        for cve in cves {
470            let cve = cve.into();
471            if is_cve_shaped(&cve) && !kept.contains(&cve) {
472                kept.push(cve);
473            }
474        }
475        if kept.is_empty() {
476            return Err(FindingError::NoExploitedCve);
477        }
478        Ok(Self { by, cves: kept })
479    }
480
481    /// The list that names them exploited: its identity, version and content
482    /// hash. Untrusted; escape before display.
483    pub fn by(&self) -> &DetectionId {
484        &self.by
485    }
486
487    /// The finding's vulnerabilities the list names, in the order the finding
488    /// cites them. Never empty.
489    pub fn cves(&self) -> impl Iterator<Item = &str> {
490        self.cves.iter().map(String::as_str)
491    }
492}
493
494/// What makes two findings *the same finding*: the detection that asserts it and
495/// the thing it asserts.
496///
497/// Excludes the version, hash, confidence, severity and excerpt (as the host's `OsClaim`
498/// key excludes confidence and evidence): they say how sure, which build and why, not
499/// what is claimed. Otherwise a detection version bump would double every finding in a
500/// merge.
501///
502/// The `subject` distinguishes two claims from the *same* detection: the CVE identifier
503/// for a CVE finding, the title otherwise. The host or port holding the finding is the
504/// other half of its identity.
505#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
506pub struct ClaimId {
507    detection: String,
508    subject: String,
509}
510
511impl ClaimId {
512    /// The producing detection's author-chosen id. Untrusted; escape before
513    /// display.
514    pub fn detection(&self) -> &str {
515        &self.detection
516    }
517
518    /// What the claim is about: the first CVE identifier the finding
519    /// references, or its title where it references none. Untrusted; escape
520    /// before display.
521    pub fn subject(&self) -> &str {
522        &self.subject
523    }
524}
525
526/// One thing wrong with a scanned subject: a typed, provenance-tagged claim.
527///
528/// Every finding names the [`DetectionId`] that produced it, carries two
529/// independent judgements ([`Severity`] and [`Confidence`]), holds a bounded
530/// [`Excerpt`] of the bytes that justify it, and points at zero or more typed
531/// [`Reference`]s. Built through [`Finding::new`] and the `with_*` builders, so every
532/// finding passes the same checks whether scanned, rebuilt from a file, or returned by
533/// a module.
534#[derive(Debug, Clone, PartialEq, Eq)]
535pub struct Finding {
536    detection: DetectionId,
537    title: String,
538    severity: Severity,
539    confidence: Confidence,
540    class: DetectionClass,
541    excerpt: Excerpt,
542    /// In the order the detection added them, deduplicated.
543    ///
544    /// Order carries meaning: a vulnerability correlation cites the worst first, and a
545    /// front end with room for three of forty-four wants those three. Two runs still
546    /// write the same file, since the producer is deterministic.
547    references: Vec<Reference>,
548    remediation: Option<String>,
549    /// The platform identifiers the finding was drawn from, for one a
550    /// vulnerability correlation drew from a service's CPEs, ascending.
551    ///
552    /// A correlation rests on the identification it matched, and [`merge`](crate::merge)
553    /// asks whether a newer scan still backs it before carrying the finding forward.
554    /// The excerpt is for people, and the detection id names a catalogue, so this is
555    /// a field.
556    ///
557    /// A set, because a service may carry two identifiers for one release (an
558    /// imported document's URI form beside its 2.3 form), and the claim is backed
559    /// while any of them is.
560    cpes: BTreeSet<String>,
561    /// What the claim is about, where the detection names it outright. See
562    /// [`claim_id`](Self::claim_id).
563    subject: Option<String>,
564    /// The distribution build a correlation judged, for one drawn from a
565    /// service that carried one.
566    ///
567    /// The claim rests on it, as on [`cpes`](Self::cpes). A distribution ships fixes as
568    /// new package revisions of the same upstream version, so an upgrade moves only
569    /// this, and [`merge`](crate::merge) has to see it move.
570    build: Option<Build>,
571    /// What this finding is one of, where its detection declared a
572    /// [`FindingGroup`]. Most detections declare none.
573    group: Option<FindingGroup>,
574    /// The distributor's advisory data a correlation consulted, where it
575    /// consulted any.
576    ///
577    /// A second stamp beside [`detection`](Self::detection). A verdict on a
578    /// distribution's build uses two datasets: the catalogue says which
579    /// vulnerabilities the upstream release has, and the distributor's data which of
580    /// them its build still carries. This records which snapshot of the second was
581    /// used.
582    advised_by: Option<DetectionId>,
583    /// Which of the vulnerabilities it cites are known to be exploited, where
584    /// the correlation that drew it consulted a list naming any.
585    exploitation: Option<Exploitation>,
586}
587
588impl Finding {
589    /// A finding from its required parts, or [`FindingError::EmptyTitle`] if
590    /// `title` is blank.
591    ///
592    /// The excerpt, references and remediation start empty and are added with the
593    /// builders below.
594    pub fn new(
595        detection: DetectionId,
596        title: impl Into<String>,
597        severity: Severity,
598        confidence: Confidence,
599        class: DetectionClass,
600    ) -> Result<Self, FindingError> {
601        let title = title.into();
602        if title.trim().is_empty() {
603            return Err(FindingError::EmptyTitle);
604        }
605        Ok(Self {
606            detection,
607            title,
608            severity,
609            confidence,
610            class,
611            excerpt: Excerpt::default(),
612            references: Vec::new(),
613            remediation: None,
614            cpes: BTreeSet::new(),
615            subject: None,
616            build: None,
617            advised_by: None,
618            exploitation: None,
619            group: None,
620        })
621    }
622
623    /// Adds a reference, keeping the order they arrive in. A duplicate folds
624    /// away, so two runs that found the same references write the same file.
625    #[must_use]
626    pub fn with_reference(mut self, reference: Reference) -> Self {
627        if !self.references.contains(&reference) {
628            self.references.push(reference);
629        }
630        self
631    }
632
633    /// Sets the justifying excerpt. Already bounded by [`Excerpt::new`].
634    #[must_use]
635    pub fn with_excerpt(mut self, excerpt: Excerpt) -> Self {
636        self.excerpt = excerpt;
637        self
638    }
639
640    /// Sets the remediation advice.
641    #[must_use]
642    pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
643        self.remediation = Some(remediation.into());
644        self
645    }
646
647    /// Adds a platform identifier the finding was drawn from.
648    ///
649    /// For a correlation, which draws a finding from a CPE a service carries. Adding
650    /// one already named changes nothing.
651    #[must_use]
652    pub fn with_cpe(mut self, cpe: impl Into<String>) -> Self {
653        self.cpes.insert(cpe.into());
654        self
655    }
656
657    /// Names what the claim is about, which [`claim_id`](Self::claim_id)
658    /// then keys on in place of the references.
659    ///
660    /// For a detection whose findings summarise a changing set of references, as a
661    /// correlation's do, so the claim does not rename itself when the data changes.
662    #[must_use]
663    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
664        self.subject = Some(subject.into());
665        self
666    }
667
668    /// Records the distribution build a correlation judged.
669    #[must_use]
670    pub fn with_build(mut self, build: Build) -> Self {
671        self.build = Some(build);
672        self
673    }
674
675    /// Records the distributor's advisory data a correlation consulted.
676    #[must_use]
677    pub fn with_advised_by(mut self, advised_by: DetectionId) -> Self {
678        self.advised_by = Some(advised_by);
679        self
680    }
681
682    /// Records which of the vulnerabilities it cites are known to be
683    /// exploited.
684    #[must_use]
685    pub fn with_exploitation(mut self, exploitation: Exploitation) -> Self {
686        self.exploitation = Some(exploitation);
687        self
688    }
689
690    /// Records which group of findings this one belongs to.
691    #[must_use]
692    pub fn with_group(mut self, group: FindingGroup) -> Self {
693        self.group = Some(group);
694        self
695    }
696
697    /// What this finding is one of, where its detection declared a group.
698    pub fn group(&self) -> Option<&FindingGroup> {
699        self.group.as_ref()
700    }
701
702    /// What the claim is about, where the detection named it. Untrusted.
703    pub fn subject(&self) -> Option<&str> {
704        self.subject.as_deref()
705    }
706
707    /// The distribution build a correlation judged, if it judged one.
708    pub fn build(&self) -> Option<&Build> {
709        self.build.as_ref()
710    }
711
712    /// The distributor's advisory data a correlation consulted, if any.
713    pub fn advised_by(&self) -> Option<&DetectionId> {
714        self.advised_by.as_ref()
715    }
716
717    /// Which of the vulnerabilities it cites are known to be exploited, if a
718    /// list consulted names any.
719    pub fn exploitation(&self) -> Option<&Exploitation> {
720        self.exploitation.as_ref()
721    }
722
723    /// The detection that produced this finding.
724    pub fn detection(&self) -> &DetectionId {
725        &self.detection
726    }
727
728    /// The one-line title. Untrusted; escape before display.
729    pub fn title(&self) -> &str {
730        &self.title
731    }
732
733    /// How bad this finding is if true.
734    pub fn severity(&self) -> Severity {
735        self.severity
736    }
737
738    /// How sure this finding is true.
739    pub fn confidence(&self) -> Confidence {
740        self.confidence
741    }
742
743    /// The intrusiveness the producing detection ran under.
744    pub fn class(&self) -> DetectionClass {
745        self.class
746    }
747
748    /// The bytes that justify this finding.
749    pub fn excerpt(&self) -> &Excerpt {
750        &self.excerpt
751    }
752
753    /// The external references, in the order the detection stated them, which is
754    /// most-relevant-first where it had an order to state.
755    pub fn references(&self) -> impl Iterator<Item = &Reference> {
756        self.references.iter()
757    }
758
759    /// The remediation advice, if any. Untrusted; escape before display.
760    pub fn remediation(&self) -> Option<&str> {
761        self.remediation.as_deref()
762    }
763
764    /// The platform identifiers a correlation drew this finding from,
765    /// ascending, and none for a finding drawn from anything else. Untrusted: a
766    /// scanned host's banner chose them, so escape before display.
767    ///
768    /// Each draws the same claim, so it stands while any of them still identifies the
769    /// endpoint.
770    pub fn cpes(&self) -> impl Iterator<Item = &str> {
771        self.cpes.iter().map(String::as_str)
772    }
773
774    /// Whether a correlation drew this finding, which is whether it names a
775    /// platform identifier it rests on.
776    pub(crate) fn is_correlation(&self) -> bool {
777        !self.cpes.is_empty()
778    }
779
780    /// The key that decides whether this finding and another are the same claim.
781    ///
782    /// The producing detection's id, paired with the subject it discriminates on:
783    /// the [`subject`](Self::subject) the detection named where it named one,
784    /// otherwise the lowest CVE identifier this finding references, or its
785    /// title where it references none.
786    ///
787    /// The lowest, not the first: a correlation states its worst first, which changes
788    /// when the catalogue does, so keying on the first would rename the claim after a
789    /// data refresh and a diff of an unchanged host would show one finding gone and
790    /// another arrived.
791    pub fn claim_id(&self) -> ClaimId {
792        let subject = self.subject.clone().unwrap_or_else(|| {
793            self.references
794                .iter()
795                .filter_map(|r| match r {
796                    Reference::Cve(id) => Some(id.clone()),
797                    _ => None,
798                })
799                .min()
800                .unwrap_or_else(|| self.title.clone())
801        });
802        ClaimId {
803            detection: self.detection.id.clone(),
804            subject,
805        }
806    }
807
808    /// Folds another account of the same claim into this one, keeping the
809    /// stronger reading, and reports whether anything changed.
810    ///
811    /// Called when a detection asserts a claim a subject already carries: the same
812    /// producer and [`claim_id`](Self::claim_id). The caller must have matched the
813    /// claims.
814    ///
815    /// The verdict (severity, title, class) follows the version, so it stays in step
816    /// with the [`DetectionId`] that records who concluded it:
817    ///
818    /// - An account at a **lower** version supplies only what is missing. Otherwise
819    ///   folding a `1.0.0` reading into a `2.0.0` one would leave `2.0.0` stamped on
820    ///   `1.0.0`'s `Low`. This is the common direction, since the record folded in is
821    ///   usually the older.
822    /// - An account at the **same** version supplies the verdict: one detection
823    ///   grading a claim differently twice has read different evidence, and the later
824    ///   reading wins. [`merge`](crate::merge) folds documents in the order their own
825    ///   clocks give, so a cipher `Low` in January and `Critical` in June is `Critical`.
826    /// - A **newer** version supplies the verdict and its own stamp.
827    ///
828    /// Regardless of version, **certainty only rises**, since a second agreeing account
829    /// is worth something whichever build produced it, and **references and platform
830    /// identifiers union**, as [`Service::merge`](crate::model::port::Service::merge)
831    /// unions CPEs. Keeping one identifier would have a merge drop the claim once a
832    /// newer scan backed only the other.
833    ///
834    /// **Except for correlations**, whose certainty and references are part of the
835    /// verdict. A correlation is a computation over a service identification and the
836    /// datasets behind it, and a later one that cites fewer vulnerabilities, or holds
837    /// them less surely, has usually learned some do not apply to this build. Unioning
838    /// would carry every vulnerability ever cited into every later report at the surest
839    /// grade ever given. So an account of a correlation at the same version or newer
840    /// replaces the certainty, references, build, advisory stamp and exploitation
841    /// outright, and an older one supplies none of them.
842    ///
843    /// The excerpt and remediation travel with the verdict where one is taken, and
844    /// otherwise fill a gap.
845    pub fn corroborate(&mut self, other: Finding) -> bool {
846        // Both must be correlations: a finding rebuilt from a file that lost its
847        // identifiers is treated as the observation it looks like.
848        let correlation = self.is_correlation() && other.is_correlation();
849
850        // Destructured, so a new field fails to compile until it is folded.
851        let Finding {
852            detection,
853            title,
854            severity,
855            confidence,
856            class,
857            excerpt,
858            references,
859            remediation,
860            cpes,
861            subject,
862            build,
863            advised_by,
864            exploitation,
865            group,
866        } = other;
867
868        let mut changed = false;
869        let at_least_as_new = detection.version >= self.detection.version;
870
871        if correlation {
872            // A correlation's verdict comes whole from an account at least as new.
873            if at_least_as_new {
874                if confidence != self.confidence {
875                    self.confidence = confidence;
876                    changed = true;
877                }
878                if references != self.references {
879                    self.references = references;
880                    changed = true;
881                }
882                if build != self.build {
883                    self.build = build;
884                    changed = true;
885                }
886                if advised_by != self.advised_by {
887                    self.advised_by = advised_by;
888                    changed = true;
889                }
890                if exploitation != self.exploitation {
891                    self.exploitation = exploitation;
892                    changed = true;
893                }
894            }
895        } else {
896            let stronger = self.confidence.max(confidence);
897            if stronger != self.confidence {
898                self.confidence = stronger;
899                changed = true;
900            }
901            for reference in references {
902                if !self.references.contains(&reference) {
903                    self.references.push(reference);
904                    changed = true;
905                }
906            }
907            if self.build.is_none() && build.is_some() {
908                self.build = build;
909                changed = true;
910            }
911            if self.advised_by.is_none() && advised_by.is_some() {
912                self.advised_by = advised_by;
913                changed = true;
914            }
915            if self.exploitation.is_none() && exploitation.is_some() {
916                self.exploitation = exploitation;
917                changed = true;
918            }
919        }
920
921        // Both accounts share the subject; one that named it fills one that did not.
922        if self.subject.is_none() && subject.is_some() {
923            self.subject = subject;
924            changed = true;
925        }
926
927        // The group belongs to the detection. A newer account carrying it moves a
928        // finding recorded before the detection joined the group onto it.
929        if at_least_as_new && group.is_some() && group != self.group {
930            self.group = group;
931            changed = true;
932        }
933
934        // Same claim means the same detection id, so the version orders them.
935        if at_least_as_new {
936            // Only a strictly newer detection replaces the stamp and content hash.
937            if detection.version > self.detection.version {
938                self.detection = detection;
939                changed = true;
940            }
941
942            if severity != self.severity {
943                self.severity = severity;
944                changed = true;
945            }
946            if title != self.title {
947                self.title = title;
948                changed = true;
949            }
950            if class != self.class {
951                self.class = class;
952                changed = true;
953            }
954            if !excerpt.is_empty() && excerpt != self.excerpt {
955                self.excerpt = excerpt;
956                changed = true;
957            }
958            if remediation.is_some() && remediation != self.remediation {
959                self.remediation = remediation;
960                changed = true;
961            }
962        } else {
963            // Superseded: its justification only fills a gap.
964            if self.excerpt.is_empty() && !excerpt.is_empty() {
965                self.excerpt = excerpt;
966                changed = true;
967            }
968            if self.remediation.is_none() && remediation.is_some() {
969                self.remediation = remediation;
970                changed = true;
971            }
972        }
973
974        for cpe in cpes {
975            changed |= self.cpes.insert(cpe);
976        }
977
978        changed
979    }
980}
981
982/// Where one account of a subject leaves a claim drawn from another account's
983/// evidence.
984///
985/// Asked only of a finding a built-in derivation draws from evidence the report records
986/// beside it, such as what a TLS endpoint accepts. For other findings, absence from a
987/// later scan only means the detection did not fire.
988#[derive(Debug, Clone, Copy, PartialEq, Eq)]
989pub(crate) enum Standing {
990    /// The account draws the same claim from its own evidence.
991    Upheld,
992    /// The account settled everything the claim rests on and does not draw it.
993    Overturned,
994    /// The account left part of what the claim rests on unsettled, so it
995    /// neither draws the claim nor refutes it.
996    Unsettled,
997}
998
999/// Why a [`Finding`] or a [`DetectionId`] could not be constructed.
1000///
1001/// Every case is an empty identifier, title, phrase or list.
1002#[non_exhaustive]
1003#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
1004pub enum FindingError {
1005    /// A [`DetectionId`] was given a blank `id`.
1006    #[error("a detection id cannot be empty")]
1007    EmptyId,
1008    /// A [`Finding`] was given a blank title.
1009    #[error("a finding title cannot be empty")]
1010    EmptyTitle,
1011    /// A [`FindingGroup`] was given a blank id or a blank summary.
1012    #[error("a finding group needs both an id and a summary")]
1013    EmptyGroup,
1014    /// An [`Exploitation`] was given no CVE identifier.
1015    #[error("an exploitation needs at least one CVE identifier")]
1016    NoExploitedCve,
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use super::*;
1022
1023    fn detection() -> DetectionId {
1024        DetectionId::new("redis-unauth-access", Version::new(1, 0, 0), "abc123").unwrap()
1025    }
1026
1027    fn finding() -> Finding {
1028        Finding::new(
1029            detection(),
1030            "Unauthenticated Redis access",
1031            Severity::High,
1032            Confidence::Certain,
1033            DetectionClass::ActiveBenign,
1034        )
1035        .unwrap()
1036    }
1037
1038    /// A correlation at the same version or newer replaces the earlier one's verdict,
1039    /// certainty and citations included.
1040    #[test]
1041    fn a_correlations_later_account_replaces_its_certainty_and_citations() {
1042        let correlation = |version: u16, confidence: Confidence, cves: &[&str]| {
1043            let mut finding = Finding::new(
1044                DetectionId::new("zond:cve-kev", Version::new(0, version, 0), "h").unwrap(),
1045                "OpenSSH 6.6.1p1",
1046                Severity::Critical,
1047                confidence,
1048                DetectionClass::Passive,
1049            )
1050            .unwrap()
1051            .with_cpe("cpe:/a:openbsd:openssh:6.6.1p1")
1052            .with_subject("openbsd:openssh:6.6.1p1@ubuntu-14.04/build-unchecked");
1053            for cve in cves {
1054                finding = finding.with_reference(Reference::cve(*cve).unwrap());
1055            }
1056            finding
1057        };
1058
1059        let mut held = correlation(
1060            3,
1061            Confidence::Probable,
1062            &["CVE-2016-1908", "CVE-2023-38408"],
1063        );
1064        assert!(held.corroborate(correlation(3, Confidence::Weak, &["CVE-2023-38408"])));
1065        assert_eq!(held.confidence(), Confidence::Weak);
1066        assert_eq!(held.references().count(), 1);
1067
1068        // An older correlator's account gives nothing.
1069        held.corroborate(correlation(2, Confidence::Certain, &["CVE-2016-1908"]));
1070        assert_eq!(held.confidence(), Confidence::Weak);
1071        assert_eq!(held.references().count(), 1);
1072
1073        // An observation still ratchets.
1074        let mut observed = finding();
1075        let mut weaker = finding();
1076        weaker.confidence = Confidence::Weak;
1077        observed.corroborate(weaker);
1078        assert_eq!(observed.confidence(), Confidence::Certain);
1079    }
1080
1081    #[test]
1082    fn severity_orders_weakest_to_strongest() {
1083        // A report ranks by this order.
1084        assert!(Severity::Info < Severity::Low);
1085        assert!(Severity::Low < Severity::Medium);
1086        assert!(Severity::Medium < Severity::High);
1087        assert!(Severity::High < Severity::Critical);
1088        assert_eq!(Severity::ALL.iter().max(), Some(&Severity::Critical));
1089        assert_eq!(Severity::Critical.as_score(), 100);
1090        assert_eq!(Severity::Info.as_score(), 0);
1091    }
1092
1093    #[test]
1094    fn an_empty_title_is_refused() {
1095        // A finding must say what it claims.
1096        let err = Finding::new(
1097            detection(),
1098            "   ",
1099            Severity::High,
1100            Confidence::Certain,
1101            DetectionClass::ActiveBenign,
1102        );
1103        assert_eq!(err, Err(FindingError::EmptyTitle));
1104    }
1105
1106    #[test]
1107    fn an_empty_detection_id_is_refused() {
1108        let err = DetectionId::new("", Version::new(1, 0, 0), "hash");
1109        assert_eq!(err, Err(FindingError::EmptyId));
1110    }
1111
1112    #[test]
1113    fn an_over_length_excerpt_is_truncated_on_a_char_boundary() {
1114        // A multi-byte char straddling the cap must not be split into invalid UTF-8,
1115        // and the result must be within the bound.
1116        let big = "é".repeat(MAX_EXCERPT_BYTES); // two bytes each, so twice the cap
1117        let excerpt = Excerpt::new(big);
1118        assert!(excerpt.as_str().len() <= MAX_EXCERPT_BYTES);
1119        // The last char is whole.
1120        assert!(excerpt.as_str().chars().all(|c| c == 'é'));
1121    }
1122
1123    #[test]
1124    fn a_short_excerpt_is_kept_verbatim() {
1125        let excerpt = Excerpt::new("redis_version:7.2.4");
1126        assert_eq!(excerpt.as_str(), "redis_version:7.2.4");
1127    }
1128
1129    /// A duplicate folds away and the rest keep the order they arrived in.
1130    ///
1131    /// A correlation cites its worst first, and that order is kept.
1132    #[test]
1133    fn references_dedup_and_keep_the_order_they_were_added_in() {
1134        let worst = Reference::cve("CVE-2024-6387").expect("a CVE");
1135        let older = Reference::cve("CVE-2015-5600").expect("a CVE");
1136
1137        let f = finding()
1138            .with_reference(Reference::cwe(306))
1139            .with_reference(Reference::cwe(306))
1140            .with_reference(worst.clone())
1141            .with_reference(older.clone());
1142
1143        let refs: Vec<_> = f.references().cloned().collect();
1144        assert_eq!(refs.len(), 3, "the duplicate CWE must fold away");
1145        assert_eq!(refs, vec![Reference::cwe(306), worst, older]);
1146    }
1147
1148    /// The claim key takes the lowest CVE, not the first.
1149    ///
1150    /// The first reference changes when the dataset does; keying on it would rename
1151    /// the claim after a catalogue refresh.
1152    #[test]
1153    fn a_claim_is_keyed_on_the_lowest_cve_however_they_were_ordered() {
1154        let ranked = finding()
1155            .with_reference(Reference::cve("CVE-2024-6387").expect("a CVE"))
1156            .with_reference(Reference::cve("CVE-2015-5600").expect("a CVE"));
1157        let reordered = finding()
1158            .with_reference(Reference::cve("CVE-2015-5600").expect("a CVE"))
1159            .with_reference(Reference::cve("CVE-2024-6387").expect("a CVE"));
1160
1161        assert_eq!(ranked.claim_id(), reordered.claim_id());
1162        assert_eq!(ranked.claim_id().subject(), "CVE-2015-5600");
1163    }
1164
1165    #[test]
1166    fn a_malformed_cve_is_not_a_reference() {
1167        assert!(Reference::cve("CVE-2021-44228").is_some());
1168        assert!(Reference::cve("not-a-cve").is_none());
1169        assert!(Reference::cve("CVE-21-44228").is_none()); // year not four digits
1170        assert!(Reference::cve("CVE-2021-").is_none()); // no sequence
1171    }
1172
1173    #[test]
1174    fn version_parses_and_orders_numerically() {
1175        assert_eq!("8.3.1".parse(), Ok(Version::new(8, 3, 1)));
1176        assert!("8.3".parse::<Version>().is_err());
1177        assert!("8.3.1.0".parse::<Version>().is_err());
1178        assert!("8.x.1".parse::<Version>().is_err());
1179        // The order is component-wise numeric, not lexicographic: 8.10 > 8.3.
1180        assert!(Version::new(8, 10, 0) > Version::new(8, 3, 1));
1181    }
1182
1183    #[test]
1184    fn claim_id_keys_on_cve_when_present_else_title() {
1185        // Two versions of the same CVE detection are the same claim; the version is
1186        // not in the key.
1187        let v1 = finding().with_reference(Reference::cve("CVE-2021-44228").unwrap());
1188        let newer = Finding::new(
1189            DetectionId::new("redis-unauth-access", Version::new(2, 0, 0), "def456").unwrap(),
1190            "A reworded title",
1191            Severity::Critical,
1192            Confidence::Strong,
1193            DetectionClass::ActiveBenign,
1194        )
1195        .unwrap()
1196        .with_reference(Reference::cve("CVE-2021-44228").unwrap());
1197        assert_eq!(v1.claim_id(), newer.claim_id());
1198
1199        // With no CVE, the title is the discriminator instead.
1200        let by_title = finding();
1201        assert_eq!(
1202            by_title.claim_id(),
1203            ClaimId {
1204                detection: "redis-unauth-access".to_string(),
1205                subject: "Unauthenticated Redis access".to_string(),
1206            }
1207        );
1208    }
1209
1210    #[test]
1211    fn corroborate_takes_the_stronger_and_newer_reading() {
1212        // The same claim, reached again by a newer version that re-scored the
1213        // severity up and carries a second reference. Certainty must only rise;
1214        // the newer verdict must win; the references must union.
1215        let mut base = finding() // High / Certain, v1.0.0
1216            .with_reference(Reference::cve("CVE-2022-0543").unwrap());
1217        let newer = Finding::new(
1218            DetectionId::new("redis-unauth-access", Version::new(1, 1, 0), "newhash").unwrap(),
1219            "Unauthenticated Redis access",
1220            Severity::Critical, // re-scored up
1221            Confidence::Strong, // weaker than Certain, and must not lower it
1222            DetectionClass::ActiveBenign,
1223        )
1224        .unwrap()
1225        .with_reference(Reference::cve("CVE-2022-0543").unwrap()) // same claim
1226        .with_reference(Reference::cwe(306))
1227        .with_remediation("Require a password.");
1228        assert_eq!(base.claim_id(), newer.claim_id());
1229
1230        assert!(base.corroborate(newer));
1231        assert_eq!(base.severity(), Severity::Critical, "newer severity wins");
1232        assert_eq!(
1233            base.confidence(),
1234            Confidence::Certain,
1235            "confidence only rises"
1236        );
1237        assert_eq!(base.detection().version(), Version::new(1, 1, 0));
1238        assert_eq!(base.remediation(), Some("Require a password."));
1239        let refs: Vec<_> = base.references().cloned().collect();
1240        assert_eq!(refs.len(), 2, "references union, not replace");
1241        assert!(refs.contains(&Reference::Cwe(306)));
1242    }
1243
1244    /// The usual direction: folding an older record (a journal read back into a newer
1245    /// run, a report from an earlier build) into a newer one keeps the newer verdict
1246    /// under the newer stamp.
1247    #[test]
1248    fn an_older_account_does_not_supply_a_newer_versions_verdict() {
1249        let account = |version: Version, severity: Severity, title: &str| {
1250            Finding::new(
1251                DetectionId::new("redis-unauth-access", version, "hash").unwrap(),
1252                title,
1253                severity,
1254                Confidence::Probable,
1255                DetectionClass::ActiveBenign,
1256            )
1257            .unwrap()
1258        };
1259
1260        let mut current = account(
1261            Version::new(2, 0, 0),
1262            Severity::Critical,
1263            "Redis, wide open",
1264        );
1265        let superseded = account(Version::new(1, 0, 0), Severity::Low, "Redis reachable");
1266
1267        current.corroborate(superseded);
1268
1269        assert_eq!(current.detection().version(), Version::new(2, 0, 0));
1270        assert_eq!(
1271            current.severity(),
1272            Severity::Critical,
1273            "the stamp and the verdict have to name one version"
1274        );
1275        assert_eq!(current.title(), "Redis, wide open");
1276    }
1277
1278    /// One detection at one version grading a claim two ways has read two lots of
1279    /// evidence, so the account arriving second stands. [`merge`](crate::merge) folds
1280    /// in clock order; see its
1281    /// `two_accounts_of_one_host_keep_every_claim_and_grade_it_as_the_newer_did`.
1282    #[test]
1283    fn an_account_at_the_same_version_supplies_the_current_reading() {
1284        let account = |severity: Severity| {
1285            Finding::new(
1286                DetectionId::new("tls-weak-cipher", Version::new(1, 0, 0), "hash").unwrap(),
1287                "a weak cipher is offered",
1288                severity,
1289                Confidence::Probable,
1290                DetectionClass::Passive,
1291            )
1292            .unwrap()
1293        };
1294
1295        let mut january = account(Severity::Low);
1296        assert!(january.corroborate(account(Severity::Critical)));
1297        assert_eq!(january.severity(), Severity::Critical);
1298
1299        // A downgrade is kept too: the later reading wins either way.
1300        let mut worse_before = account(Severity::Critical);
1301        assert!(worse_before.corroborate(account(Severity::Low)));
1302        assert_eq!(worse_before.severity(), Severity::Low);
1303
1304        // The stamp does not move.
1305        assert_eq!(january.detection().version(), Version::new(1, 0, 0));
1306    }
1307
1308    /// A superseded account's excerpt fills a gap.
1309    #[test]
1310    fn an_older_account_fills_a_gap_it_cannot_overwrite() {
1311        let account = |version: Version| {
1312            Finding::new(
1313                DetectionId::new("redis-unauth-access", version, "hash").unwrap(),
1314                "Unauthenticated Redis access",
1315                Severity::High,
1316                Confidence::Probable,
1317                DetectionClass::ActiveBenign,
1318            )
1319            .unwrap()
1320        };
1321
1322        let mut current = account(Version::new(2, 0, 0));
1323        let older = account(Version::new(1, 0, 0))
1324            .with_excerpt(Excerpt::new("-ERR unknown command"))
1325            .with_remediation("Require a password.");
1326
1327        assert!(current.corroborate(older), "a gap was filled");
1328        assert_eq!(current.excerpt().as_str(), "-ERR unknown command");
1329        assert_eq!(current.remediation(), Some("Require a password."));
1330
1331        // It does not displace an excerpt the newer account already carried.
1332        let mut carrying = account(Version::new(2, 0, 0)).with_excerpt(Excerpt::new("READONLY"));
1333        carrying.corroborate(account(Version::new(1, 0, 0)).with_excerpt(Excerpt::new("older")));
1334        assert_eq!(carrying.excerpt().as_str(), "READONLY");
1335    }
1336
1337    /// **A claim drawn from two identifiers names both**, whichever account is current
1338    /// and whichever catalogue version drew it.
1339    #[test]
1340    fn a_claim_drawn_from_two_identifiers_names_both() {
1341        let drawn = |version: Version, cpe: &str| {
1342            Finding::new(
1343                DetectionId::new("zond:cve-kev", version, "hash").unwrap(),
1344                "http_server 2.4.49 has 1 known vulnerability",
1345                Severity::Critical,
1346                Confidence::Probable,
1347                DetectionClass::Passive,
1348            )
1349            .unwrap()
1350            .with_reference(Reference::cve("CVE-2021-41773").unwrap())
1351            .with_cpe(cpe)
1352        };
1353        let uri = "cpe:/a:apache:http_server:2.4.49";
1354        let formatted = "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*";
1355
1356        for (current, other) in [
1357            (Version::new(1, 0, 0), Version::new(1, 0, 0)),
1358            (Version::new(2, 0, 0), Version::new(1, 0, 0)),
1359            (Version::new(1, 0, 0), Version::new(2, 0, 0)),
1360        ] {
1361            let mut claim = drawn(current, uri);
1362            assert!(claim.corroborate(drawn(other, formatted)));
1363            assert_eq!(
1364                claim.cpes().collect::<Vec<_>>(),
1365                [uri, formatted],
1366                "{current} corroborated by {other}"
1367            );
1368            assert!(
1369                !claim.corroborate(drawn(other, uri)),
1370                "an identifier already named is no news"
1371            );
1372        }
1373    }
1374
1375    #[test]
1376    fn corroborate_reports_no_change_for_an_identical_refiring() {
1377        // The same claim twice is not new information.
1378        let mut base = finding();
1379        assert!(!base.corroborate(finding()));
1380    }
1381}