use crate::error::Entry;
use crate::{
base::{CommonProperties, CommonPropertiesBuilder, Stix},
error::{return_multiple_errors, CheckContext, Outcome, StixError as Error},
relationship_objects::{Related, RelationshipObjectBuilder},
types::{ExternalReference, GranularMarking, Identified, Identifier, Timestamp},
validation::validate_value,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::collections::BTreeMap;
use stixflayer_derive::StixProperties;
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct MarkingDefinition {
#[serde(rename = "type")]
pub object_type: String,
#[serde(flatten)]
pub common_properties: CommonProperties,
pub name: Option<String>,
pub definition_type: Option<String>,
pub definition: Option<MarkingTypes>,
}
impl MarkingDefinition {
pub fn from_json(json: &str, strict: bool, allow_custom: bool) -> Result<Self, Error> {
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value(value, allow_custom, strict)
}
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 MarkingDefinition {
fn get_id(&self) -> &Identifier {
&self.common_properties.id
}
}
impl Related for MarkingDefinition {
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)
}
}
impl Stix for MarkingDefinition {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
ctx.set_object_id(Some(self.get_id().to_string()));
let mut errors = Vec::new();
if self.common_properties.spec_version.is_none() {
errors.push(Error::ValidationError(
"Marking Definition SMOs must have a `spec_version` property.".to_string(),
));
}
if self.common_properties.created.is_none() {
errors.push(Error::ValidationError(
"Marking Definition SMOs must have a `created` property.".to_string(),
));
}
if self.common_properties.extensions.is_none()
&& (self.definition_type.is_none() || self.definition.is_none())
{
errors.push(Error::ValidationError(
"Need properties extension to be present OR definition type or definition(exclusive).".to_string(),
));
}
if let Some(definition_type) = &self.definition_type {
if definition_type != "tlp" && definition_type != "statement" {
ctx.warn(
Entry::new(
"marking_definition_type_not_suggested",
format!(
"`definition_type` SHOULD be from the open vocabulary, either 'tlp' or 'statement'. Found '{}'.",
definition_type
),
)
.property("definition_type")
.value(definition_type.clone()),
);
}
}
if self.common_properties.defanged.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `defanged` property.".to_string(),
));
}
if self.common_properties.modified.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `modified` property.".to_string(),
));
}
if self.common_properties.revoked.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `revoked` property.".to_string(),
));
}
if self.common_properties.labels.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `labels` property.".to_string(),
));
}
if self.common_properties.confidence.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `confidence` property.".to_string(),
));
}
if self.common_properties.lang.is_some() {
errors.push(Error::ValidationError(
"Marking Definition SMOs cannot have a `lang` property.".to_string(),
));
}
return_multiple_errors(errors)
}
}
crate::impl_custom_properties_holder!(MarkingDefinition);
#[derive(Clone, Debug)]
pub struct MarkingDefinitionBuilder {
common_properties: CommonPropertiesBuilder,
name: Option<String>,
definition_type: Option<String>,
definition: Option<MarkingTypes>,
}
impl MarkingDefinitionBuilder {
pub fn new() -> Result<Self, Error> {
let common_properties =
CommonPropertiesBuilder::new("marking-definition", "marking-definition")?;
Ok(Self {
common_properties,
name: Default::default(),
definition_type: Default::default(),
definition: Default::default(),
})
}
pub fn created_by_ref(mut self, id: Identifier) -> Result<Self, Error> {
self.common_properties = self.common_properties.clone().created_by_ref(id)?;
Ok(self)
}
pub fn external_references(mut self, references: Vec<ExternalReference>) -> Self {
self.common_properties = self
.common_properties
.clone()
.external_references(references);
self
}
pub fn object_marking_refs(mut self, references: Vec<Identifier>) -> Self {
self.common_properties = self
.common_properties
.clone()
.object_marking_refs(references);
self
}
pub fn granular_markings(mut self, markings: Vec<GranularMarking>) -> Self {
self.common_properties = self.common_properties.clone().granular_markings(markings);
self
}
pub fn created(mut self, created: Timestamp) -> Self {
self.common_properties = self.common_properties.clone().created(created);
self
}
pub fn definition_type(mut self, definition_type: String) -> Self {
self.definition_type = Some(definition_type);
self
}
pub fn definition(mut self, definition: MarkingTypes) -> Self {
self.definition = Some(definition);
self
}
pub fn name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
pub fn custom_properties(mut self, custom_properties: BTreeMap<String, Value>) -> Self {
self.common_properties = self
.common_properties
.clone()
.custom_properties(custom_properties);
self
}
pub fn build_no_validate(self) -> Result<MarkingDefinition, Error> {
let common_properties = self.common_properties.build();
let name = self.name;
let definition_type = self.definition_type;
let definition = self.definition;
let marking_definition = MarkingDefinition {
object_type: "marking-definition".to_string(),
common_properties,
name,
definition_type,
definition,
};
Ok(marking_definition)
}
pub fn build(self) -> Result<MarkingDefinition, Error> {
let object = self.build_no_validate()?;
object.stix_check()?;
Ok(object)
}
pub fn build_outcome(self) -> Outcome<MarkingDefinition> {
let object = match self.build_no_validate() {
Ok(object) => object,
Err(error) => return Outcome::err(error, Vec::new()),
};
let mut ctx = CheckContext::new();
let result = object.check(&mut ctx).map(|()| object);
Outcome::from_result(result, ctx.into_warnings())
}
pub fn version(old: &MarkingDefinition) -> Result<Self, Error> {
let old_properties = old.common_properties.clone();
let common_properties =
CommonPropertiesBuilder::version("marking-definition", &old_properties)?;
Ok(Self {
common_properties,
name: old.name.clone(),
definition_type: old.definition_type.clone(),
definition: old.definition.clone(),
})
}
pub fn from_parsed(old: &MarkingDefinition) -> Result<Self, Error> {
let old_properties = old.common_properties.clone();
let common_properties =
CommonPropertiesBuilder::from_existing("marking-definition", &old_properties)?;
Ok(Self {
common_properties,
name: old.name.clone(),
definition_type: old.definition_type.clone(),
definition: old.definition.clone(),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MarkingTypes {
Tlp(TLP),
Statement(Statement),
}
impl Stix for MarkingTypes {
fn check(&self, _ctx: &mut CheckContext) -> Result<(), Error> {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TLP {
pub tlp: String,
}
impl Stix for TLP {
fn check(&self, _ctx: &mut CheckContext) -> Result<(), Error> {
if self.tlp != "white" && self.tlp != "red" && self.tlp != "amber" && self.tlp != "green" {
return Err(Error::ValidationError(
"TLP value must be one of the four TLP levels".to_string(),
));
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Statement {
pub statement: String,
}
impl Stix for Statement {
fn check(&self, _ctx: &mut CheckContext) -> Result<(), Error> {
Ok(())
}
}