csaf-core 0.3.4

CSAF storage, validation, sidecar generation, import/export
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Exhaustive path-traversal regression suite for
//! `csaf_core::path_security::safe_join`.
//!
//! The vectors below are drawn from four sources, each tagged in
//! the test name so a regression points at the original threat
//! corpus.
//!
//! - `cs_*` — adapted from cap-std's upstream test files
//!   (`bytecodealliance/cap-std`): `tests/symlinks.rs`,
//!   `tests/paths-containing-nul.rs`, `tests/canonicalize.rs`,
//!   `tests/fs.rs`, `tests/fs_additional.rs`, `tests/root.rs`.
//!   These exercise the same threat model (capability boundary
//!   escape) at the string layer while the cap-std migration is
//!   in progress.
//! - `owasp_*` — OWASP "Path Traversal" cheat sheet (CWE-22):
//!   `https://owasp.org/www-community/attacks/Path_Traversal`.
//!   Covers absolute-path injection, encoded `../`, double-encoded
//!   variants, NULL-byte truncation (CVE-2007-0883 class), and
//!   the Windows / UNC shapes that frequently slip past naive
//!   `starts_with` checks.
//! - `csaf_*` — the actual attacker-controllable string fields
//!   in our CSAF / OSV / RSS feeders (`tracking_id`, advisory
//!   `path` from `changes.csv`, Atom entry `<id>` URI fragments).
//!   These vectors come from manually crafted malformed advisories
//!   used during feeder hardening and from corpus minimisation of
//!   the existing `fuzz_advisory_path_traversal` target.
//! - `unicode_*` — Unicode normalisation cases (NFC vs NFD, visual
//!   lookalikes, RTL override, fullwidth Latin) that have produced
//!   sandbox escapes in other projects (Node.js path-traversal
//!   advisories, Apache Tomcat's CVE-2014-0050 family).
//!
//! Every vector either MUST be accepted with the result staying
//! under `dest_dir`, or MUST be rejected outright (returns `None`).
//! "Pass-through then escape" is the failure mode the suite is
//! designed to catch.

#![allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::too_many_lines,
    clippy::similar_names,
    // Debug formatting of paths is intentional: a failing vector may
    // contain NUL / control bytes that Display would render invisibly.
    clippy::unnecessary_debug_formatting
)]

use std::path::{Component, Path, PathBuf};

use csaf_core::path_security::safe_join;

const BASE: &str = "/var/lib/csaf-crud/csaf";

fn base() -> PathBuf {
    PathBuf::from(BASE)
}

/// Helper: assert that `input` is rejected.
#[track_caller]
fn assert_rejected(label: &str, input: &str) {
    let got = safe_join(&base(), input);
    assert!(
        got.is_none(),
        "{label}: expected REJECTION for {input:?}, got accepted as {got:?}"
    );
}

/// Helper: assert that `input` is accepted AND the result stays
/// inside `dest_dir` AND contains no residual `..` components.
#[track_caller]
fn assert_accepted_under_base(label: &str, input: &str) {
    let got = safe_join(&base(), input);
    let resolved =
        got.unwrap_or_else(|| panic!("{label}: expected ACCEPT for {input:?}, got rejected"));
    assert!(
        resolved.starts_with(base()),
        "{label}: result {resolved:?} escapes base {BASE} for input {input:?}"
    );
    assert!(
        !resolved
            .components()
            .any(|c| matches!(c, Component::ParentDir)),
        "{label}: result {resolved:?} still contains `..` for input {input:?}"
    );
}

// ======================================================================
// Happy-path: well-formed relative paths MUST be accepted
// ======================================================================

#[test]
fn happy_simple_filename() {
    assert_accepted_under_base("happy_simple_filename", "advisory.json");
}

#[test]
fn happy_year_subdir() {
    assert_accepted_under_base("happy_year_subdir", "2026/001/ndaal-sa-2026-001.json");
}

#[test]
fn happy_deep_nesting() {
    assert_accepted_under_base("happy_deep_nesting", "a/b/c/d/e/f/g/h/i/j/k.json");
}

#[test]
fn happy_curdir_segments_collapse() {
    assert_accepted_under_base("happy_curdir_segments_collapse", "./2026/./001/./adv.json");
}

