stixflayer 0.1.0

Fast STIX 2.1 parsing, validation, and serialization in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Data structures and functions for implementing Lanugage Content SMOs

use std::str::FromStr;
use stixflayer_derive::StixProperties;

use crate::{
    base::{CommonProperties, CommonPropertiesBuilder, Stix},
    error::{add_error, return_multiple_errors, StixError as Error},
    relationship_objects::{Related, RelationshipObjectBuilder},
    types::{
        DictionaryValue, ExternalReference, GranularMarking, Identified, Identifier,
        StixDictionary, Timestamp,
    },
    validation::validate_value,
};
use language_tags::LanguageTag;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::collections::{BTreeMap, HashMap};
use uuid::Uuid;

/// A Language Content Stix Meta Object (SMO).
///
/// The Language Content object represents text content for STIX Objects represented in languages other than that of the original object. Language content may be a
/// translation of the original object by a third-party, a first-source translation by the original publisher, or additional official language content provided at the time
/// of creation.
///
/// Language Content contains two important sets of properties:
/// - The `object_ref` and `object_modified` properties specify the target object that the language content applies to.
///    - For example, to provide additional language content for a Campaign, the `object_ref` property should be set to the `id` of the Campaign and the `object_modified`
///      property set to its modified time. Most relationships in STIX are not specific to a particular version of a STIX object, but because language content provides the
///      translation of specific text, the `object_modified` property is necessary to provide that specificity.
/// - The `content` property is a dictionary which maps to properties in the target object in order to provide a translation of them.
///
/// For more information see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_z9r1cwtu8jja>
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct LanguageContent {
    #[serde(rename = "type")]
    pub object_type: String,
    /// Common STIX object properties
    #[serde(flatten)]
    pub common_properties: CommonProperties,
    /// The `object_ref` property identifies the `id` of the object that this LanguageContent applies to. It **MUST** be the identifier for a STIX Object.
    pub object_ref: Identifier,
    /// The `object_modified` property identifies the modified time of the object that this LanguageContent applies to. It **MUST** be an exact match for the `modified` time
    /// of the STIX Object being referenced.
    pub object_modified: Option<Timestamp>,
    /// The contents property contains the actual Language Content (translation).
    ///
    /// The keys in the dictionary **MUST** be RFC 5646 language codes for which language content is being provided.
    ///
    /// The values each consist of a Vec that mirrors the properties in the target object (identified by `object_ref` and `object_modified`).
    pub contents: StixDictionary<StixDictionary<ContentType>>,
}

impl LanguageContent {
    /// Deserializes a LanguageContent SMO 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 Language Content SMO 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)
    }

    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)
    }
}

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

