soft-canonicalize 0.5.5

Path canonicalization that works with non-existing paths.
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
/// CVE security tests: symlink races, Podman-style escapes, archive traversal,
/// URL-encoded paths, combined vectors, and defensive edge cases
///
/// Covers:
/// - CVE-2024-23651: Symlink TOCTOU race conditions (Docker/Buildkit)
/// - CVE-2024-21626: File descriptor leaks via /proc/self/fd
/// - CVE-2025-9566: Podman symlink traversal
/// - CVE-2024-38819: Path traversal via crafted HTTP requests (Spring Framework)
/// - Combined multi-technique attack vectors
/// - Defensive programming: long paths, deeply nested paths, empty components
use crate::soft_canonicalize;

#[cfg(feature = "anchored")]
use crate::anchored_canonicalize;

// ============================================================================
// Symlink TOCTOU Race Conditions (CVE-2024-23651, CVE-2024-21626)
// ============================================================================

#[cfg(unix)]
#[test]
fn test_symlink_swap_race_resistance() {
    // WHITE-BOX: Based on CVE-2024-23651 (Docker Buildkit cache mount race)
    // Verify that symlink target swapping during resolution doesn't cause escape

    use std::fs;
    use std::os::unix::fs::symlink;
    use std::thread;
    use std::time::Duration;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let base = temp_dir.path();

    let safe_target = base.join("safe");
    let dangerous_target = base.join("dangerous");
    fs::create_dir(&safe_target).unwrap();
    fs::create_dir(&dangerous_target).unwrap();

    let link = base.join("racing_link");
    symlink(&safe_target, &link).unwrap();

    let link_clone = link.clone();
    let dangerous_clone = dangerous_target.clone();

    // Spawn thread to swap symlink target mid-resolution
    let handle = thread::spawn(move || {
        thread::sleep(Duration::from_micros(100));
        let _ = fs::remove_file(&link_clone);
        let _ = symlink(&dangerous_clone, &link_clone);
    });

    // Attempt canonicalization during race window
    let result = soft_canonicalize(link.join("nonexistent.txt"));

    handle.join().unwrap();

    // Should either succeed with one of the targets or fail gracefully
    match result {
        Ok(resolved) => {
            // Must resolve to one of the two targets (race is benign)
            // Canonicalize expected paths to handle macOS /var -> /private/var symlink
            let safe_expected = soft_canonicalize(safe_target.join("nonexistent.txt")).unwrap();
            let dangerous_expected =
                soft_canonicalize(dangerous_target.join("nonexistent.txt")).unwrap();
            assert!(
                resolved == safe_expected || resolved == dangerous_expected,
                "Should resolve to one of the race targets.\nExpected either:\n  {:?}\n  {:?}\nGot:\n  {:?}",
                safe_expected,
                dangerous_expected,
                resolved
            );
        }
        Err(e) => {
            // Graceful failure is acceptable
            assert!(
                e.kind() == std::io::ErrorKind::NotFound
                    || e.kind() == std::io::ErrorKind::InvalidInput,
                "Should fail gracefully: {}",
                e
            );
        }
    }
}

#[cfg(unix)]
#[test]
fn test_proc_self_fd_symlink_attack() {
    // BLACK-BOX: Based on CVE-2024-21626 (runC /proc/self/fd escape)
    // Malicious container could symlink to /proc/self/fd/N to access host filesystem

    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let base = temp_dir.path();

    // Simulate malicious symlink pointing to /proc/self/fd/7
    let malicious_link = base.join("innocent_looking_path");
    symlink("/proc/self/fd/7", &malicious_link).unwrap();

    // Try to canonicalize the malicious symlink
    let result = soft_canonicalize(&malicious_link);

    // Should handle gracefully - either resolve to actual fd target or error
    if let Ok(resolved) = result {
        // If it resolves, verify it doesn't give unexpected access
        let resolved_str = resolved.to_string_lossy();
        // The fd might not exist or might point somewhere safe
        println!("Resolved /proc/self/fd/7 symlink to: {}", resolved_str);
    }
    // Failure is acceptable if fd doesn't exist
}

