use std::collections::BTreeMap;
use super::verdict::{MIN_REPORTABLE_ACCURACY, OsSource, OsVerdict};
pub const MAX_FUSED_ACCURACY: u8 = 95;
#[derive(Debug, Clone, PartialEq)]
pub struct OsEvidence {
pub source: OsSource,
pub family: String,
pub vendor: Option<String>,
pub product: Option<String>,
pub version: Option<String>,
pub cpe: Option<String>,
pub confidence: f32,
pub evidence: String,
}
pub fn resolve(evidence: Vec<OsEvidence>) -> Option<OsVerdict> {
if evidence.is_empty() {
return None;
}
let mut by_family: BTreeMap<&str, Vec<&OsEvidence>> = BTreeMap::new();
for item in &evidence {
by_family
.entry(item.family.as_str())
.or_default()
.push(item);
}
let mut scored: Vec<(&str, f32, Vec<&OsEvidence>)> = by_family
.into_iter()
.map(|(family, items)| {
let score = combine(items.iter().map(|item| item.confidence));
(family, score, items)
})
.collect();
scored.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(b.0))
});
let (family, score, items) = scored.first()?;
let against = combine(scored.iter().skip(1).map(|(_, score, _)| *score));
let survived = score * (1.0 - against);
let accuracy = (survived * 100.0)
.round()
.clamp(0.0, f32::from(MAX_FUSED_ACCURACY)) as u8;
if accuracy < MIN_REPORTABLE_ACCURACY {
return None;
}
let agreed = |part: fn(&OsEvidence) -> &Option<String>| -> Option<String> {
let first = part(items.first()?).as_ref()?;
items
.iter()
.all(|item| part(item).as_deref() == Some(first.as_str()))
.then(|| first.clone())
};
let strongest = items
.iter()
.max_by(|a, b| {
a.confidence
.partial_cmp(&b.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
})
.copied()?;
let mut lines: Vec<&str> = items.iter().map(|item| item.evidence.as_str()).collect();
lines.sort_unstable();
lines.dedup();
Some(OsVerdict {
family: (*family).to_string(),
vendor: agreed(|item| &item.vendor),
product: agreed(|item| &item.product),
version: agreed(|item| &item.version),
cpe: agreed(|item| &item.cpe),
accuracy,
source: strongest.source,
evidence: lines.join(" | "),
})
}
fn combine(confidences: impl Iterator<Item = f32>) -> f32 {
let doubt = confidences
.map(|confidence| 1.0 - confidence.clamp(0.0, 1.0))
.product::<f32>();
1.0 - doubt
}
#[cfg(test)]
mod tests {
use super::*;
fn evidence(family: &str, confidence: f32, source: OsSource) -> OsEvidence {
OsEvidence {
source,
family: family.to_string(),
vendor: None,
product: None,
version: None,
cpe: None,
confidence,
evidence: format!("{source:?} says {family}"),
}
}
#[test]
fn two_agreeing_sources_are_worth_more_than_either() {
let stack = evidence("Linux", 0.65, OsSource::TcpStack);
let hardware = evidence("Linux", 0.30, OsSource::HardwareVendor);
let alone = resolve(vec![stack.clone()]).expect("one source names it");
let together = resolve(vec![stack, hardware]).expect("two sources name it");
assert!(together.accuracy > alone.accuracy);
assert_eq!(together.accuracy, 76, "1 - (0.35 x 0.70)");
}
#[test]
fn no_amount_of_agreement_reaches_certainty() {
let many: Vec<OsEvidence> = (0..20)
.map(|_| evidence("Linux", 0.6, OsSource::TcpStack))
.collect();
let resolved = resolve(many).expect("named");
assert_eq!(
resolved.accuracy, MAX_FUSED_ACCURACY,
"twenty agreeing sources may be highly confident and must not be certain"
);
assert!(
resolved.accuracy < 100,
"certainty is reserved for a host that identified itself"
);
}
#[test]
fn disagreement_lowers_the_answer_rather_than_picking_a_winner() {
let uncontested = resolve(vec![evidence("Linux", 0.65, OsSource::TcpStack)])
.expect("one source names it")
.accuracy;
let contested = resolve(vec![
evidence("Linux", 0.65, OsSource::TcpStack),
evidence("Windows", 0.30, OsSource::HardwareVendor),
])
.expect("the leader survives one dissenter");
assert_eq!(contested.family, "Linux");
assert!(
contested.accuracy < uncontested,
"a contested verdict must not score what an uncontested one does"
);
}
#[test]
fn an_even_conflict_names_nothing() {
assert!(
resolve(vec![
evidence("Linux", 0.65, OsSource::TcpStack),
evidence("Windows", 0.65, OsSource::HardwareVendor),
])
.is_none()
);
}
#[test]
fn a_finer_detail_survives_only_where_every_source_agrees() {
let mut precise = evidence("Linux", 0.65, OsSource::TcpStack);
precise.product = Some("Ubuntu".to_string());
let vague = evidence("Linux", 0.30, OsSource::HardwareVendor);
let resolved = resolve(vec![precise, vague]).expect("named");
assert_eq!(resolved.family, "Linux");
assert_eq!(
resolved.product, None,
"one source naming a product is not agreement about it"
);
}
#[test]
fn the_answer_does_not_depend_on_the_order_evidence_arrived_in() {
let a = evidence("Linux", 0.5, OsSource::TcpStack);
let b = evidence("macOS", 0.5, OsSource::HardwareVendor);
assert_eq!(
resolve(vec![a.clone(), b.clone()]),
resolve(vec![b, a]),
"the same evidence in the other order is the same evidence"
);
}
#[test]
fn nothing_in_names_nothing_out() {
assert!(resolve(Vec::new()).is_none());
}
}