impl Related for LanguageContent {
    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!(LanguageContent);

impl Stix for LanguageContent {
    fn stix_check(&self) -> Result<(), Error> {
        let mut errors = Vec::new();

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

        // Check that required common properties fields are present and prohibited common properties fields are absent

        // Check that the `spec_version` field exists for Language Content SMOs
        if self.common_properties.spec_version.is_none() {
            errors.push(Error::ValidationError(
                "Language Content SMOs must have a `spec_version` property.".to_string(),
            ));
        }
        // Check that the `created` field exists for Language Content SMOs
        if self.common_properties.created.is_none() {
            errors.push(Error::ValidationError(
                "Language Content SMOs must have a `created` property.".to_string(),
            ));
        }
        // Check that the `modified` field exists for Language Content SMOs
        if self.common_properties.modified.is_none() {
            errors.push(Error::ValidationError(
                "Language Content SMOs must have a `modified` property.".to_string(),
            ));
        }
        // Check that the `lang` property is `None` for Language Content SMOs
        if self.common_properties.lang.is_some() {
            errors.push(Error::ValidationError(
                "Language Content SMOs cannot have a `lang` property.".to_string(),
            ));
        }
        // Check that the `defanged` property is `None` for Language Content SMOs
        if self.common_properties.defanged.is_some() {
            errors.push(Error::ValidationError(
                "Language Content SMOs cannot have a `defanged` property.".to_string(),
            ));
        }

        // Check specific LanguageContent type constraints
        if self.object_type != "language-content" {
            errors.push(Error::ValidationError(
                "Language Content SMOs must have a type of 'language-content'".to_string(),
            ));
        }

        // Validate that the `contents` field is a valid STIX Dictionary
        add_error(&mut errors, self.contents.stix_check());
        for (key, value) in self.contents.iter() {
            // Check that a dictionary key is an RFC5646 language code
            match LanguageTag::parse(key) {
                Ok(tag) => if let Err(e) = LanguageTag::validate(&tag) {
                    errors.push(Error::ValidationError(format!("One of the keys for LanguageContent Object {}'s `contents` dictionary is {}. A `content` key must conform to RFC5646. Details: {}",
                    self.common_properties.id,
                    key,
                    e
                )));
                }
                Err(e) => errors.push(Error::ValidationError(format!("One of the keys for LanguageContent Object {}'s `contents` dictionary is {}. A `content` key must conform to RFC5646. Details: {}",
                    self.common_properties.id,
                    key,
                    e
                ))),
            }
            // Check that the nested dictionary is a valid STIX Dictionary
            add_error(&mut errors, value.stix_check());
            // Check that subkeys are valid property names: ^[a-z0-9_]{3,250}$
            for (subkey, _) in value.iter() {
                let valid = subkey.len() >= 3
                    && subkey.len() <= 250
                    && subkey
                        .chars()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
                if !valid {
                    errors.push(Error::ValidationError(format!(
                        "'{}' in '{}' of the 'contents' property is invalid and must match a valid property name",
                        subkey, key,
                    )));
                }
            }
        }

        return_multiple_errors(errors)
    }
}

/// Options for the values of a LanguageContent `contents` dictionary
///
/// These values **MUST** mirror the original properties of the target object (e.g. if the original property is a String, the corresponding value must be a String)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContentType {
    /// Translation of a single String
    String(String),
    /// Translation of a list of items. If no translation is provided for one or more elements of the original list, the untranlated items must be represented by ""
    List(Vec<String>),
    /// Translation of an entire STIX object or dictionary, represented as a nested LanguageContent object with its own properties based on the translated object or dictionary
    Object(Box<LanguageContent>),
}

impl Stix for ContentType {
    fn stix_check(&self) -> Result<(), Error> {
        match self {
            ContentType::String(string) => string.stix_check(),
            ContentType::List(list) => list.stix_check(),
            ContentType::Object(content) => content.stix_check(),
        }
    }
}

/// Builder struct for Language Content SMOs.
///
/// This follows the "Rust builder pattern," where we  use a `new()` function to construct a Builder
/// with a minimum set of required fields, then set additional fields with their own setter functions.
/// Once all fields have been set, the `build()` function will take all of the fields in the Builder
/// struct and use them to create the final `LanguageContent` struct.
///
/// Note: Because the `contents` dictionary property must be nonempty, the `build()` method will error
/// if no entries are added to this property, or if the `created_by_ref` property is not set.
#[derive(Clone, Debug)]
pub struct LanguageContentBuilder {
    /// Common STIX properties
    common_properties: CommonPropertiesBuilder,
    object_ref: Identifier,
    object_modified: Option<Timestamp>,
    contents: StixDictionary<StixDictionary<ContentType>>,
}

impl LanguageContentBuilder {
    /// Creates a new STIX 2.1 `LanguageContentBuilder` with a given `object_ref`
    ///
    /// The `object_ref` field must be a valid Stix id
    ///
    /// Automatically generates an `id`
    /// The `contents` field is created as an empty dictionary, whose entries must be added prior to the final build
    /// Other fields are set to their Default (which is `None`` for optional fields)
    pub fn new(object_ref: &str) -> Result<Self, Error> {
        // Parses the provided `object_ref` as a STIX id
        let object_ref_id = Identifier::from_str(object_ref)?;

        // Build the common properties with generated and default values
        let common_properties =
            CommonPropertiesBuilder::new("language-content", "language-content")?;

        Ok(Self {
            common_properties,
            object_ref: object_ref_id,
            object_modified: None,
            contents: StixDictionary::new(),
        })
    }

