use std::fmt::{Display, Formatter};
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::error::{CVSSError, Result};
use crate::metric::{Help, Metric, MetricType, MetricTypeV3, Worth};
#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum UserInteractionType {
Required,
None,
}
impl Display for UserInteractionType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", Self::name(), self.as_str())
}
}
impl UserInteractionType {
pub fn metric_help(&self) -> Help {
self.help()
}
}
impl Metric for UserInteractionType {
const TYPE: MetricType = MetricType::V3(MetricTypeV3::UI);
fn help(&self) -> Help {
match self {
Self::Required => { Help { worth: Worth::Bad, des: "Successful exploitation of this vulnerability requires a user to take some action before the vulnerability can be exploited. For example, a successful knowledge_base may only be possible during the installation of an application by a system administrator.".to_string() } }
Self::None => {Help{ worth: Worth::Worst, des: "The vulnerable system can be exploited without interaction from any user.".to_string() }}
}
}
fn score(&self) -> f32 {
match self {
Self::Required => 0.62,
Self::None => 0.85,
}
}
fn as_str(&self) -> &'static str {
match self {
Self::Required => "R",
Self::None => "N",
}
}
}
impl FromStr for UserInteractionType {
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('N') => Ok(Self::None),
Some('R') => Ok(Self::Required),
_ => Err(CVSSError::InvalidCVSS {
key: name.to_string(),
value: format!("{:?}", c),
expected: "N,R".to_string(),
}),
}
}
}