#[test]
fn happy_dotfile() {
    // Files starting with `.` are fine — only `..` is escape-bearing.
    assert_accepted_under_base("happy_dotfile", ".hidden");
}

#[test]
fn happy_long_filename() {
    // 255 chars is the typical filesystem maximum; we accept it
    // because rejection belongs at the syscall layer, not here.
    let long_name = "a".repeat(255);
    assert_accepted_under_base("happy_long_filename", &long_name);
}

#[test]
fn happy_path_with_special_chars() {
    // Special chars OTHER than `\0` are allowed at the lexical layer
    // (the filesystem will reject what it doesn't support).
    assert_accepted_under_base("happy_path_with_special_chars", "name with spaces.json");
    assert_accepted_under_base("happy_path_with_unicode", "ç-é-ñ.json");
    assert_accepted_under_base("happy_path_with_emoji", "🚀.json");
}

// ======================================================================
// cs_* — cap-std upstream-style boundary-escape vectors
// ======================================================================

#[test]
fn cs_absolute_unix_root() {
    assert_rejected("cs_absolute_unix_root", "/etc/passwd");
}

#[test]
fn cs_absolute_unix_root_dot() {
    assert_rejected("cs_absolute_unix_root_dot", "/./etc/passwd");
}

#[test]
fn cs_absolute_unix_double_slash() {
    assert_rejected("cs_absolute_unix_double_slash", "//etc/passwd");
}

#[test]
fn cs_parent_one_level() {
    assert_rejected("cs_parent_one_level", "../etc/passwd");
}

#[test]
fn cs_parent_multi_level() {
    assert_rejected("cs_parent_multi_level", "../../../../../../etc/passwd");
}

#[test]
fn cs_parent_then_descend() {
    assert_rejected("cs_parent_then_descend", "../csaf-other/secret.json");
}

#[test]
fn cs_descend_then_escape() {
    // Common bypass attempt: descend into a real subdir then escape
    // via `..` — caught by the post-walk `starts_with(base)` check.
    assert_rejected("cs_descend_then_escape", "2026/../../etc/passwd");
}

#[test]
fn cs_alternating_dots() {
    assert_rejected("cs_alternating_dots", "./../foo/../../bar");
}

#[test]
fn cs_only_dots() {
    assert_rejected("cs_only_dots", "..");
    assert_rejected("cs_only_dots_doubled", "../..");
}

#[test]
fn cs_curdir_only() {
    // `.` alone resolves to base itself — accepted (degenerate but
    // not an escape).
    assert_accepted_under_base("cs_curdir_only", ".");
}

#[test]
fn cs_empty_string() {
    // Empty input → join is base itself → accepted.  No segment to
    // escape with, no NUL, not absolute.
    assert_accepted_under_base("cs_empty_string", "");
}

#[test]
fn cs_trailing_slash() {
    assert_accepted_under_base("cs_trailing_slash", "2026/");
}

#[test]
fn cs_trailing_parent() {
    // Trailing `..` MUST escape: base/foo/.. == base; we accept
    // that, but base/.. escapes base.
    assert_rejected("cs_trailing_parent_only", "..");
    assert_accepted_under_base("cs_trailing_parent_after_descent", "2026/..");
}

// ======================================================================
// cs_nul_* — NUL-byte truncation (CVE-2007-0883 family)
// ======================================================================

#[test]
fn cs_nul_leading() {
    assert_rejected("cs_nul_leading", "\0advisory.json");
}

#[test]
fn cs_nul_trailing() {
    assert_rejected("cs_nul_trailing", "advisory.json\0");
}

#[test]
fn cs_nul_embedded() {
    assert_rejected("cs_nul_embedded", "advisory\0.json");
}

#[test]
fn cs_nul_after_escape() {
    assert_rejected("cs_nul_after_escape", "../etc/passwd\0.json");
}

#[test]
fn cs_nul_after_safe_segment() {
    // A NUL anywhere is a flat reject, even after an otherwise
    // legitimate segment.
    assert_rejected("cs_nul_after_safe_segment", "2026/001\0.json");
}

// ======================================================================
// cs_symlink_* — symlink-shaped INPUT strings.  String-level
// safe_join cannot dereference symlinks; the test checks that the
// names themselves don't constitute an escape.  cap-std's syscall
// boundary handles actual symlink resolution at the kernel.
// ======================================================================

