use crate::error::CheckContext;
use crate::{
base::Stix,
common::string::stix_case,
error::{add_error, return_multiple_errors, StixError as Error},
taxonomy::ExtensionType,
};
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt, str::FromStr};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StixDictionary<T: Stix>(BTreeMap<String, T>);
impl<T: Stix> StixDictionary<T> {
pub fn new() -> Self {
Self(BTreeMap::new())
}
pub fn insert(&mut self, key: &str, value: T) -> Result<(), Error> {
if check_dictionary_key(key) {
match self.0.insert(key.to_string(), value) {
Some(_duplicate_key) => Err(Error::ValidationError(format!(
"Duplicate value specified for {}",
key
))),
None => Ok(()),
}
} else {
Err(Error::ValidationError(format!("Key {} is not a valid key under STIX policies. Keys may only contain letters, numbers, '-, or '_'.", key)))
}
}
pub fn get(&self, key: &str) -> Option<&T> {
self.0.get(key)
}
pub fn keys(&self) -> impl Iterator<Item = &String> {
self.0.keys()
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
self.0.iter()
}
}
impl<T: Stix> Default for StixDictionary<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Stix> Stix for StixDictionary<T> {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
if self.0.is_empty() {
return Err(Error::EmptyList);
}
let mut errors = Vec::new();
for (key, val) in self.iter() {
if !check_dictionary_key(key) {
errors.push(Error::ValidationError(format!("Key {} is not a valid key under STIX policies. Keys may only contain letters, numbers, '-, or '_'.", key)))
}
add_error(&mut errors, val.check(ctx));
}
return_multiple_errors(errors)
}
}
fn check_dictionary_key(key: &str) -> bool {
key.len() <= 250
&& (key
.chars()
.all(|c| c.is_ascii() && (c.is_alphanumeric() || c == '-' || c == '_')))
}
pub fn check_observable_dictionary_key(key: &str) -> Result<(), Error> {
if key.chars().any(|c| c.is_uppercase()) {
return Err(Error::ValidationError(format!(
"Observable dictionary key '{}' contains uppercase characters. Dictionary keys SHOULD be lowercase.",
key
)));
}
if key.len() > 250 {
return Err(Error::ValidationError(format!(
"Observable dictionary key '{}' exceeds the maximum length of 250 characters.",
key
)));
}
Ok(())
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum DictionaryValue {
String(String),
Bool(bool),
Int(u64),
SInt(i64),
Float(OrderedFloat<f64>),
List(Vec<DictionaryValue>),
Dict(StixDictionary<DictionaryValue>),
}
impl fmt::Display for DictionaryValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DictionaryValue::String(string) => write!(f, "{string}"),
DictionaryValue::Bool(bool) => write!(f, "{bool}"),
DictionaryValue::Int(int) => write!(f, "{int}"),
DictionaryValue::SInt(signed) => write!(f, "{signed}"),
DictionaryValue::Float(float) => write!(f, "{float}"),
DictionaryValue::List(list) => {
let mut vec_string = String::new();
vec_string.push('[');
for item in list {
vec_string.push_str(&item.to_string());
vec_string.push_str(", ");
}
vec_string.pop();
vec_string.pop();
vec_string.push(']');
write!(f, "{vec_string}")
}
DictionaryValue::Dict(dict) => {
let mut dict_string = String::new();
dict_string.push('{');
for (key, value) in dict.iter() {
dict_string.push_str(&format!("{}: {}", key, value));
dict_string.push_str(", ");
}
dict_string.pop();
dict_string.pop();
dict_string.push('}');
write!(f, "{dict_string}")
}
}
}
}
impl Stix for DictionaryValue {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
match self {
DictionaryValue::String(string) => string.check(ctx),
DictionaryValue::Bool(bool) => bool.check(ctx),
DictionaryValue::Int(int) => int.check(ctx),
DictionaryValue::SInt(_signed) => Ok(()),
DictionaryValue::Float(float) => float.check(ctx),
DictionaryValue::List(list) => list.check(ctx),
DictionaryValue::Dict(dict) => dict.check(ctx),
}
}
}
pub fn get_extension_type(extension: &StixDictionary<DictionaryValue>) -> Option<ExtensionType> {
match extension.get("extension_type") {
Some(DictionaryValue::String(extension_type)) => {
ExtensionType::from_str(&stix_case(extension_type)).ok()
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dictionary_keys_allow_up_to_250_characters() {
let mut dictionary = StixDictionary::<DictionaryValue>::new();
let key31 = "a".repeat(31);
assert!(dictionary
.insert(&key31, DictionaryValue::String("value".to_string()))
.is_ok());
let mut dictionary = StixDictionary::<DictionaryValue>::new();
let key251 = "a".repeat(251);
assert!(dictionary
.insert(&key251, DictionaryValue::String("value".to_string()))
.is_err());
}
#[test]
fn dictionary_check_does_not_warn_for_uppercase_keys() {
let mut dictionary = StixDictionary::<DictionaryValue>::new();
dictionary
.insert("XResolution", DictionaryValue::String("72".to_string()))
.unwrap();
assert!(dictionary.outcome().warnings.is_empty());
}
}