use crate::error::CheckContext;
use crate::{
base::{
validate_custom_property_name, validate_custom_property_suffix_value, CommonProperties,
Stix,
},
custom_objects::validation::check_custom_object_type,
cyber_observable_objects::sco::check_sco_properties,
domain_objects::sdo::check_sdo_properties,
error::{add_error, return_multiple_errors, Entry, StixError as Error},
relationship_objects::{check_sro_properties, Related, RelationshipObjectBuilder},
types::{get_extension_type, ExtensionType, Identified, Identifier},
validation::validate_value,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::{collections::BTreeMap, str::FromStr};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CustomObjectKind {
Sdo,
Sco,
Sro,
Generic,
}
impl CustomObjectKind {
pub fn extension_type(self) -> Option<ExtensionType> {
match self {
Self::Sdo => Some(ExtensionType::NewSdo),
Self::Sco => Some(ExtensionType::NewSco),
Self::Sro => Some(ExtensionType::NewSro),
Self::Generic => None,
}
}
}
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomObject {
#[serde(rename = "type")]
pub object_type: String,
#[serde(flatten)]
pub common_properties: CommonProperties,
#[serde(flatten)]
pub custom_properties: BTreeMap<String, Value>,
}
impl CustomObject {
pub fn from_json(json: &str) -> Result<Self, Error> {
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value(value, true, true)
}
pub fn get_kind(&self) -> CustomObjectKind {
let Some(extensions) = &self.common_properties.extensions else {
return CustomObjectKind::Generic;
};
for (extension_key, extension) in extensions.iter() {
let Ok(id) = Identifier::from_str(extension_key) else {
continue;
};
if id.get_type() != "extension-definition" {
continue;
}
match get_extension_type(extension) {
Some(ExtensionType::NewSdo) => return CustomObjectKind::Sdo,
Some(ExtensionType::NewSco) => return CustomObjectKind::Sco,
Some(ExtensionType::NewSro) => return CustomObjectKind::Sro,
Some(ExtensionType::PropertyExtension)
| Some(ExtensionType::ToplevelPropertyExtension) => continue,
None => continue,
}
}
CustomObjectKind::Generic
}
pub fn get_object_type(&self) -> Option<ExtensionType> {
self.get_kind().extension_type()
}
pub fn get_modified(&self) -> Option<String> {
self.common_properties
.modified
.as_ref()
.map(|modified| modified.to_string())
}
pub fn is_revoked(&self) -> bool {
matches!(self.common_properties.revoked, Some(true))
}
pub fn add_sighting(self) -> Result<RelationshipObjectBuilder, Error> {
let sighting_of_ref = self.get_id().to_owned();
RelationshipObjectBuilder::new_sighting(sighting_of_ref)
}
}
impl Identified for CustomObject {
fn get_id(&self) -> &Identifier {
&self.common_properties.id
}
}
impl Related for CustomObject {
fn add_relationship<T: Related + Identified>(
self,
target: T,
relationship_type: String,
) -> Result<RelationshipObjectBuilder, Error> {
let source_id = self.get_id().to_owned();
let target_id = target.get_id().to_owned();
RelationshipObjectBuilder::new(source_id, target_id, &relationship_type)
}
}
crate::impl_custom_properties_holder!(CustomObject);
impl Stix for CustomObject {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
ctx.set_object_id(Some(self.get_id().to_string()));
let mut common_errors = Vec::new();
add_error(&mut common_errors, self.common_properties.check(ctx));
return_multiple_errors(common_errors)?;
let kind = self.get_kind();
if kind == CustomObjectKind::Generic {
ctx.warn(
Entry::new(
"custom_missing_extension",
format!(
"Custom object {} does not declare a new-sdo, new-sco, or new-sro extension; it was validated as a generic custom object",
self.common_properties.id
),
)
.property("extensions"),
);
}
let mut errors = Vec::new();
add_error(&mut errors, check_custom_object_type(&self.object_type));
if self.common_properties.id.get_type() != self.object_type {
errors.push(Error::ValidationError(format!(
"The `id` prefix '{}' does not match the custom object type '{}'",
self.common_properties.id.get_type(),
self.object_type
)));
}
add_error(&mut errors, self.common_properties.id.check(ctx));
match kind {
CustomObjectKind::Sdo => {
add_error(&mut errors, check_sdo_properties(&self.common_properties));
}
CustomObjectKind::Sro => {
add_error(&mut errors, check_sro_properties(&self.common_properties));
}
CustomObjectKind::Sco => {
add_error(&mut errors, check_sco_properties(&self.common_properties));
}
CustomObjectKind::Generic => {}
}
for (key, value) in self.custom_properties.iter() {
add_error(&mut errors, validate_custom_property_name(key));
add_error(
&mut errors,
validate_custom_property_suffix_value(key, value),
);
}
add_error(&mut errors, self.custom_properties.check(ctx));
return_multiple_errors(errors)
}
}