use std::fmt;
use std::str::FromStr;
use crate::model::finding::DetectionClass;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DetectionEnvelope {
ceiling: Option<DetectionClass>,
}
impl DetectionEnvelope {
pub const fn up_to(ceiling: DetectionClass) -> Self {
Self {
ceiling: Some(ceiling),
}
}
pub const fn none() -> Self {
Self { ceiling: None }
}
pub fn permits(self, class: DetectionClass) -> bool {
matches!(self.ceiling, Some(ceiling) if class <= ceiling)
}
pub const fn ceiling(self) -> Option<DetectionClass> {
self.ceiling
}
}
impl fmt::Display for DetectionEnvelope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.ceiling {
Some(ceiling) => f.write_str(ceiling.label()),
None => f.write_str("off"),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownDetectionEnvelope {
pub input: String,
}
impl fmt::Display for UnknownDetectionEnvelope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut names = vec!["off"];
names.extend(DetectionClass::ALL.iter().map(|class| class.label()));
write!(
f,
"unknown detection envelope '{}', expected one of: {} (or 0 to {})",
self.input,
names.join(", "),
DetectionClass::ALL.len()
)
}
}
impl std::error::Error for UnknownDetectionEnvelope {}
impl FromStr for DetectionEnvelope {
type Err = UnknownDetectionEnvelope;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let written = input.trim();
let refused = || UnknownDetectionEnvelope {
input: input.to_string(),
};
if let Ok(level) = written.parse::<usize>() {
let Some(step) = level.checked_sub(1) else {
return Ok(Self::none());
};
return DetectionClass::ALL
.get(step)
.copied()
.map(Self::up_to)
.ok_or_else(refused);
}
let wanted = written.replace('_', "-");
if wanted.eq_ignore_ascii_case("off") {
return Ok(Self::none());
}
DetectionClass::ALL
.iter()
.copied()
.find(|class| {
class
.label()
.replace('_', "-")
.eq_ignore_ascii_case(&wanted)
})
.map(Self::up_to)
.ok_or_else(refused)
}
}
impl Default for DetectionEnvelope {
fn default() -> Self {
Self {
ceiling: Some(DetectionClass::Passive),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_scale_runs_from_off_through_the_classes() {
assert_eq!("off".parse(), Ok(DetectionEnvelope::none()));
assert_eq!("OFF".parse(), Ok(DetectionEnvelope::none()));
assert_eq!("0".parse(), Ok(DetectionEnvelope::none()));
for (level, class) in DetectionClass::ALL.iter().copied().enumerate() {
let asked = (level + 1).to_string();
assert_eq!(
asked.parse(),
Ok(DetectionEnvelope::up_to(class)),
"{asked} is not {}",
class.label()
);
}
assert!(
(DetectionClass::ALL.len() + 1)
.to_string()
.parse::<DetectionEnvelope>()
.is_err(),
"a step past the top of the scale was accepted"
);
}
#[test]
fn off_permits_nothing_and_is_the_bottom_of_the_scale() {
let off = DetectionEnvelope::none();
for &class in DetectionClass::ALL {
assert!(!off.permits(class), "{} ran under off", class.label());
}
assert_eq!(off.ceiling(), None);
assert_eq!(off.to_string(), "off");
assert!(
off < DetectionEnvelope::up_to(DetectionClass::Passive),
"off does not sort below the quietest class"
);
}
#[test]
fn the_default_reads_but_does_not_probe() {
let envelope = DetectionEnvelope::default();
assert!(envelope.permits(DetectionClass::Passive));
assert!(
!envelope.permits(DetectionClass::ActiveBenign),
"a detection that opens its own connection runs without being asked for"
);
assert!(!envelope.permits(DetectionClass::ActiveMutating));
assert!(!envelope.permits(DetectionClass::Exploit));
assert!(!envelope.permits(DetectionClass::Dos));
}
#[test]
fn a_ceiling_parses_by_name_and_by_number_like_every_other_scale() {
for (index, class) in DetectionClass::ALL.iter().copied().enumerate() {
let expected = DetectionEnvelope::up_to(class);
assert_eq!(class.label().parse(), Ok(expected), "{class:?} by name");
assert_eq!(
(index + 1).to_string().parse(),
Ok(expected),
"{class:?} by number"
);
assert_eq!(
class.label().to_uppercase().parse(),
Ok(expected),
"case is not part of the name"
);
}
assert_eq!(
"active_benign".parse::<DetectionEnvelope>(),
"active-benign".parse::<DetectionEnvelope>()
);
assert!("everything".parse::<DetectionEnvelope>().is_err());
assert!(
(DetectionClass::ALL.len() + 1)
.to_string()
.parse::<DetectionEnvelope>()
.is_err(),
"a ceiling this engine does not offer is refused, not rounded down"
);
}
#[test]
fn a_refusal_names_every_ceiling_that_would_have_worked() {
let message = "everything"
.parse::<DetectionEnvelope>()
.unwrap_err()
.to_string();
for &class in DetectionClass::ALL {
assert!(
message.contains(class.label()),
"{message} omits {}",
class.label()
);
}
}
#[test]
fn a_rendered_envelope_parses_back_to_the_same_ceiling() {
for &class in DetectionClass::ALL {
let envelope = DetectionEnvelope::up_to(class);
assert_eq!(envelope.to_string().parse(), Ok(envelope));
}
}
#[test]
fn raising_the_ceiling_opens_the_classes_up_to_it_and_no_further() {
let envelope = DetectionEnvelope::up_to(DetectionClass::Exploit);
assert!(envelope.permits(DetectionClass::ActiveMutating));
assert!(envelope.permits(DetectionClass::Exploit));
assert!(!envelope.permits(DetectionClass::Dos));
}
}