#[cfg(feature = "anchored")]
#[cfg(unix)]
#[test]
fn test_anchored_symlink_toctou_race() {
    // WHITE-BOX: Symlink TOCTOU in anchored context (CVE-2025-9566 pattern)
    // Verify anchored_canonicalize handles symlink races within virtual filesystem

    use std::fs;
    use std::os::unix::fs::symlink;
    use std::thread;
    use std::time::Duration;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let anchor = temp_dir.path().join("anchor");
    fs::create_dir_all(&anchor).unwrap();

    let internal_target = anchor.join("internal");
    fs::create_dir(internal_target).unwrap();

    let link = anchor.join("link");
    symlink("internal", &link).unwrap();

    let link_clone = link;

    // Try to swap to absolute path during resolution
    let handle = thread::spawn(move || {
        thread::sleep(Duration::from_micros(100));
        let _ = fs::remove_file(&link_clone);
        let _ = symlink("/etc/passwd", &link_clone);
    });

    // Attempt anchored canonicalization during race
    let result = anchored_canonicalize(&anchor, "link/nonexistent");

    handle.join().unwrap();

    // Must stay within anchor regardless of race outcome
    if let Ok(resolved) = result {
        assert!(
            resolved.starts_with(&anchor)
                || resolved.starts_with(fs::canonicalize(&anchor).unwrap()),
            "Race should not escape anchor: {:?}",
            resolved
        );
    }
    // Failure is acceptable
}

// ============================================================================
// Podman-style Symlink Traversal (CVE-2025-9566)
// ============================================================================

#[cfg(feature = "anchored")]
#[cfg(unix)]
#[test]
fn test_configmap_style_symlink_escape_prevention() {
    // BLACK-BOX: Based on CVE-2025-9566 (Podman kube play symlink traversal)
    // Malicious ConfigMap/Secret could contain symlinks designed to escape container

    use std::fs;
    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let container_root = temp_dir.path().join("container");
    fs::create_dir_all(&container_root).unwrap();

    // Simulate mounting a ConfigMap with malicious symlink
    let configmap_dir = container_root.join("configmap");
    fs::create_dir(&configmap_dir).unwrap();

    // Malicious symlink trying to escape to host /etc
    let malicious_config = configmap_dir.join("escape_link");
    symlink("/etc/shadow", malicious_config).unwrap();

    // Use anchored canonicalization (like container runtime should)
    let result = anchored_canonicalize(&container_root, "configmap/escape_link");

    assert!(result.is_ok());
    let resolved = result.unwrap();

    // Must be clamped within container root
    let canon_root = fs::canonicalize(&container_root).unwrap();
    assert!(
        resolved.starts_with(&canon_root),
        "ConfigMap symlink should be clamped to container: {:?} not in {:?}",
        resolved,
        canon_root
    );

    // Should map to container/etc/shadow, not host /etc/shadow
    assert!(
        resolved.ends_with("etc/shadow"),
        "Should clamp to virtual etc/shadow: {:?}",
        resolved
    );
}

#[cfg(feature = "anchored")]
#[cfg(unix)]
#[test]
fn test_nested_configmap_symlinks() {
    // WHITE-BOX: Chained symlinks in ConfigMap-style scenario
    // link1 -> link2 -> /host/secret

    use std::fs;
    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let container = temp_dir.path().join("container");
    fs::create_dir_all(&container).unwrap();

    let config_dir = container.join("config");
    fs::create_dir(&config_dir).unwrap();

    // Create symlink chain
    let link1 = config_dir.join("link1");
    let link2 = config_dir.join("link2");

    symlink("link2", link1).unwrap();
    symlink("/host/sensitive/data", link2).unwrap();

    let result = anchored_canonicalize(&container, "config/link1");

    assert!(result.is_ok());
    let resolved = result.unwrap();

    // Must be clamped
    let canon_container = fs::canonicalize(&container).unwrap();
    assert!(
        resolved.starts_with(canon_container),
        "Chained symlinks should stay clamped: {:?}",
        resolved
    );
}

// ============================================================================
// Archive Extraction Scenarios (General Path Traversal)
// ============================================================================

#[cfg(feature = "anchored")]
#[test]
fn test_tar_bomb_style_dotdot_sequences() {
    // BLACK-BOX: Malicious archive with excessive ../ sequences
    // Common in tar bombs and zip slip attacks

    use std::fs;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let extract_zone = temp_dir.path().join("extract");
    fs::create_dir_all(&extract_zone).unwrap();

    // Simulate extracting file with malicious path
    let malicious_paths = vec![
        "../../../etc/cron.d/backdoor",
        "../../../../../../../../tmp/evil.sh",
        "subdir/../../../../../../etc/passwd",
    ];

    for malicious_path in malicious_paths {
        let result = anchored_canonicalize(&extract_zone, malicious_path);

        if let Ok(resolved) = result {
            // Must stay within extraction zone
            assert!(
                resolved.starts_with(soft_canonicalize(&extract_zone).unwrap()),
                "Archive path should be contained: {} -> {:?}",
                malicious_path,
                resolved
            );
        }
        // Err(_) => Rejection is also acceptable
    }
}

