csaf-models 0.3.0

CSAF 2.0/2.1 data models, SQLite management, and user models
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Application settings model.

use serde::{Deserialize, Serialize};

/// Application settings stored in redb.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct Settings {
    /// CSAF mode: `"2.0"` or `"2.1"`.
    #[serde(default = "default_csaf_mode")]
    pub csaf_mode: String,

    /// UI theme: `"light"` or `"dark"`.
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Directory to scan for CSAF imports.
    #[serde(default = "default_import_directory")]
    pub import_directory: String,

    /// Directory to export CSAF files to.
    #[serde(default = "default_export_directory")]
    pub export_directory: String,

    /// Directory to write full database dumps + hash sidecars to.
    #[serde(default = "default_dump_directory")]
    pub dump_directory: String,

    /// Directory to write rolling application log files + sidecars to.
    #[serde(default = "default_log_directory")]
    pub log_directory: String,

    /// Whether to generate SHA-256 sidecar files (extension `.sha-256`).
    #[serde(default = "default_true")]
    pub sidecar_sha256: bool,

    /// Whether to generate SHA-512 (SHA-2 family) sidecar files
    /// (extension `.sha-512`).
    #[serde(default = "default_true")]
    pub sidecar_sha512: bool,

    /// Whether to generate SHA3-512 sidecar files (extension `.sha3-512`).
    #[serde(default = "default_true")]
    pub sidecar_sha3_512: bool,

    /// Naming convention prefix for CSAF files.
    #[serde(default = "default_naming_convention")]
    pub naming_convention: String,

    // -----------------------------------------------------------------------
    // Publisher defaults used when creating new CSAF documents.
    // -----------------------------------------------------------------------
    /// Default publisher name injected into new CSAF documents.
    #[serde(default = "default_publisher_name")]
    pub publisher_name: String,

    /// Default publisher namespace URI.
    #[serde(default = "default_publisher_namespace")]
    pub publisher_namespace: String,

    /// Default publisher category (`vendor`, `discoverer`, `coordinator`,
    /// `user`, `translator`, `other`).
    #[serde(default = "default_publisher_category")]
    pub publisher_category: String,

    /// Default publisher contact details (email or URL).
    #[serde(default = "default_publisher_contact")]
    pub publisher_contact_details: String,

    // -----------------------------------------------------------------------
    // Classification defaults -- TLP 2.0, German Verschlusssache, NATO.
    //
    // These drive the colored TLP dropdown and the Verschlusssache/NATO
    // selects on the CSAF create/edit form.
    // -----------------------------------------------------------------------
    /// Default TLP 2.0 label (one of [`TLP_LABELS`]).
    #[serde(default = "default_tlp")]
    pub tlp_default: String,

    /// Whether the Verschlusssache (German national classification) field
    /// is exposed on the CSAF form.
    #[serde(default = "default_true")]
    pub verschlusssache_enabled: bool,

    /// Default Verschlusssache label (one of [`VERSCHLUSSSACHE_LABELS`]).
    #[serde(default = "default_verschlusssache")]
    pub verschlusssache_default: String,

    /// Whether the NATO classification field is exposed on the CSAF form.
    #[serde(default = "default_true")]
    pub nato_enabled: bool,

    /// Default NATO classification label (one of [`NATO_LABELS`]).
    #[serde(default = "default_nato")]
    pub nato_default: String,

    /// Where to write Verschlusssache / NATO values in the exported CSAF
    /// document. One of [`CLASSIFICATION_STORAGE_MODES`]:
    /// `"distribution_text"`, `"notes"`, or `"both"`.
    #[serde(default = "default_classification_storage_mode")]
    pub classification_storage_mode: String,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            csaf_mode: default_csaf_mode(),
            theme: default_theme(),
            import_directory: default_import_directory(),
            export_directory: default_export_directory(),
            dump_directory: default_dump_directory(),
            log_directory: default_log_directory(),
            sidecar_sha256: true,
            sidecar_sha512: true,
            sidecar_sha3_512: true,
            naming_convention: default_naming_convention(),
            publisher_name: default_publisher_name(),
            publisher_namespace: default_publisher_namespace(),
            publisher_category: default_publisher_category(),
            publisher_contact_details: default_publisher_contact(),
            tlp_default: default_tlp(),
            verschlusssache_enabled: true,
            verschlusssache_default: default_verschlusssache(),
            nato_enabled: true,
            nato_default: default_nato(),
            classification_storage_mode: default_classification_storage_mode(),
        }
    }
}

