use std::fmt::{Display, Formatter};
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::error::{CVSSError, Result};
use crate::metric::{Help, Metric, MetricType, MetricTypeV2, Worth};
#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AccessComplexityType {
High,
Medium,
Low,
}
impl Display for AccessComplexityType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", Self::name(), self.as_str())
}
}
impl AccessComplexityType {
pub fn metric_help(&self) -> Help {
self.help()
}
}
impl Metric for AccessComplexityType {
const TYPE: MetricType = MetricType::V2(MetricTypeV2::AC);
fn help(&self) -> Help {
match self {
Self::High => Help {
worth: Worth::Bad,
des: "In most configurations, the attacking party must already have elevated privileges or spoof additional systems in addition to the attacking system (e.g., DNS hijacking).".to_string(),
},
Self::Medium => Help {
worth: Worth::Worse,
des: "The attacking party is limited to a group of systems or users at some level of authorization, possibly untrusted.".to_string(),
},
Self::Low => Help {
worth: Worth::Worst,
des: "The affected product typically requires access to a wide range of systems and users, possibly anonymous and untrusted (e.g., Internet-facing web or mail server).".to_string(),
},
}
}
fn score(&self) -> f32 {
match self {
Self::High => 0.35,
Self::Medium => 0.61,
Self::Low => 0.71,
}
}
fn as_str(&self) -> &'static str {
match self {
Self::High => "H",
Self::Medium => "M",
Self::Low => "L",
}
}
}
impl FromStr for AccessComplexityType {
type Err = CVSSError;
fn from_str(s: &str) -> Result<Self> {
let name = Self::name();
let s = s.to_uppercase();
let (_name, v) = s
.split_once(&format!("{}:", name))
.ok_or(CVSSError::InvalidCVSS {
key: name.to_string(),
value: s.to_string(),
expected: name.to_string(),
})?;
let c = v.chars().next();
match c {
Some('H') => Ok(Self::High),
Some('M') => Ok(Self::Medium),
Some('L') => Ok(Self::Low),
_ => Err(CVSSError::InvalidCVSS {
key: name.to_string(),
value: format!("{:?}", c),
expected: "H,M,L".to_string(),
}),
}
}
}