#[cfg(feature = "anchored")]
#[cfg(unix)]
#[test]
fn test_tar_bomb_with_absolute_symlinks() {
    // BLACK-BOX: Archive contains both files and absolute symlinks
    // Attacker tries to write through symlink to host filesystem

    use std::fs;
    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let extract_zone = temp_dir.path().join("extract");
    fs::create_dir_all(&extract_zone).unwrap();

    // Simulate extracted symlink pointing to /tmp
    let extracted_link = extract_zone.join("tmplink");
    symlink("/tmp", extracted_link).unwrap();

    // Try to write through the symlink
    let result = anchored_canonicalize(&extract_zone, "tmplink/evil_payload.sh");

    assert!(result.is_ok());
    let resolved = result.unwrap();

    // Must be clamped (should resolve to extract_zone/tmp/evil_payload.sh)
    let canon_extract = fs::canonicalize(&extract_zone).unwrap();
    assert!(
        resolved.starts_with(canon_extract),
        "Archive symlink should be clamped: {:?}",
        resolved
    );
}

// ============================================================================
// Edge Cases from CVE-2024-38819 (Spring Framework)
// ============================================================================

#[test]
fn test_url_encoded_path_traversal() {
    // BLACK-BOX: URL-encoded path traversal sequences
    // CVE-2024-38819 involved crafted HTTP requests with encoded paths

    // These should be handled at HTTP layer, but verify we handle literal strings
    let paths = vec![
        "..%2F..%2F..%2Fetc%2Fpasswd", // ../../../etc/passwd
        "..%5c..%5c..%5cwindows",      // ..\..\..\windows
        "%2e%2e%2f%2e%2e%2f",          // ../../
    ];

    for path in paths {
        let result = soft_canonicalize(path);

        if let Ok(resolved) = result {
            let resolved_str = resolved.to_string_lossy();
            // Should treat as literal strings (URL decoding is HTTP layer's job)
            // We just verify we don't crash
            assert!(!resolved_str.is_empty());
        }
        // Err(_) => Invalid paths should error appropriately
    }
}

#[test]
fn test_double_encoded_traversal() {
    // BLACK-BOX: Double URL-encoded traversal attempts

    let paths = vec![
        "%252e%252e%252f", // Double-encoded ../
        "%252e%252e%255c", // Double-encoded ..\
    ];

    for path in paths {
        let result = soft_canonicalize(path);
        // Should handle as literal string (no decoding)
        match result {
            Ok(_) | Err(_) => {
                // Either outcome is fine, just don't crash
            }
        }
    }
}

// ============================================================================
// Mixed Attack Vectors
// ============================================================================

#[cfg(feature = "anchored")]
#[cfg(unix)]
#[test]
fn test_combined_device_symlink_dotdot_attack() {
    // WHITE-BOX: Combine multiple attack techniques
    // Symlink + excessive ../ + absolute paths

    use std::fs;
    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let anchor = temp_dir.path().join("sandbox");
    fs::create_dir_all(&anchor).unwrap();

    let attack_dir = anchor.join("attack");
    fs::create_dir(&attack_dir).unwrap();

    // Create symlink to absolute path
    let link = attack_dir.join("escape");
    symlink("/etc/passwd", link).unwrap();

    // Try to traverse through symlink
    let result = anchored_canonicalize(&anchor, "attack/escape/../../../etc/shadow");

    assert!(result.is_ok());
    let resolved = result.unwrap();

    // Must stay clamped
    let canon_anchor = fs::canonicalize(&anchor).unwrap();
    assert!(
        resolved.starts_with(canon_anchor),
        "Combined attack should be contained: {:?}",
        resolved
    );
}

// ============================================================================
// Defensive Programming Tests
// ============================================================================

#[test]
fn test_extremely_long_path_with_traversal() {
    // WHITE-BOX: Very long paths with traversal sequences
    // Ensure no buffer issues or performance degradation

    let mut long_path = String::new();
    for _ in 0..1000 {
        long_path.push_str("../");
    }
    long_path.push_str("etc/passwd");

    let result = soft_canonicalize(&long_path);

    // Should handle without panic or hang
    assert!(result.is_ok());
}

#[test]
fn test_deeply_nested_nonexistent_path() {
    // BLACK-BOX: Very deep directory nesting

    let mut deep_path = String::from("a");
    for _ in 0..500 {
        deep_path.push_str("/b");
    }

    let result = soft_canonicalize(&deep_path);

    // Should handle without panic
    assert!(result.is_ok());
}

#[cfg(feature = "anchored")]
#[test]
fn test_anchored_with_empty_components() {
    // WHITE-BOX: Paths with empty components (doubled slashes)

    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let anchor = temp_dir.path();

    let paths = vec!["foo//bar", "foo///bar", "./foo//bar", "foo/./bar"];

    for path in paths {
        let result = anchored_canonicalize(anchor, path);
        assert!(
            result.is_ok(),
            "Empty components should be normalized: {}",
            path
        );
    }
}