use serde::{Deserialize, Serialize};
use super::StixError;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
pub kind: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub property: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub vocabulary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub object_id: Option<String>,
}
impl Entry {
pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
Self {
kind: kind.into(),
message: message.into(),
..Default::default()
}
}
pub fn property(mut self, property: impl Into<String>) -> Self {
self.property = Some(property.into());
self
}
pub fn value(mut self, value: impl Into<String>) -> Self {
self.value = Some(value.into());
self
}
pub fn vocabulary(mut self, vocabulary: impl Into<String>) -> Self {
self.vocabulary = Some(vocabulary.into());
self
}
pub fn object_id(mut self, object_id: impl Into<String>) -> Self {
self.object_id = Some(object_id.into());
self
}
fn dedupe_key(&self) -> (Option<&str>, &str, Option<&str>, Option<&str>) {
(
self.object_id.as_deref(),
self.kind.as_str(),
self.property.as_deref(),
self.value.as_deref(),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Outcome<T = ()> {
pub valid: bool,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub value: Option<T>,
pub errors: Vec<Entry>,
pub warnings: Vec<Entry>,
}
impl<T> Outcome<T> {
pub fn from_result(result: Result<T, StixError>, warnings: Vec<Entry>) -> Self {
match result {
Ok(value) => Self {
valid: true,
value: Some(value),
errors: Vec::new(),
warnings,
},
Err(error) => Self {
valid: false,
value: None,
errors: error.errors(),
warnings,
},
}
}
pub fn ok(value: T, warnings: Vec<Entry>) -> Self {
Self {
valid: true,
value: Some(value),
errors: Vec::new(),
warnings,
}
}
pub fn valid(warnings: Vec<Entry>) -> Outcome<()> {
Outcome {
valid: true,
value: Some(()),
errors: Vec::new(),
warnings,
}
}
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Outcome<U> {
Outcome {
valid: self.valid,
value: self.value.map(f),
errors: self.errors,
warnings: self.warnings,
}
}
pub fn into_result(self) -> Result<T, StixError> {
match self.value {
Some(value) if self.valid => Ok(value),
_ => {
let errors = self
.errors
.into_iter()
.map(|entry| StixError::ValidationError(entry.message))
.collect::<Vec<_>>();
Err(if errors.len() == 1 {
errors.into_iter().next().expect("one error")
} else {
StixError::ValidationErrors(errors)
})
}
}
}
pub fn err(error: StixError, warnings: Vec<Entry>) -> Self {
Self {
valid: false,
value: None,
errors: error.errors(),
warnings,
}
}
}
impl<T: Serialize> Outcome<T> {
pub fn to_json(&self) -> serde_json::Value {
serde_json::to_value(self).expect("Outcome serializes to JSON")
}
}
#[derive(Debug, Default, Clone)]
pub struct CheckContext {
warnings: Vec<Entry>,
object_id: Option<String>,
}
impl CheckContext {
pub fn new() -> Self {
Self::default()
}
pub fn discard() -> Self {
Self::default()
}
pub fn set_object_id(&mut self, object_id: Option<String>) -> Option<String> {
std::mem::replace(&mut self.object_id, object_id)
}
pub fn warn(&mut self, mut entry: Entry) {
if entry.object_id.is_none() {
entry.object_id = self.object_id.clone();
}
let key = entry.dedupe_key();
let duplicate = self.warnings.iter().any(|existing| {
let existing_key = existing.dedupe_key();
existing_key == key
});
if !duplicate {
self.warnings.push(entry);
}
}
pub fn warnings(&self) -> &[Entry] {
&self.warnings
}
pub fn into_warnings(self) -> Vec<Entry> {
self.warnings
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn outcome_serializes_expected_shape() {
let outcome = Outcome::ok(
"value".to_string(),
vec![Entry::new("hash_not_sha256", "use sha-256").property("hashes")],
);
let json = outcome.to_json();
assert_eq!(json["valid"], true);
assert_eq!(json["value"], "value");
assert!(json["errors"].as_array().unwrap().is_empty());
assert_eq!(json["warnings"].as_array().unwrap().len(), 1);
assert_eq!(json["warnings"][0]["kind"], "hash_not_sha256");
assert_eq!(json["warnings"][0]["property"], "hashes");
assert!(json.get("level").is_none());
assert!(json.get("severity").is_none());
}
#[test]
fn optional_fields_are_omitted() {
let entry = Entry::new("some_kind", "message");
let json = serde_json::to_value(&entry).unwrap();
for key in ["property", "value", "vocabulary", "object_id"] {
assert!(json.get(key).is_none(), "{key} should be omitted: {json}");
}
assert!(json.get("properties").is_none());
assert!(json.get("expected").is_none());
assert!(json.get("got").is_none());
}
#[test]
fn outcome_with_no_findings_is_valid() {
let outcome = Outcome::<()>::valid(Vec::new());
assert!(outcome.valid);
assert!(outcome.errors.is_empty());
assert!(outcome.warnings.is_empty());
}
#[test]
fn outcome_with_warnings_is_valid() {
let mut ctx = CheckContext::new();
ctx.warn(Entry::new("hash_not_sha256", "use sha-256"));
let outcome = Outcome::<()>::valid(ctx.into_warnings());
assert!(outcome.valid);
assert!(outcome.errors.is_empty());
assert_eq!(outcome.warnings.len(), 1);
}
#[test]
fn outcome_from_error_is_invalid_without_value() {
let outcome: Outcome<()> = Outcome::from_result(Err(StixError::EmptyList), Vec::new());
assert!(!outcome.valid);
assert!(outcome.value.is_none());
assert_eq!(outcome.errors.len(), 1);
}
#[test]
fn context_stamps_object_id() {
let mut ctx = CheckContext::new();
ctx.set_object_id(Some("identity--123".to_string()));
ctx.warn(Entry::new("open_vocab_value_not_suggested", "message"));
assert_eq!(
ctx.warnings()[0].object_id.as_deref(),
Some("identity--123")
);
}
#[test]
fn contexts_do_not_leak() {
let mut first = CheckContext::new();
first.warn(Entry::new("hash_not_sha256", "message"));
let second = CheckContext::new();
assert_eq!(first.into_warnings().len(), 1);
assert!(second.into_warnings().is_empty());
}
#[test]
fn duplicate_warnings_are_dropped() {
let mut ctx = CheckContext::new();
ctx.set_object_id(Some("identity--123".to_string()));
ctx.warn(Entry::new("hash_not_sha256", "first").property("hashes"));
ctx.warn(Entry::new("hash_not_sha256", "second").property("hashes"));
assert_eq!(ctx.warnings().len(), 1);
ctx.warn(Entry::new("hash_not_sha256", "third").property("other"));
assert_eq!(ctx.warnings().len(), 2);
}
}