stixflayer 0.1.0

Fast STIX 2.1 parsing, validation, and serialization in Rust
Documentation
//! Property registry for STIX types.
//!
//! For every known STIX type name this registry answers "which JSON property
//! names are structurally valid, and which are required" *without* needing a
//! successfully parsed object. The per-type property lists are generated at
//! compile time from the type structs by `#[derive(StixProperties)]`
//! (see rust/stixflayer_derive); this module composes them with the category-level
//! common property subsets that `stix_check` enforces
//! (check_sdo_properties / check_sco_properties / check_sro_properties).
//!
//! Consumers:
//! - the collect-all validation flow uses `type_properties` to report unknown
//!   and missing properties together, instead of stopping at the first serde
//!   parse failure;
//! - unknown types (custom objects, bundles) return `None`, meaning
//!   "structurally permissive" (custom-property legality remains the job of
//!   `stix_check`).

use std::collections::HashMap;
use std::sync::LazyLock;

use crate::base::CommonProperties;
use crate::cyber_observable_objects::sco::CYBER_OBJECT_TYPE_VARIANTS;
use crate::domain_objects::sdo::DOMAIN_OBJECT_TYPE_VARIANTS;
use crate::meta_objects::extension_definition::ExtensionDefinition;
use crate::meta_objects::language_content::LanguageContent;
use crate::meta_objects::marking_definition::MarkingDefinition;
use crate::relationship_objects::RELATIONSHIP_OBJECT_TYPE_VARIANTS;
use crate::types::get_object_type;

/// The property registry trait. Impls are generated by
/// `#[derive(StixProperties)]` (see rust/stixflayer_derive).
///
/// KNOWN lists every JSON property name the type structurally accepts;
/// REQUIRED lists the subset that must be present (serde-non-optional
/// fields). Category-level common property legality (e.g. "SCOs cannot have
/// a `created` property") is enforced by `stix_check` and mirrored in the
/// composed registry below.
///
/// Note: the derive references this trait by `crate::properties::` path, so
/// it is only usable from within this crate.
pub trait StixProperties {
    /// KNOWN lists every JSON property name the type structurally accepts.
    const KNOWN: &'static [&'static str];
    /// REQUIRED lists the subset that must be present (serde-non-optional).
    const REQUIRED: &'static [&'static str];
}

/// Per-variant entry of a tagged enum's property table.
pub struct VariantProps {
    pub tag: &'static str,
    pub known: &'static [&'static str],
    pub required: &'static [&'static str],
}

/// The property lists for a composed STIX type.
pub struct TypeProperties {
    pub known: Vec<&'static str>,
    pub required: Vec<&'static str>,
}

/// The tag key every known STIX object type uses.
const TYPE_KEY: &str = "type";

/// SCOs structurally accept only this subset of the common properties
/// (mirrors check_sco_properties).
const SCO_COMMON: &[&str] = &[
    "spec_version",
    "id",
    "defanged",
    "extensions",
    "object_marking_refs",
    "granular_markings",
];

/// SDO/SRO/meta structurally accept every common property except `defanged`
/// (mirrors check_sdo_properties / check_sro_properties).
fn common_except_defanged() -> Vec<&'static str> {
    CommonProperties::KNOWN
        .iter()
        .copied()
        .filter(|k| *k != "defanged")
        .collect()
}

fn compose(variant: &VariantProps, common: &[&'static str]) -> TypeProperties {
    let mut known: Vec<&'static str> = Vec::with_capacity(variant.known.len() + common.len() + 1);
    known.extend_from_slice(variant.known);
    known.extend_from_slice(common);
    known.push(TYPE_KEY);
    let mut required: Vec<&'static str> = Vec::with_capacity(variant.required.len() + 1);
    required.extend_from_slice(variant.required);
    required.extend_from_slice(CommonProperties::REQUIRED);
    TypeProperties { known, required }
}

fn compose_meta(
    tag: &'static str,
    known: &'static [&'static str],
    required: &'static [&'static str],
    common: &[&'static str],
) -> TypeProperties {
    compose(
        &VariantProps {
            tag,
            known,
            required,
        },
        common,
    )
}

/// Registry of every known STIX type's composed property lists.
static REGISTRY: LazyLock<HashMap<&'static str, TypeProperties>> = LazyLock::new(|| {
    let mut m: HashMap<&'static str, TypeProperties> = HashMap::new();

    // SDOs
    let sdo_common = common_except_defanged();
    for variant in DOMAIN_OBJECT_TYPE_VARIANTS {
        m.insert(variant.tag, compose(variant, &sdo_common));
    }

    // SCOs
    for variant in CYBER_OBJECT_TYPE_VARIANTS {
        m.insert(variant.tag, compose(variant, SCO_COMMON));
    }

    // SROs
    let mut sro_common = common_except_defanged();
    sro_common.push("description");
    for variant in RELATIONSHIP_OBJECT_TYPE_VARIANTS {
        m.insert(variant.tag, compose(variant, &sro_common));
    }

    // Meta objects
    let meta_common = common_except_defanged();
    m.insert(
        "marking-definition",
        compose_meta(
            "marking-definition",
            MarkingDefinition::KNOWN,
            MarkingDefinition::REQUIRED,
            &meta_common,
        ),
    );
    m.insert(
        "language-content",
        compose_meta(
            "language-content",
            LanguageContent::KNOWN,
            LanguageContent::REQUIRED,
            &meta_common,
        ),
    );
    m.insert(
        "extension-definition",
        compose_meta(
            "extension-definition",
            ExtensionDefinition::KNOWN,
            ExtensionDefinition::REQUIRED,
            &meta_common,
        ),
    );

    m
});

/// Returns the composed property lists for a STIX type name, or `None` for
/// structurally permissive types (custom objects, bundles).
///
/// `type_name` must already be kebab-case (as it appears in the JSON `type`
/// field). The legacy `email-address` spelling is accepted as an alias for
/// `email-addr`.
pub fn type_properties(type_name: &str) -> Option<&'static TypeProperties> {
    REGISTRY.get(type_name)
}

/// Returns the composed property lists for a STIX type name based on its
/// category (see get_object_type), or `None` if the category is structurally
/// permissive (custom, bundle) or the type name is unknown in that category.
#[allow(dead_code)]
pub fn type_properties_by_category(type_name: &str) -> Option<&'static TypeProperties> {
    match get_object_type(type_name) {
        cat if cat == "custom" || cat == "bundle" => None,
        _ => type_properties(type_name),
    }
}