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
//! Value-based collect-all validation for STIX objects.
//!
//! This module provides the central deserialization gate used by every typed
//! `from_json` path. It operates on a single [`serde_json::Value`] (the JSON is
//! parsed once at the top level) and tries to surface as many independent errors
//! as possible instead of stopping at the first serde failure.
//!
//! The flow is:
//!
//! 1. Structural checks from the property registry:
//!    - unknown properties (unless `allow_custom` is true)
//!    - missing required properties
//! 2. Typed deserialization; `serde_path_to_error` turns data errors into
//!    structured [`StixError::MissingProperty`] / [`StixError::InvalidPropertyType`].
//! 3. Object-specific `stix_check` logic when `strict` is true.

use serde::de::DeserializeOwned;
use serde_json::Value;
use serde_path_to_error as serde_path;

use crate::{
    base::{validate_custom_property_name, CustomPropertiesHolder, Stix},
    error::{add_error, classify_serde_error, return_multiple_errors, StixError as Error},
    properties::type_properties,
};

/// Validates a STIX object from a JSON value and returns the typed struct.
///
/// - `allow_custom: false` rejects unknown properties against the registry.
/// - `allow_custom: true` permits unknown properties, strips them out into the
///   object's [`CommonProperties::custom_properties`][crate::base::CommonProperties::custom_properties]
///   bag, and validates their names against the STIX 2.1 custom-property rules.
/// - `strict: true` adds required-property checks and runs the object-specific
///   `stix_check`. `strict: false` just deserializes and optionally checks unknown
///   properties.
///
/// Multiple independent errors are returned as a single
/// [`StixError::ValidationErrors`].
pub fn validate_value<T: DeserializeOwned + Stix + CustomPropertiesHolder>(
    value: Value,
    allow_custom: bool,
    strict: bool,
) -> Result<T, Error> {
    validate_value_from_object(value, allow_custom, strict)
}

