stixflayer 0.1.1

Fast, spec-correct STIX 2.1 parsing, validation, and serialization in Rust.
Documentation
//! Data structures and functions for implementing STIX Relationship Objects (SROs).
#![allow(dead_code)]

use crate::error::CheckContext;

/// Builder for constructing STIX Relationship Objects (SROs).
pub mod builder;
/// The generic Relationship SRO, a typed connection between two STIX Objects.
pub mod relationship;
/// The Sighting SRO, an assertion that an object was seen in a context.
pub mod sighting;
/// Validation of the required common properties for SROs.
pub mod validation;

pub use builder::RelationshipObjectBuilder;
pub use relationship::Relationship;
pub use sighting::Sighting;
pub use validation::check_sro_properties;

/// Relationship type vocabulary used by SROs.
pub mod types;

use crate::{
    base::{CommonProperties, Stix},
    error::{add_error, return_multiple_errors, StixError as Error},
    types::{Identified, Identifier},
    validation::validate_value,
};
use stixflayer_derive::StixProperties;

use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use strum::{AsRefStr, Display as StrumDisplay};

/// A trait for all STIX Objects that can be related by SROs.
pub trait Related {
    /// Creates a relationship of the given type from this object to `target`.
    ///
    /// Returns a builder for the new SRO.
    fn add_relationship<T: Related + Identified>(
        self,
        target: T,
        relationship_type: String,
    ) -> Result<RelationshipObjectBuilder, Error>;
}

/// Represents a STIX Relationship Object (SRO).
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct RelationshipObject {
    /// Identifies the type of STIX Object.
    ///
    /// For SROs, this is either "relationship" for a generic relationship or "sighting"
    #[serde(flatten)]
    pub object_type: RelationshipObjectType,
    /// Common object properties
    #[serde(flatten)]
    pub common_properties: CommonProperties,
    /// Provides more details and context about the Relationship, potentially including its purpose and its key characteristics.
    pub description: Option<String>,
}

impl RelationshipObject {
    /// Deserializes an SRO from a JSON String.
    /// Checks that all fields conform to the STIX 2.1 standard.
    /// If the `allow_custom` flag is false, checks that there are no fields in the JSON String
    /// that are not in the SRO type definition.
    pub fn from_json(json: &str, 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, true)
    }

    /// Returns whether the SRO is marked as revoked.
    pub fn is_revoked(&self) -> bool {
        matches!(self.common_properties.revoked, Some(true))
    }

    /// Retunrs the relationship type for generic SROs or "sighting" if the SRO is a Sighting
    pub fn get_relationship_type(&self) -> &str {
        match &self.object_type {
            RelationshipObjectType::Relationship(relationship) => {
                relationship.relationship_type.as_ref()
            }
            RelationshipObjectType::Sighting(_) => "sighting",
        }
    }
}

/// Returns a reference to the identifier of the `RelationshipObject`.
// This implementation accesses the `id` field from the `common_properties`
// of the `RelationshipObject`, providing a way to retrieve the unique
// identifier associated with this object.
impl Identified for RelationshipObject {
    fn get_id(&self) -> &Identifier {
        &self.common_properties.id
    }
}

impl Stix for RelationshipObject {
    fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
        ctx.set_object_id(Some(self.get_id().to_string()));
        let mut errors = Vec::new();

        // Check that we have the correct common properties for an SRO
        add_error(&mut errors, check_sro_properties(&self.common_properties));

        // Check common properties
        add_error(&mut errors, self.common_properties.check(ctx));

        // Check the identifier (UUIDv5 is a SHOULD finding for non-SCOs).
        add_error(&mut errors, self.common_properties.id.check(ctx));

        // Check specific properties for the type of SRO
        match &self.object_type {
            RelationshipObjectType::Relationship(relationship) => add_error(
                &mut errors,
                relationship
                    .check(ctx)
                    .map_err(|e| Error::InvalidNestedObject {
                        context: format!(
                            "Relationship Object {} is not a valid generic relationship",
                            self.get_id()
                        ),
                        source: Box::new(e),
                    }),
            ),
            RelationshipObjectType::Sighting(sighting) => add_error(
                &mut errors,
                sighting.check(ctx).map_err(|e| Error::InvalidNestedObject {
                    context: format!(
                        "Relationship Object {} is not a valid sighting",
                        self.get_id()
                    ),
                    source: Box::new(e),
                }),
            ),
        }

        return_multiple_errors(errors)
    }
}

crate::impl_custom_properties_holder!(RelationshipObject);

/// Whether the SRO is a standard generic or a sighting
#[derive(
    Clone, Debug, PartialEq, Eq, Serialize, Deserialize, AsRefStr, StrumDisplay, StixProperties,
)]
#[serde(tag = "type", rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum RelationshipObjectType {
    /// A generic relationship between two STIX Objects.
    Relationship(Relationship),
    /// A sighting of a STIX Object in a context.
    Sighting(Sighting),
}