use std::collections::{HashMap, HashSet};
use crate::{
base::Stix,
bundles::Bundle,
error::{add_error, return_multiple_errors, CheckContext, StixError as Error},
object::StixObject,
relationship_objects::RelationshipObjectType,
types::Identified,
};
impl Bundle {
pub fn check_invariants(&self) -> Result<(), Error> {
let mut errors = Vec::new();
if &self.object_type != "bundle" {
errors.push(Error::ValidationError(format!(
"STIX bundles must have a `type` of 'bundle'. Bundle {} has a type of {}",
self.id, self.object_type
)));
}
add_error(&mut errors, self.id.check(&mut CheckContext::discard()));
if self.objects.is_empty() {
errors.push(Error::ValidationError(
"Bundle must contain at least one object".to_string(),
));
}
let mut seen_ids: HashMap<String, Option<String>> = HashMap::new();
for object in self.objects.iter() {
let id = object.get_id();
let modified = object.get_modified();
if let Some(prev_modified) = seen_ids.get(&id) {
let both_versioned =
prev_modified.is_some() && modified.is_some() && prev_modified != &modified;
if !both_versioned {
errors.push(Error::Located {
object_id: id.clone(),
error: Box::new(Error::ValidationError(format!(
"Bundle contains duplicate object id: {}",
id
))),
});
}
} else {
seen_ids.insert(id, modified);
}
}
let bundle_ids: HashSet<String> = self
.objects
.iter()
.filter(|obj| obj.get_type() != "relationship")
.map(|obj| obj.get_id())
.collect();
for object in self.objects.iter() {
if let StixObject::Sro(sro) = object {
if let RelationshipObjectType::Relationship(ref rel) = sro.object_type {
let relationship_id = sro.get_id().to_string();
if !bundle_ids.contains(&rel.source_ref.to_string()) {
errors.push(Error::Located {
object_id: relationship_id.clone(),
error: Box::new(Error::ValidationError(format!(
"Relationship object {} makes reference to {} which is not found in current bundle.",
relationship_id, rel.source_ref
))),
});
}
if !bundle_ids.contains(&rel.target_ref.to_string()) {
errors.push(Error::Located {
object_id: relationship_id.clone(),
error: Box::new(Error::ValidationError(format!(
"Relationship object {} makes reference to {} which is not found in current bundle.",
relationship_id, rel.target_ref
))),
});
}
}
}
}
return_multiple_errors(errors)
}
}
impl Stix for Bundle {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
let mut errors = Vec::new();
add_error(&mut errors, self.check_invariants());
for object in self.objects.iter() {
add_error(&mut errors, object.check(ctx));
}
return_multiple_errors(errors)
}
}