#[test]
fn cs_symlink_name_is_safe() {
    // A filename that happens to be `etc-passwd-link` is just a
    // name — no traversal, no NUL, no absolute prefix.
    assert_accepted_under_base("cs_symlink_name_is_safe", "etc-passwd-link");
}

#[test]
fn cs_proc_self_environ_relative() {
    // `proc/self/environ` as a relative path is legal — the
    // filesystem will resolve it relative to base, where it does
    // not exist.  String-level: not an escape.
    assert_accepted_under_base("cs_proc_self_environ_relative", "proc/self/environ");
}

#[test]
fn cs_absolute_proc_self_environ() {
    assert_rejected("cs_absolute_proc_self_environ", "/proc/self/environ");
}

// ======================================================================
// owasp_* — OWASP Path Traversal cheat sheet
// ======================================================================

#[test]
fn owasp_classic() {
    assert_rejected("owasp_classic", "../../../etc/passwd");
}

#[test]
fn owasp_url_encoded_slash() {
    // %2f is NOT decoded by safe_join (we operate on raw strings).
    // The literal three-char sequence "%2f" is a legal filename
    // and we accept it.  Any caller that URL-decodes BEFORE calling
    // safe_join must do so safely.
    assert_accepted_under_base("owasp_url_encoded_slash", "..%2f..%2fetc%2fpasswd");
}

#[test]
fn owasp_double_url_encoded() {
    // Same logic — safe_join treats `%252e` as literal characters.
    assert_accepted_under_base("owasp_double_url_encoded", "%252e%252e%252fetc");
}

#[test]
fn owasp_overlong_utf8_dot() {
    // The 4-byte overlong UTF-8 representation of `.` is itself a
    // multibyte sequence, not a literal `..` component.  Most Rust
    // string APIs reject overlong sequences in `from_utf8`, but
    // because we accept `&str` (already validated UTF-8) we never
    // see them.  We DO accept legal multibyte sequences as
    // filenames.
    assert_accepted_under_base("owasp_overlong_utf8_dot", "\u{2024}\u{2024}/etc");
}

#[test]
fn owasp_windows_backslash_traversal_on_unix() {
    // On Unix targets `..\\..\\etc` is a single filename — `\\` is
    // not a path separator.  Accepted.  On Windows targets, both
    // `/` and `\\` are separators; safe_join's behaviour there is
    // verified by the platform-specific tests below.
    #[cfg(unix)]
    assert_accepted_under_base("owasp_windows_backslash_traversal_on_unix", "..\\..\\etc");
}

#[test]
fn owasp_unc_path_unix() {
    // On Unix, `\\\\server\\share` is a literal 6-component path
    // starting with backslashes; no escape.  On Windows it's UNC.
    #[cfg(unix)]
    assert_accepted_under_base("owasp_unc_path_unix", "\\\\server\\share\\file");
}

#[test]
fn owasp_drive_letter_unix() {
    // `C:/etc/passwd` is a relative path on Unix (the `C:` is just
    // a filename segment).  On Windows it's an absolute path with
    // a drive prefix.
    #[cfg(unix)]
    assert_accepted_under_base("owasp_drive_letter_unix", "C:/etc/passwd");
}

#[cfg(windows)]
#[test]
fn owasp_drive_letter_windows() {
    assert_rejected("owasp_drive_letter_windows", "C:\\etc\\passwd");
}

#[cfg(windows)]
#[test]
fn owasp_unc_path_windows() {
    assert_rejected("owasp_unc_path_windows", "\\\\server\\share\\file");
}

#[test]
fn owasp_null_byte_truncation() {
    // Classic null-byte injection.
    assert_rejected("owasp_null_byte_truncation", "../../../etc/passwd\0.jpg");
}

#[test]
fn owasp_mixed_separators() {
    // On Unix, `\\` is NOT a path separator — `..\\..\\..` is a
    // single, legally-named filename, so the whole input parses as
    // a three-component relative path whose first segment has
    // backslashes in its name.  No `ParentDir` component, no
    // escape, accepted as-is.  On Windows the same input would
    // parse to multiple `ParentDir` components and reject.
    #[cfg(unix)]
    assert_accepted_under_base("owasp_mixed_separators_unix", "..\\..\\../etc/passwd");
    #[cfg(windows)]
    assert_rejected("owasp_mixed_separators_windows", "..\\..\\../etc/passwd");
}