/// Allowed values for the publisher category dropdown.
pub const PUBLISHER_CATEGORIES: &[&str] = &[
    "vendor",
    "discoverer",
    "coordinator",
    "user",
    "translator",
    "other",
];

/// Check whether a candidate string is an allowed publisher category.
#[must_use]
pub fn is_valid_publisher_category(value: &str) -> bool {
    PUBLISHER_CATEGORIES.contains(&value)
}

/// Allowed TLP 2.0 labels (`https://www.first.org/tlp/`).
pub const TLP_LABELS: &[&str] = &["CLEAR", "GREEN", "AMBER", "AMBER+STRICT", "RED"];

/// Allowed Verschlusssache (German national classification) labels
/// according to <https://de.wikipedia.org/wiki/Verschlusssache#Einstufung>.
pub const VERSCHLUSSSACHE_LABELS: &[&str] = &[
    "VS-NfD (VS-NUR FÜR DEN DIENSTGEBRAUCH)",
    "VS-Vertr. (VS-VERTRAULICH)",
    "Geh. (GEHEIM)",
    "Str. Geh. (STRENG GEHEIM)",
];

/// Allowed NATO classification labels according to
/// <https://de.wikipedia.org/wiki/Geheimhaltungsgrad#NATO>.
pub const NATO_LABELS: &[&str] = &[
    "NR (NATO RESTRICTED)",
    "NC (NATO CONFIDENTIAL)",
    "NS (NATO SECRET)",
    "CTS (COSMIC TOP SECRET)",
];

/// Where to write Verschlusssache / NATO values in the exported CSAF JSON.
///
/// - `"distribution_text"`: append to `document.distribution.text` as
///   `"Verschlusssache: <value> | NATO: <value>"`.
/// - `"notes"`: add one `document.notes[]` entry per field with the
///   well-known titles `"Verschlusssache"` and `"NATO Classification"`.
/// - `"both"`: write to both locations so any CSAF consumer can find it.
pub const CLASSIFICATION_STORAGE_MODES: &[&str] = &["distribution_text", "notes", "both"];

/// Check whether a candidate string is an allowed TLP 2.0 label.
#[must_use]
pub fn is_valid_tlp(value: &str) -> bool {
    TLP_LABELS.contains(&value)
}

/// Check whether a candidate string is an allowed Verschlusssache label.
#[must_use]
pub fn is_valid_verschlusssache(value: &str) -> bool {
    VERSCHLUSSSACHE_LABELS.contains(&value)
}

/// Check whether a candidate string is an allowed NATO classification
/// label.
#[must_use]
pub fn is_valid_nato(value: &str) -> bool {
    NATO_LABELS.contains(&value)
}

/// Check whether a candidate string is an allowed classification storage
/// mode.
#[must_use]
pub fn is_valid_classification_storage_mode(value: &str) -> bool {
    CLASSIFICATION_STORAGE_MODES.contains(&value)
}

/// Maximum accepted length (bytes) of a user-supplied storage path.
pub const STORAGE_PATH_MAX_LEN: usize = 4096;

/// Check whether a candidate string is an acceptable
/// filesystem-path setting (`import_directory`, `export_directory`,
/// `dump_directory`).
///
/// Rejects:
/// - empty / whitespace-only strings,
/// - strings longer than [`STORAGE_PATH_MAX_LEN`] bytes,
/// - strings containing a NUL byte (`\0`),
/// - strings containing a `..` path component (path-traversal guard),
/// - strings that start with `~` (no shell-style home expansion).
///
/// The check is purely syntactic — it does not touch the filesystem.
#[must_use]
pub fn is_valid_storage_path(value: &str) -> bool {
    let trimmed = value.trim();
    if trimmed.is_empty() || trimmed.len() > STORAGE_PATH_MAX_LEN {
        return false;
    }
    if trimmed.contains('\0') {
        return false;
    }
    if trimmed.starts_with('~') {
        return false;
    }
    // Reject any `..` segment, anywhere. Uses Path to avoid missing
    // encodings like `a/..` vs `..\\b` on different platforms.
    for component in std::path::Path::new(trimmed).components() {
        if matches!(component, std::path::Component::ParentDir) {
            return false;
        }
    }
    true
}

fn default_csaf_mode() -> String {
    "2.1".to_owned()
}

fn default_theme() -> String {
    "light".to_owned()
}

fn default_import_directory() -> String {
    "./data_import".to_owned()
}

fn default_export_directory() -> String {
    "./data_export".to_owned()
}

fn default_dump_directory() -> String {
    "./data_dump".to_owned()
}

