pub mod deserialize;
#[cfg(test)]
mod tests;
pub mod validation;
pub use deserialize::deserialize_bundle_objects;
use crate::{
error::{add_error, return_multiple_errors, Entry, Outcome, StixError as Error},
object::StixObject,
types::{Identified, Identifier},
validation::ValidationOptions,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bundle {
#[serde(rename = "type")]
pub object_type: String,
pub id: Identifier,
#[serde(deserialize_with = "deserialize_bundle_objects")]
pub objects: Vec<StixObject>,
}
impl Bundle {
pub fn new(object: StixObject) -> Self {
Self {
object_type: "bundle".to_string(),
id: Identifier::new("bundle").unwrap(),
objects: vec![object],
}
}
pub fn add(&mut self, object: StixObject) {
self.objects.push(object);
}
pub fn push_json(&mut self, json: &str) -> Result<(), Error> {
let object = StixObject::from_json(json, false)?;
self.objects.push(object);
Ok(())
}
pub fn from_json(json: &str) -> Result<Self, Error> {
Self::from_json_parts(json).0
}
pub fn from_json_with_options(json: &str, options: ValidationOptions) -> Result<Self, Error> {
Self::from_json_parts_with_options(json, options).0
}
pub fn from_json_outcome(json: &str) -> Outcome<Self> {
Self::from_json_outcome_with_options(json, ValidationOptions::new(true, true))
}
pub fn from_json_outcome_with_options(json: &str, options: ValidationOptions) -> Outcome<Self> {
let (result, warnings) = Self::from_json_parts_with_options(json, options);
Outcome::from_result(result, warnings)
}
pub fn from_json_parts(json: &str) -> (Result<Self, Error>, Vec<Entry>) {
Self::from_json_parts_with_options(json, ValidationOptions::new(true, true))
}
pub fn from_json_parts_with_options(
json: &str,
options: ValidationOptions,
) -> (Result<Self, Error>, Vec<Entry>) {
#[derive(Deserialize)]
struct RawBundle {
#[serde(rename = "type")]
object_type: String,
id: Identifier,
objects: Vec<Value>,
}
let raw: RawBundle = match serde_json::from_str(json) {
Ok(raw) => raw,
Err(e) => return (Err(Error::DeserializationError(e.to_string())), Vec::new()),
};
let mut objects = Vec::with_capacity(raw.objects.len());
let mut errors = Vec::new();
let mut warnings = Vec::new();
for value in raw.objects {
let (result, mut object_warnings) =
StixObject::from_value_parts_with_options(value, options);
warnings.append(&mut object_warnings);
match result {
Ok(object) => objects.push(object),
Err(error) => errors.push(error),
}
}
let bundle = Self {
object_type: raw.object_type,
id: raw.id,
objects,
};
if errors.is_empty() {
add_error(&mut errors, bundle.check_invariants());
}
(return_multiple_errors(errors).map(|()| bundle), warnings)
}
pub fn get_objects(&self) -> Vec<StixObject> {
self.objects.clone()
}
}
impl Identified for Bundle {
fn get_id(&self) -> &Identifier {
&self.id
}
}