// ======================================================================
// csaf_* — actual attacker-controlled fields from upstream feeders
// ======================================================================

#[test]
fn csaf_tracking_id_traversal() {
    // A malicious CSAF document with
    // `document.tracking.id == "../../etc/passwd"` would cause
    // unsafe write paths in our feeders before the safe_join check.
    assert_rejected("csaf_tracking_id_traversal", "../../etc/passwd");
}

#[test]
fn csaf_tracking_id_absolute() {
    assert_rejected("csaf_tracking_id_absolute", "/etc/passwd");
}

#[test]
fn csaf_index_txt_path_with_escape() {
    // The `changes.csv` / `index.txt` columns are attacker-controlled
    // — the CSAF Trusted Provider can serve arbitrary content.
    assert_rejected(
        "csaf_index_txt_path_with_escape",
        "2026/../../../../tmp/pwned.json",
    );
}

#[test]
fn csaf_advisory_id_with_curdir() {
    // CSAF advisory IDs occasionally contain `.` in the wild;
    // `./` as a leading segment must not break the accepted-set.
    assert_accepted_under_base("csaf_advisory_id_with_curdir", "./ndaal-sa-2026-044.json");
}

#[test]
fn csaf_advisory_id_legitimate_dot() {
    // Names like `v1.2.3-advisory` contain `.` but no `..` segment.
    assert_accepted_under_base("csaf_advisory_id_legitimate_dot", "v1.2.3-advisory.json");
}

#[test]
fn csaf_atom_id_with_uri_fragment() {
    // Atom `<id>` URIs sometimes leak into derived filenames.
    // safe_join treats the whole string as a filename; any `://`
    // makes it non-traversing.
    assert_accepted_under_base(
        "csaf_atom_id_with_uri_fragment",
        "https:%2F%2Fexample.com%2Fa%2Fb",
    );
}

#[test]
fn csaf_extremely_deep_traversal() {
    // 32 levels of `..` — must reject even though base has only ~4
    // levels.  Defends against patterns that try to overflow
    // a `usize` depth counter.
    let attack = "../".repeat(32) + "etc/passwd";
    assert_rejected("csaf_extremely_deep_traversal", &attack);
}

// ======================================================================
// unicode_* — Unicode normalisation cases that have escaped other
// projects' sandboxes
// ======================================================================

#[test]
fn unicode_combining_acute_dot() {
    // `é` written as `e` + U+0301 combining acute.  Two codepoints,
    // displays as one — but the underlying bytes do NOT form `..`,
    // so accepted.
    let nfd = "e\u{0301}.json";
    assert_accepted_under_base("unicode_combining_acute_dot", nfd);
}

#[test]
fn unicode_rtl_override() {
    // U+202E RIGHT-TO-LEFT OVERRIDE famously confuses humans
    // reading file lists — but the bytes are still a single name
    // segment.  Accepted.
    let rtl = "advisory\u{202E}json.txt";
    assert_accepted_under_base("unicode_rtl_override", rtl);
}

#[test]
fn unicode_fullwidth_dot_segments() {
    // U+FF0E FULLWIDTH FULL STOP visually resembles `.` but is a
    // distinct codepoint — does NOT form `..` to the OS path
    // parser.  Accepted as a (visually weird) filename.
    let fullwidth = "\u{FF0E}\u{FF0E}/etc/passwd";
    assert_accepted_under_base("unicode_fullwidth_dot_segments", fullwidth);
}

#[test]
fn unicode_zero_width_joiner() {
    // U+200D between dots does NOT make `..` — the joiner is a
    // codepoint between the two dots, so to the path parser it's
    // a 3-codepoint segment, not a `ParentDir` component.
    let zwj = ".\u{200D}./etc/passwd";
    assert_accepted_under_base("unicode_zero_width_joiner", zwj);
}

#[test]
fn unicode_homoglyph_slash() {
    // U+2215 DIVISION SLASH looks like `/` but is not a path
    // separator on any OS Rust supports.  Accepted as a single
    // filename containing the codepoint.
    let homoglyph = "etc\u{2215}passwd";
    assert_accepted_under_base("unicode_homoglyph_slash", homoglyph);
}