/// Validates a STIX object from its raw object [`Value`] without re-serializing.
///
/// This is the optimized implementation. The API-compatible [`validate_value`]
/// wrapper delegates here.
pub fn validate_value_from_object<T: DeserializeOwned + Stix + CustomPropertiesHolder>(
    mut value: Value,
    allow_custom: bool,
    strict: bool,
) -> Result<T, Error> {
    let type_name = value
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_string();
    let props = type_properties(&type_name);
    let mut errors: Vec<Error> = Vec::new();

    let mut custom_properties: Option<std::collections::BTreeMap<String, Value>> = None;

    if let Some(props) = props {
        if let Some(map) = value.as_object() {
            let keys: std::collections::HashSet<&str> = map.keys().map(|s| s.as_str()).collect();
            let known: std::collections::HashSet<&str> = props.known.iter().copied().collect();

            let unknown: Vec<&str> = keys.difference(&known).copied().collect();

            if !unknown.is_empty() {
                if !allow_custom {
                    errors.push(Error::UnknownProperties {
                        object_type: type_name.to_string(),
                        fields: unknown.into_iter().map(|k| k.to_string()).collect(),
                    });
                } else {
                    // Validate custom property names immediately, regardless of `strict`.
                    for key in &unknown {
                        add_error(&mut errors, validate_custom_property_name(key));
                    }

                    if errors.is_empty() {
                        let mut bag = std::collections::BTreeMap::new();
                        for key in unknown {
                            if let Some(val) = map.get(key) {
                                bag.insert(key.to_string(), val.clone());
                            }
                        }
                        if !bag.is_empty() {
                            custom_properties = Some(bag);
                        }
                    }
                }
            }

            for req in props.required.iter() {
                if !keys.contains(*req) {
                    errors.push(Error::MissingProperty {
                        object_type: type_name.to_string(),
                        property: req.to_string(),
                    });
                }
            }
        }
    }

    // If we found custom properties, strip them from the value before passing it
    // to serde so the flattened `custom_properties` field cannot accidentally
    // capture known keys.
    if let Some(bag) = custom_properties.as_ref() {
        if let Some(map) = value.as_object_mut() {
            for key in bag.keys() {
                map.remove(key);
            }
        }
    }

    let mut typed: T = match serde_path::deserialize(value) {
        Ok(t) => t,
        Err(e) => {
            let classified = classify_serde_error(e, &type_name);
            // Avoid reporting a missing field that the registry already listed.
            if let Error::MissingProperty { property, .. } = &classified {
                if errors.iter().any(|err| {
                    matches!(
                        err,
                        Error::MissingProperty {
                            property: p,
                            ..
                        } if p == property
                    )
                }) {
                    return Err(return_multiple_errors(errors).unwrap_err());
                }
            }
            errors.push(classified);
            return Err(return_multiple_errors(errors).unwrap_err());
        }
    };

    // Attach the custom-property bag explicitly, overriding the serde-default None.
    typed.set_custom_properties(custom_properties);

    if strict {
        add_error(&mut errors, typed.stix_check());
    }

    return_multiple_errors(errors)?;
    Ok(typed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain_objects::sdo::DomainObject;
    use std::collections::BTreeMap;

    #[test]
    fn valid_sdo_deserializes() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing"
        });
        assert!(validate_value::<DomainObject>(value, false, true).is_ok());
    }

    #[test]
    fn unknown_property_rejected_when_allow_custom_false() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "junk": "value"
        });
        let err = validate_value::<DomainObject>(value, false, true).unwrap_err();
        assert!(
            matches!(err, Error::UnknownProperties { .. }),
            "expected UnknownProperties, got {err:?}"
        );
    }

    #[test]
    fn unknown_property_allowed_when_allow_custom_true() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "junk": "value"
        });
        assert!(validate_value::<DomainObject>(value, true, true).is_ok());
    }

    #[test]
    fn multiple_validation_errors_collected() {
        // Both errors are independent: the object deserializes fine, but
        // `spec_version` is wrong per `stix_check` and `junk` is unknown.
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "3.0",
            "name": "Spear Phishing",
            "junk": "value"
        });
        let err = validate_value::<DomainObject>(value, false, true).unwrap_err();
        match err {
            Error::ValidationErrors(errors) => {
                assert!(
                    errors
                        .iter()
                        .any(|e| matches!(e, Error::UnknownProperties { .. })),
                    "missing unknown property error"
                );
                assert!(
                    errors
                        .iter()
                        .any(|e| matches!(e, Error::ValidationError(_))),
                    "missing validation error"
                );
            }
            other => panic!("expected ValidationErrors, got {other:?}"),
        }
    }

    #[test]
    fn missing_required_property_reported() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1"
        });
        let err = validate_value::<DomainObject>(value, false, true).unwrap_err();
        assert!(
            matches!(err, Error::MissingProperty { ref property, .. } if property == "name"),
            "expected MissingProperty name, got {err:?}"
        );
    }

    #[test]
    fn invalid_top_level_type_reported_as_deserialization_error() {
        // Top-level properties are flattened into the object structs, so
        // `serde_path_to_error` cannot report the property name for an invalid
        // type at the root. The error should still be surfaced, not lost.
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": 2.1,
            "name": "Spear Phishing"
        });
        let err = validate_value::<DomainObject>(value, false, true).unwrap_err();
        assert!(
            matches!(err, Error::DeserializationError(_)),
            "expected DeserializationError, got {err:?}"
        );
    }

    #[test]
    fn non_strict_skips_validation() {
        // missing required `name`, invalid timestamp, unknown property
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "junk": "value"
        });
        // Non-strict still fails because the required `name` field cannot be deserialized.
        assert!(validate_value::<DomainObject>(value.clone(), true, false).is_err());
        // When allow_custom is true the unknown field is ignored; but `name` is still required.
        let err = validate_value::<DomainObject>(value, true, false).unwrap_err();
        assert!(
            !matches!(err, Error::UnknownProperties { .. }),
            "unknown property should not be reported in non-strict mode: {err:?}"
        );
    }

    #[test]
    fn allow_custom_true_preserves_custom_property() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_vendor_severity": 5
        });
        let obj = validate_value::<DomainObject>(value, true, true).unwrap();
        assert_eq!(
            obj.common_properties.custom_properties,
            Some(BTreeMap::from([(
                "x_vendor_severity".to_string(),
                serde_json::json!(5)
            )]))
        );

        let json = serde_json::to_string(&obj).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["x_vendor_severity"], 5);
    }

    #[test]
    fn allow_custom_false_rejects_custom_property() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_vendor_severity": 5
        });
        let err = validate_value::<DomainObject>(value, false, true).unwrap_err();
        assert!(
            matches!(err, Error::UnknownProperties { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn custom_property_name_may_start_with_digit() {
        let value = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "1digit_custom": "allowed"
        });
        let obj = validate_value::<DomainObject>(value, true, true).unwrap();
        assert!(obj
            .common_properties
            .custom_properties
            .as_ref()
            .unwrap()
            .contains_key("1digit_custom"));
    }

    #[test]
    fn invalid_custom_property_name_is_rejected() {
        let cases = [
            ("bad-key", "characters outside the allowed set"),
            ("AB", "too short"),
            ("severity", "reserved"),
        ];
        for (key, _msg) in cases {
            let value = serde_json::json!({
                "type": "attack-pattern",
                "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
                "created": "2016-05-12T08:17:27Z",
                "modified": "2016-05-12T08:17:27Z",
                "spec_version": "2.1",
                "name": "Spear Phishing",
                key: "value"
            });
            let err = validate_value::<DomainObject>(value, true, true).unwrap_err();
            assert!(
                matches!(err, Error::ValidationError(_) | Error::ValidationErrors(_)),
                "{key}: expected ValidationError, got {err:?}"
            );
        }
    }

    #[test]
    fn custom_property_suffix_value_validation() {
        let valid_hex = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_bytes_hex": "deadbeef"
        });
        assert!(validate_value::<DomainObject>(valid_hex, true, true).is_ok());

        let invalid_hex_odd = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_bytes_hex": "deadbee"
        });
        assert!(validate_value::<DomainObject>(invalid_hex_odd, true, true).is_err());

        let invalid_hex_upper = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_bytes_hex": "DEADBEEF"
        });
        assert!(validate_value::<DomainObject>(invalid_hex_upper, true, true).is_err());

        let valid_bin = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_payload_bin": "aGVsbG8gd29ybGQ="
        });
        assert!(validate_value::<DomainObject>(valid_bin, true, true).is_ok());

        let invalid_bin = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_payload_bin": "not-valid-base64!!!"
        });
        assert!(validate_value::<DomainObject>(invalid_bin, true, true).is_err());

        // Non-string values with a _hex suffix are rejected.
        let non_string_hex = serde_json::json!({
            "type": "attack-pattern",
            "id": "attack-pattern--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "name": "Spear Phishing",
            "x_bytes_hex": 12345
        });
        assert!(validate_value::<DomainObject>(non_string_hex, true, true).is_err());
    }

    #[test]
    fn custom_object_custom_property_validation() {
        use crate::custom_objects::CustomObject;

        let valid = serde_json::json!({
            "type": "x-custom",
            "id": "x-custom--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "extensions": {
                "extension-definition--12345678-1234-5678-1234-567812345678": {
                    "extension_type": "new-sdo"
                }
            },
            "x_bytes_hex": "deadbeef"
        });
        assert!(validate_value::<CustomObject>(valid, true, true).is_ok());

        let invalid = serde_json::json!({
            "type": "x-custom",
            "id": "x-custom--12345678-1234-5678-1234-567812345678",
            "created": "2016-05-12T08:17:27Z",
            "modified": "2016-05-12T08:17:27Z",
            "spec_version": "2.1",
            "extensions": {
                "extension-definition--12345678-1234-5678-1234-567812345678": {
                    "extension_type": "new-sdo"
                }
            },
            "x_bytes_hex": "not-hex"
        });
        assert!(validate_value::<CustomObject>(invalid, true, true).is_err());
    }
}