fn default_log_directory() -> String {
    "./data_log".to_owned()
}

fn default_naming_convention() -> String {
    "ndaal-sa-".to_owned()
}

fn default_publisher_name() -> String {
    "ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH & Co KG".to_owned()
}

fn default_publisher_namespace() -> String {
    "https://ndaal.eu/csaf".to_owned()
}

fn default_publisher_category() -> String {
    "vendor".to_owned()
}

fn default_publisher_contact() -> String {
    "security@ndaal.eu".to_owned()
}

fn default_tlp() -> String {
    "AMBER".to_owned()
}

fn default_verschlusssache() -> String {
    "VS-NfD (VS-NUR FÜR DEN DIENSTGEBRAUCH)".to_owned()
}

fn default_nato() -> String {
    "NR (NATO RESTRICTED)".to_owned()
}

fn default_classification_storage_mode() -> String {
    "both".to_owned()
}

const fn default_true() -> bool {
    true
}

#[cfg(test)]
// Dense assertion blocks are acceptable in tests — clippy's
// cognitive-complexity threshold is tuned for production code paths.
#[allow(clippy::cognitive_complexity)]
mod tests {
    use super::*;

    #[test]
    fn test_default_settings() {
        let settings = Settings::default();
        assert_eq!(settings.csaf_mode, "2.1");
        assert_eq!(settings.theme, "light");
        assert!(settings.sidecar_sha256);
        assert!(settings.sidecar_sha512);
        assert!(settings.sidecar_sha3_512);
        assert_eq!(settings.naming_convention, "ndaal-sa-");
        assert_eq!(settings.import_directory, "./data_import");
        assert_eq!(settings.export_directory, "./data_export");
        assert_eq!(settings.dump_directory, "./data_dump");
        assert_eq!(settings.log_directory, "./data_log");
        assert_eq!(
            settings.publisher_name,
            "ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH & Co KG"
        );
        assert_eq!(settings.publisher_namespace, "https://ndaal.eu/csaf");
        assert_eq!(settings.publisher_category, "vendor");
        assert_eq!(settings.publisher_contact_details, "security@ndaal.eu");
        assert_eq!(settings.tlp_default, "AMBER");
        assert!(settings.verschlusssache_enabled);
        assert_eq!(
            settings.verschlusssache_default,
            "VS-NfD (VS-NUR FÜR DEN DIENSTGEBRAUCH)"
        );
        assert!(settings.nato_enabled);
        assert_eq!(settings.nato_default, "NR (NATO RESTRICTED)");
        assert_eq!(settings.classification_storage_mode, "both");
    }

    #[test]
    fn test_settings_roundtrip() {
        let settings = Settings::default();
        let json = serde_json::to_string(&settings).expect("serialize failed");
        let parsed: Settings = serde_json::from_str(&json).expect("deserialize failed");
        assert_eq!(settings, parsed);
    }

    #[test]
    fn test_partial_deserialization() {
        let json = r#"{"csaf_mode": "2.0", "theme": "dark"}"#;
        let settings: Settings = serde_json::from_str(json).expect("deserialize failed");
        assert_eq!(settings.csaf_mode, "2.0");
        assert_eq!(settings.theme, "dark");
        // Defaults applied for missing fields, including the publisher defaults.
        assert_eq!(settings.dump_directory, "./data_dump");
        assert_eq!(settings.log_directory, "./data_log");
        assert!(settings.sidecar_sha256);
        assert!(settings.sidecar_sha512);
        assert_eq!(settings.naming_convention, "ndaal-sa-");
        assert_eq!(settings.publisher_category, "vendor");
        assert_eq!(settings.publisher_namespace, "https://ndaal.eu/csaf");
    }

    #[test]
    fn test_publisher_category_whitelist() {
        for cat in PUBLISHER_CATEGORIES {
            assert!(is_valid_publisher_category(cat), "{cat} should be valid");
        }
        assert!(!is_valid_publisher_category("VENDOR"));
        assert!(!is_valid_publisher_category("bogus"));
        assert!(!is_valid_publisher_category(""));
    }

    #[test]
    fn test_tlp_whitelist() {
        for label in TLP_LABELS {
            assert!(is_valid_tlp(label), "{label} should be a valid TLP label");
        }
        assert!(!is_valid_tlp(""));
        assert!(!is_valid_tlp("clear"));
        assert!(!is_valid_tlp("AMBER "));
        assert!(!is_valid_tlp("WHITE"));
    }