    /// Create a new STIX 2.1 `LanguageContentBuilder` by cloning the fields from an existing `LanguageContent`
    /// When built, this will create `LanguageContent` as a newer version of the original object.
    pub fn version(old: &LanguageContent) -> Result<Self, Error> {
        if old.is_revoked() {
            return Err(Error::UnableToVersion(format!(
                "LanguageContent SMO {} is revoked. Versioning a revoked object is prohibited.",
                old.common_properties.id
            )));
        }

        let object_ref = old.object_ref.clone();
        let object_modified = old.object_modified.clone();
        let contents = old.contents.clone();

        let old_properties = old.common_properties.clone();
        let common_properties =
            CommonPropertiesBuilder::version("language-content", &old_properties)?;

        Ok(Self {
            common_properties,
            object_ref,
            object_modified,
            contents,
        })
    }

    /// Create a builder from an already-parsed LanguageContent, preserving its
    /// `id`, `created`, `modified`, and `revoked` properties exactly. Unlike
    /// `version()`, this does not treat the object as the basis for a new version.
    pub fn from_parsed(old: &LanguageContent) -> Result<Self, Error> {
        let object_ref = old.object_ref.clone();
        let object_modified = old.object_modified.clone();
        let contents = old.contents.clone();

        let old_properties = old.common_properties.clone();
        let common_properties =
            CommonPropertiesBuilder::from_existing("language-content", &old_properties)?;

        Ok(Self {
            common_properties,
            object_ref,
            object_modified,
            contents,
        })
    }

    // Setter functions for common properties