// ======================================================================
// Property-style coverage — many randomly-generated traversal
// vectors must all reject.  Uses deterministic seeds so the corpus
// is reproducible.
// ======================================================================

#[test]
fn property_every_traversal_depth_rejected() {
    // 1..=64 levels of `../` followed by `etc/passwd` — every one
    // must reject.  Mirrors the bounded loop the cap-std primitive
    // walks internally.
    for depth in 1..=64 {
        let attack = "../".repeat(depth) + "etc/passwd";
        assert_rejected(&format!("property_traversal_depth_{depth}"), &attack);
    }
}

#[test]
fn property_balanced_pop_then_descend_rejected() {
    // `a/../a/../...../etc/passwd` — alternating descend/pop.
    // Each step lands at base; a single `..` at the end escapes.
    for n in 1..=16 {
        let mut attack = String::new();
        for _ in 0..n {
            attack.push_str("a/../");
        }
        attack.push_str("../etc/passwd");
        assert_rejected(&format!("property_balanced_pop_then_descend_n{n}"), &attack);
    }
}

#[test]
fn property_balanced_pop_stays_at_base_accepted() {
    // The above pattern WITHOUT a trailing `..`: ends inside base,
    // accepted.  Confirms safe_join doesn't reject legitimate
    // walks.
    for n in 1..=16 {
        let mut path = String::new();
        for _ in 0..n {
            path.push_str("a/../");
        }
        path.push_str("etc/passwd");
        assert_accepted_under_base(&format!("property_balanced_pop_n{n}"), &path);
    }
}

#[test]
fn property_nul_at_every_position_rejected() {
    // Insert `\0` at every byte position of a benign filename.
    let benign = "advisory-2026-001.json";
    for pos in 0..=benign.len() {
        let mut s = String::with_capacity(benign.len() + 1);
        s.push_str(&benign[..pos]);
        s.push('\0');
        s.push_str(&benign[pos..]);
        assert_rejected(&format!("property_nul_pos_{pos}"), &s);
    }
}

// ======================================================================
// Idempotence + post-condition properties
// ======================================================================

#[test]
fn idempotence_double_safe_join_is_consistent() {
    // Run safe_join twice on the same input — must yield equal
    // results.  Catches state-leak / TLS-cache bugs.
    let inputs = [
        "2026/001/adv.json",
        "deeply/nested/file.json",
        "./curdir/then/file.json",
    ];
    for input in inputs {
        let first = safe_join(&base(), input);
        let second = safe_join(&base(), input);
        assert_eq!(first, second, "non-idempotent for {input:?}");
    }
}

#[test]
fn post_condition_accepted_paths_have_no_parent_dir_component() {
    // Cross-check the post-walk invariant that the
    // `fuzz_advisory_path_traversal` fuzz target asserts: every
    // accepted path is `..`-free.
    let inputs = [
        "a/b/c.json",
        "./a/./b/./c.json",
        "x/y/../z/file.json",
        "x/y/../../",
    ];
    for input in inputs {
        if let Some(resolved) = safe_join(&base(), input) {
            assert!(
                !resolved
                    .components()
                    .any(|c| matches!(c, Component::ParentDir)),
                "post-walk path {resolved:?} still has ParentDir for input {input:?}"
            );
        }
    }
}

#[test]
fn post_condition_accepted_paths_start_with_base() {
    let inputs = [
        "a.json",
        "./a.json",
        "deep/nested/dir/a.json",
        "a/../b.json",
    ];
    for input in inputs {
        if let Some(resolved) = safe_join(&base(), input) {
            assert!(
                resolved.starts_with(base()),
                "accepted {resolved:?} does not start with base for input {input:?}"
            );
        }
    }
}

#[test]
fn base_with_trailing_slash_equivalent() {
    // safe_join(base, "x") == safe_join(base_with_slash, "x")
    let base_a = Path::new(BASE);
    let base_b = PathBuf::from(format!("{BASE}/"));
    for input in ["a.json", "2026/b.json", "./c.json"] {
        let ra = safe_join(base_a, input);
        let rb = safe_join(&base_b, input);
        assert_eq!(
            ra, rb,
            "result differs by base trailing-slash for input {input:?}: a={ra:?} b={rb:?}"
        );
    }
}