    #[test]
    fn test_verschlusssache_whitelist() {
        for label in VERSCHLUSSSACHE_LABELS {
            assert!(is_valid_verschlusssache(label));
        }
        assert!(!is_valid_verschlusssache(""));
        assert!(!is_valid_verschlusssache("VS-NfD"));
        assert!(!is_valid_verschlusssache("VS-NUR FÜR DEN DIENSTGEBRAUCH"));
    }

    #[test]
    fn test_nato_whitelist() {
        for label in NATO_LABELS {
            assert!(is_valid_nato(label));
        }
        assert!(!is_valid_nato(""));
        assert!(!is_valid_nato("NR"));
        assert!(!is_valid_nato("nr (nato restricted)"));
    }

    #[test]
    fn test_is_valid_storage_path_accepts() {
        for good in [
            "./data_dump",
            "./data_import",
            "/var/lib/csaf",
            "data/dump",
            "C:/dev/csaf/dump",
        ] {
            assert!(is_valid_storage_path(good), "{good} should be accepted");
        }
    }

    #[test]
    fn test_is_valid_storage_path_rejects() {
        for bad in [
            "",
            "   ",
            "\t",
            "~/dumps",
            "~\\dumps",
            "../etc/passwd",
            "./../a",
            "foo/../bar",
            "a\0b",
        ] {
            assert!(!is_valid_storage_path(bad), "{bad:?} should be rejected");
        }
    }

    #[test]
    fn test_is_valid_storage_path_max_length() {
        let huge = "a".repeat(STORAGE_PATH_MAX_LEN + 1);
        assert!(!is_valid_storage_path(&huge));
        let ok = "a".repeat(STORAGE_PATH_MAX_LEN);
        assert!(is_valid_storage_path(&ok));
    }

    #[test]
    fn test_classification_storage_mode_whitelist() {
        for mode in CLASSIFICATION_STORAGE_MODES {
            assert!(is_valid_classification_storage_mode(mode));
        }
        assert!(!is_valid_classification_storage_mode(""));
        assert!(!is_valid_classification_storage_mode("BOTH"));
        assert!(!is_valid_classification_storage_mode("distribution"));
        assert!(!is_valid_classification_storage_mode("note"));
    }

    #[test]
    fn test_cartesian_combinations_roundtrip() {
        // Every (TLP, VS, NATO, mode) quadruple must round-trip through
        // JSON without drift.
        for tlp in TLP_LABELS {
            for vs in VERSCHLUSSSACHE_LABELS {
                for nato in NATO_LABELS {
                    for mode in CLASSIFICATION_STORAGE_MODES {
                        let settings = Settings {
                            tlp_default: (*tlp).to_owned(),
                            verschlusssache_default: (*vs).to_owned(),
                            nato_default: (*nato).to_owned(),
                            classification_storage_mode: (*mode).to_owned(),
                            ..Settings::default()
                        };
                        let json = serde_json::to_string(&settings).expect("serialize failed");
                        let parsed: Settings =
                            serde_json::from_str(&json).expect("deserialize failed");
                        assert_eq!(settings, parsed);
                    }
                }
            }
        }
    }

    #[test]
    fn test_old_settings_json_still_loads() {
        // JSON written by a previous version without the publisher fields
        // must still deserialise successfully via the `default` helpers.
        let json = r#"{
            "csaf_mode": "2.1",
            "theme": "dark",
            "import_directory": "./data_import",
            "export_directory": "./data_export",
            "sidecar_sha256": true,
            "sidecar_sha3_512": true,
            "naming_convention": "ndaal-sa-"
        }"#;
        let settings: Settings = serde_json::from_str(json).expect("deserialize failed");
        assert_eq!(settings.publisher_category, "vendor");
        assert_eq!(settings.publisher_contact_details, "security@ndaal.eu");
        // Dump directory must also receive its serde default.
        assert_eq!(settings.dump_directory, "./data_dump");
        // Log directory + sha512 toggle (0.3.0 additions) also default.
        assert_eq!(settings.log_directory, "./data_log");
        assert!(settings.sidecar_sha512);
        // Classification fields must also get their defaults from the
        // serde(default) helpers.
        assert_eq!(settings.tlp_default, "AMBER");
        assert!(settings.verschlusssache_enabled);
        assert_eq!(
            settings.verschlusssache_default,
            "VS-NfD (VS-NUR FÜR DEN DIENSTGEBRAUCH)"
        );
        assert!(settings.nato_enabled);
        assert_eq!(settings.nato_default, "NR (NATO RESTRICTED)");
        assert_eq!(settings.classification_storage_mode, "both");
    }
}