    /// Set the `created_by_ref` field for a Language Content SMO under construction
    /// This is only allowed when creating a new Language Content SMO, not when versioning an existing one,
    /// as only the original creator of an object can version it.
    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)
    }

    /// Set the optional `labels` field for an Language Content SMO under construction
    pub fn labels(mut self, labels: Vec<String>) -> Self {
        self.common_properties = self.common_properties.clone().labels(labels);
        self
    }

    /// Set the optional `confidence` field for an Language Content SMO under construction
    pub fn confidence(mut self, confidence: u8) -> Self {
        self.common_properties = self.common_properties.clone().confidence(confidence);
        self
    }

    /// Set the optional `external_references` field for an Language Content SMO under construction
    pub fn external_references(mut self, references: Vec<ExternalReference>) -> Self {
        self.common_properties = self
            .common_properties
            .clone()
            .external_references(references);
        self
    }

    /// Set the optional `object_marking_refs` field for an Language Content SMO under construction
    pub fn object_marking_refs(mut self, references: Vec<Identifier>) -> Self {
        self.common_properties = self
            .common_properties
            .clone()
            .object_marking_refs(references);
        self
    }

    /// Set the optional `granular_markings` field for a Language Content SMO under construction.
    pub fn granular_markings(mut self, markings: Vec<GranularMarking>) -> Self {
        self.common_properties = self.common_properties.clone().granular_markings(markings);
        self
    }

    /// Add an optional extension to the `extensions` field for a Language Content SMO under construction, creating the field if it does not exist
    pub fn add_extension(
        mut self,
        key: &str,
        extension: StixDictionary<DictionaryValue>,
    ) -> Result<Self, Error> {
        self.common_properties = self
            .common_properties
            .clone()
            .add_extension(key, extension)?;
        Ok(self)
    }

    // Setter functions for Language Content specific properties

    /// Setter function for the optional `object_modified` property
    pub fn object_modified(mut self, object_modified: &str) -> Result<Self, Error> {
        self.object_modified = Some(Timestamp(
            object_modified.parse().map_err(Error::DateTimeError)?,
        ));
        Ok(self)
    }

    /// Add an element to the content dictionary
    pub fn insert_content(
        mut self,
        lang: &str,
        content: StixDictionary<ContentType>,
    ) -> Result<Self, Error> {
        self.contents.insert(lang, content)?;
        Ok(self)
    }

    /// Add an element to the content dictionary with simple String values
    pub fn insert_content_strings(
        mut self,
        lang: &str,
        content: HashMap<String, String>,
    ) -> Result<Self, Error> {
        let mut dict = StixDictionary::new();
        for (key, value) in content {
            dict.insert(&key, ContentType::String(value))?;
        }
        self.contents.insert(lang, dict)?;
        Ok(self)
    }

    /// Add an element to the content dictionary with List of String values
    pub fn insert_content_lists(
        mut self,
        lang: &str,
        content: HashMap<String, Vec<String>>,
    ) -> Result<Self, Error> {
        let mut dict = StixDictionary::new();
        for (key, value) in content {
            dict.insert(&key, ContentType::List(value))?;
        }
        self.contents.insert(lang, dict)?;
        Ok(self)
    }

    /// Add an element to the content dictionary with nested LanguageContent Object values
    pub fn insert_content_objects(
        mut self,
        lang: &str,
        content: HashMap<String, HashMap<String, Value>>,
    ) -> Result<Self, Error> {
        let object_ref = self.object_ref.to_string();
        let mut dict = StixDictionary::new();
        for (key, value_map) in content.iter() {
            let mut nested_dict = StixDictionary::new();
            for (prop_key, prop_value) in value_map.iter() {
                let content_type = match prop_value {
                    Value::String(s) => ContentType::String(s.clone()),
                    Value::Array(arr) => {
                        let mut vec = Vec::new();
                        for item in arr {
                            if let Value::String(s) = item {
                                vec.push(s.clone());
                            } else {
                                vec.push("".to_string());
                            }
                        }
                        ContentType::List(vec)
                    }
                    Value::Object(map) => {
                        let mut inner_map = HashMap::new();
                        for (k, v) in map.iter() {
                            if let Value::String(s) = v {
                                inner_map.insert(k.clone(), s.clone());
                            } else {
                                inner_map.insert(k.clone(), "".to_string());
                            }
                        }
                        ContentType::Object(Box::new(
                            LanguageContentBuilder::new(&format!(
                                "{}--{}--{}",
                                object_ref,
                                key,
                                Uuid::new_v4()
                            ))?
                            .object_modified("2017-02-08T21:31:22.007Z")?
                            .insert_content_strings(lang, inner_map)?
                            .build()?,
                        ))
                    }
                    _ => ContentType::String("".to_string()),
                };
                nested_dict.insert(prop_key, content_type)?;
            }
            let nested_lc = LanguageContentBuilder::new(&format!(
                "{}--{}--{}",
                object_ref,
                key,
                Uuid::new_v4()
            ))?
            .object_modified("2017-02-08T21:31:22.007Z")?
            .insert_content(lang, nested_dict)?
            .build()?;
            dict.insert(key.as_str(), ContentType::Object(Box::new(nested_lc)))?;
        }
        self.contents.insert(lang, dict)?;
        Ok(self)
    }

    /// Set custom properties for the language content SMO under construction.
    pub fn custom_properties(mut self, custom_properties: BTreeMap<String, Value>) -> Self {
        self.common_properties = self
            .common_properties
            .clone()
            .custom_properties(custom_properties);
        self
    }

    /// Builds a new Language Content SMO without running `stix_check()`
    /// validation.
    ///
    /// This assembles the final `LanguageContent` object from the builder, but
    /// skips the object-specific `stix_check()`. It is intended for callers that
    /// have already validated the object and only need its typed representation
    /// (e.g. serialization).
    pub fn build_no_validate(self) -> Result<LanguageContent, Error> {
        let common_properties = self.common_properties.build();

        let object_ref = self.object_ref;
        let object_modified = self.object_modified;
        let contents = self.contents;

        let language_content = LanguageContent {
            object_type: "language-content".to_string(),
            common_properties,
            object_ref,
            object_modified,
            contents,
        };

        Ok(language_content)
    }

    /// Builds a new Language Content SMO, using the information found in the
    /// `LanguageContentBuilder`.
    ///
    /// This assembles the final `LanguageContent` object from the builder and
    /// then runs `stix_check()` on it.
    pub fn build(self) -> Result<LanguageContent, Error> {
        let language_content = self.build_no_validate()?;
        language_content.stix_check()?;
        Ok(language_content)
    }
}