bashkit 0.5.0

Awesomely fast virtual sandbox with bash and file system
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
521
522
523
524
525
//! Integration tests for RealFs feature.
//!
//! Tests the full pipeline: host directory → RealFs → PosixFs → Bash interpreter.

#![cfg(feature = "realfs")]

use bashkit::Bash;
use std::path::Path;

fn setup_host_dir() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("hello.txt"), "hello world\n").unwrap();
    std::fs::create_dir(dir.path().join("subdir")).unwrap();
    std::fs::write(dir.path().join("subdir/nested.txt"), "nested\n").unwrap();
    std::fs::write(dir.path().join("data.csv"), "a,1\nb,2\nc,3\n").unwrap();
    dir
}

// --- Use case 1: readonly overlay at root ---

#[tokio::test]
async fn readonly_root_overlay_cat() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    let result = bash.exec("cat /hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn readonly_root_overlay_ls() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    let result = bash.exec("ls /").await.unwrap();
    assert!(result.stdout.contains("hello.txt"));
    assert!(result.stdout.contains("subdir"));
}

#[tokio::test]
async fn readonly_root_overlay_nested() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    let result = bash.exec("cat /subdir/nested.txt").await.unwrap();
    assert_eq!(result.stdout, "nested\n");
}

#[tokio::test]
async fn readonly_root_overlay_write_goes_to_memory() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    // Write a new file - should go to in-memory overlay
    bash.exec("echo 'vfs only' > /new_file.txt").await.unwrap();
    let result = bash.exec("cat /new_file.txt").await.unwrap();
    assert_eq!(result.stdout, "vfs only\n");

    // Host should NOT have this file
    assert!(!dir.path().join("new_file.txt").exists());
}

#[tokio::test]
async fn readonly_root_overlay_pipes() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    let result = bash.exec("cat /data.csv | grep b").await.unwrap();
    assert_eq!(result.stdout, "b,2\n");
}

#[tokio::test]
async fn readonly_root_overlay_wc() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readonly(dir.path()).build();

    let result = bash.exec("wc -l < /data.csv").await.unwrap();
    assert_eq!(result.stdout.trim(), "3");
}

// --- Use case 2: readonly mount at specific path ---

#[tokio::test]
async fn readonly_mount_at_path_cat() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    let result = bash.exec("cat /mnt/data/hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");
}

#[tokio::test]
async fn readonly_mount_at_path_ls() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    let result = bash.exec("ls /mnt/data").await.unwrap();
    assert!(result.stdout.contains("hello.txt"));
    assert!(result.stdout.contains("subdir"));
}

#[tokio::test]
async fn readonly_mount_at_path_vfs_root_intact() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    // VFS root should still have default dirs
    let result = bash
        .exec("test -d /tmp && echo yes || echo no")
        .await
        .unwrap();
    assert_eq!(result.stdout.trim(), "yes");

    // Can write to VFS normally
    bash.exec("echo test > /tmp/test.txt").await.unwrap();
    let result = bash.exec("cat /tmp/test.txt").await.unwrap();
    assert_eq!(result.stdout, "test\n");
}

// --- Use case 3: readwrite mount ---

#[tokio::test]
async fn readwrite_mount_modifies_host() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/workspace")
        .build();

    // Read existing file
    let result = bash.exec("cat /workspace/hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");

    // Write to host file (overwrite)
    bash.exec("echo 'modified by bash' > /workspace/hello.txt")
        .await
        .unwrap();

    // Verify on host
    let content = std::fs::read_to_string(dir.path().join("hello.txt")).unwrap();
    assert_eq!(content, "modified by bash\n");

    // Append to host file
    bash.exec("echo 'appended line' >> /workspace/hello.txt")
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("hello.txt")).unwrap();
    assert!(
        content.contains("appended line"),
        "append should modify host file, got: {:?}",
        content
    );
}

#[tokio::test]
async fn readwrite_mount_creates_files_on_host() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/workspace")
        .build();

    bash.exec("echo 'new' > /workspace/created.txt")
        .await
        .unwrap();

    assert!(dir.path().join("created.txt").exists());
    let content = std::fs::read_to_string(dir.path().join("created.txt")).unwrap();
    assert_eq!(content, "new\n");
}

#[tokio::test]
async fn readwrite_mount_creates_dirs_on_host() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/workspace")
        .build();

    bash.exec("mkdir -p /workspace/a/b/c").await.unwrap();
    assert!(dir.path().join("a/b/c").is_dir());
}

#[tokio::test]
async fn readwrite_root_overlay() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder().mount_real_readwrite(dir.path()).build();

    let result = bash.exec("cat /hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");

    // Write goes to overlay (in-memory), not host, because OverlayFs wraps it
    bash.exec("echo 'overlay' > /overlay_file.txt")
        .await
        .unwrap();
    let result = bash.exec("cat /overlay_file.txt").await.unwrap();
    assert_eq!(result.stdout, "overlay\n");
}

// --- Multiple mounts ---

#[tokio::test]
async fn multiple_readonly_mounts() {
    let dir1 = setup_host_dir();
    let dir2 = tempfile::tempdir().unwrap();
    std::fs::write(dir2.path().join("other.txt"), "from dir2\n").unwrap();

    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir1.path(), "/mnt/a")
        .mount_real_readonly_at(dir2.path(), "/mnt/b")
        .build();

    let result = bash.exec("cat /mnt/a/hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");

    let result = bash.exec("cat /mnt/b/other.txt").await.unwrap();
    assert_eq!(result.stdout, "from dir2\n");
}

#[tokio::test]
async fn mixed_readonly_and_text_mounts() {
    let dir = setup_host_dir();

    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/host")
        .mount_text("/config/app.toml", "key = 'value'\n")
        .build();

    let result = bash.exec("cat /mnt/host/hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");

    let result = bash.exec("cat /config/app.toml").await.unwrap();
    assert_eq!(result.stdout, "key = 'value'\n");
}

// --- Security: path traversal ---

#[tokio::test]
async fn path_traversal_blocked_via_bash() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    // Attempt traversal - should not leak files outside the mount root
    let result = bash
        .exec("cat /mnt/data/../../etc/passwd 2>&1")
        .await
        .unwrap();
    // This should fail or return content from VFS, not from host /etc/passwd
    assert!(result.exit_code != 0 || !result.stdout.contains("root:"));
}

// --- Direct filesystem API ---

#[tokio::test]
async fn direct_fs_api_read() {
    let dir = setup_host_dir();
    let bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    let fs = bash.fs();
    let content = fs
        .read_file(Path::new("/mnt/data/hello.txt"))
        .await
        .unwrap();
    assert_eq!(content, b"hello world\n");
}

#[tokio::test]
async fn direct_fs_api_stat() {
    let dir = setup_host_dir();
    let bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    let fs = bash.fs();
    let meta = fs.stat(Path::new("/mnt/data/hello.txt")).await.unwrap();
    assert!(meta.file_type.is_file());
    assert_eq!(meta.size, 12); // "hello world\n"
}

#[tokio::test]
async fn direct_fs_api_exists() {
    let dir = setup_host_dir();
    let bash = Bash::builder()
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    let fs = bash.fs();
    assert!(fs.exists(Path::new("/mnt/data/hello.txt")).await.unwrap());
    assert!(!fs.exists(Path::new("/mnt/data/nope.txt")).await.unwrap());
}

// ==================== Symlink sandbox escape prevention (Issue #979) ====================

#[tokio::test]
async fn realfs_symlink_absolute_escape_blocked() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/mnt/workspace")
        .build();

    // Attempt to create a symlink pointing to /etc/passwd
    let r = bash
        .exec("ln -s /etc/passwd /mnt/workspace/escape 2>&1; echo $?")
        .await
        .unwrap();
    // Should fail with non-zero exit code
    assert!(
        r.stdout.trim().ends_with('1')
            || r.stdout.contains("not allowed")
            || r.stdout.contains("Permission denied"),
        "Symlink creation should be blocked, got: {}",
        r.stdout
    );
}

#[tokio::test]
async fn realfs_symlink_relative_escape_blocked() {
    let dir = setup_host_dir();
    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/mnt/workspace")
        .build();

    // Attempt relative path traversal via symlink
    let r = bash
        .exec("ln -s ../../../../etc/passwd /mnt/workspace/escape 2>&1; echo $?")
        .await
        .unwrap();
    assert!(
        r.stdout.trim().ends_with('1')
            || r.stdout.contains("not allowed")
            || r.stdout.contains("Permission denied"),
        "Relative symlink escape should be blocked, got: {}",
        r.stdout
    );
}

#[tokio::test]
async fn realfs_symlink_within_mount_allowed() {
    let dir = setup_host_dir();
    std::fs::write(dir.path().join("original.txt"), "content").unwrap();

    let mut bash = Bash::builder()
        .mount_real_readwrite_at(dir.path(), "/mnt/workspace")
        .build();

    // Relative symlink within mount should succeed (exit code 0)
    let r = bash
        .exec("ln -s original.txt /mnt/workspace/link.txt 2>&1; echo $?")
        .await
        .unwrap();
    assert!(
        r.stdout.trim().ends_with('0'),
        "Symlink within mount should succeed, got stdout: {} stderr: {}",
        r.stdout,
        r.stderr
    );
}

// --- Mount path validation ---

#[tokio::test]
async fn mount_allowlist_blocks_unlisted_path() {
    let dir = setup_host_dir();
    std::fs::write(dir.path().join("data.txt"), "secret").unwrap();

    // Mount with allowlist that does NOT include the dir
    let mut bash = Bash::builder()
        .allowed_mount_paths(["/nonexistent/allowed"])
        .mount_real_readonly_at(dir.path(), "/mnt/data")
        .build();

    // The mount should have been skipped — file should not be accessible
    let r = bash
        .exec("cat /mnt/data/data.txt 2>&1; echo $?")
        .await
        .unwrap();
    assert!(
        r.stdout.trim().ends_with('1') || r.stdout.contains("No such file"),
        "Mount outside allowlist should be blocked, got: {}",
        r.stdout
    );
}

#[tokio::test]
async fn mount_sensitive_path_blocked() {
    // Attempting to mount /proc should be silently blocked
    let mut bash = Bash::builder()
        .mount_real_readonly_at("/proc", "/mnt/proc")
        .build();

    let r = bash.exec("ls /mnt/proc 2>&1; echo $?").await.unwrap();
    assert!(
        r.stdout.trim().ends_with('1') || r.stdout.contains("No such file"),
        "Sensitive path /proc should be blocked, got: {}",
        r.stdout
    );
}

#[tokio::test]
async fn mount_allowlist_blocks_dotdot_escape() {
    let sandbox = tempfile::tempdir().unwrap();
    let allowed_root = sandbox.path().join("allowed");
    let secret_root = sandbox.path().join("secret");
    std::fs::create_dir_all(&allowed_root).unwrap();
    std::fs::create_dir_all(&secret_root).unwrap();
    std::fs::write(secret_root.join("data.txt"), "top-secret\n").unwrap();

    let escaped_mount = allowed_root.join("../secret");
    let mut bash = Bash::builder()
        .allowed_mount_paths([&allowed_root])
        .mount_real_readonly_at(&escaped_mount, "/mnt/data")
        .build();

    let r = bash
        .exec("cat /mnt/data/data.txt 2>&1; echo $?")
        .await
        .unwrap();
    assert!(
        r.stdout.trim().ends_with('1') || r.stdout.contains("No such file"),
        "Dot-dot allowlist escape should be blocked, got: {}",
        r.stdout
    );
}

#[cfg(unix)]
#[tokio::test]
async fn mount_allowlist_blocks_symlink_escape() {
    use std::os::unix::fs::symlink;

    let sandbox = tempfile::tempdir().unwrap();
    let allowed_root = sandbox.path().join("allowed");
    let secret_root = sandbox.path().join("secret");
    std::fs::create_dir_all(&allowed_root).unwrap();
    std::fs::create_dir_all(&secret_root).unwrap();
    std::fs::write(secret_root.join("data.txt"), "top-secret\n").unwrap();

    let link_path = allowed_root.join("escape_link");
    symlink(&secret_root, &link_path).unwrap();

    let mut bash = Bash::builder()
        .allowed_mount_paths([&allowed_root])
        .mount_real_readonly_at(&link_path, "/mnt/data")
        .build();

    let r = bash
        .exec("cat /mnt/data/data.txt 2>&1; echo $?")
        .await
        .unwrap();
    assert!(
        r.stdout.trim().ends_with('1') || r.stdout.contains("No such file"),
        "Symlink allowlist escape should be blocked, got: {}",
        r.stdout
    );
}

// --- Runtime mount/unmount (exercises Bash::mount / Bash::unmount) ---

#[tokio::test]
async fn runtime_mount_readonly() {
    use bashkit::{PosixFs, RealFs, RealFsMode};
    use std::sync::Arc;

    let dir = setup_host_dir();
    let mut bash = Bash::new();

    let backend = RealFs::new(dir.path(), RealFsMode::ReadOnly).unwrap();
    let fs: Arc<dyn bashkit::FileSystem> = Arc::new(PosixFs::new(backend));
    bash.mount("/mnt/host", fs).unwrap();

    let result = bash.exec("cat /mnt/host/hello.txt").await.unwrap();
    assert_eq!(result.stdout, "hello world\n");
}

#[tokio::test]
async fn runtime_unmount() {
    use bashkit::{PosixFs, RealFs, RealFsMode};
    use std::sync::Arc;

    let dir = setup_host_dir();
    let mut bash = Bash::new();

    let backend = RealFs::new(dir.path(), RealFsMode::ReadOnly).unwrap();
    let fs: Arc<dyn bashkit::FileSystem> = Arc::new(PosixFs::new(backend));
    bash.mount("/mnt/host", fs).unwrap();

    let result = bash.exec("cat /mnt/host/hello.txt").await.unwrap();
    assert_eq!(result.exit_code, 0);

    bash.unmount("/mnt/host").unwrap();

    let result = bash.exec("cat /mnt/host/hello.txt 2>&1").await.unwrap();
    assert_ne!(
        result.exit_code, 0,
        "file should not be accessible after unmount"
    );
}

#[tokio::test]
async fn runtime_mount_readwrite() {
    use bashkit::{PosixFs, RealFs, RealFsMode};
    use std::sync::Arc;

    let dir = setup_host_dir();
    let mut bash = Bash::new();

    let backend = RealFs::new(dir.path(), RealFsMode::ReadWrite).unwrap();
    let fs: Arc<dyn bashkit::FileSystem> = Arc::new(PosixFs::new(backend));
    bash.mount("/workspace", fs).unwrap();

    bash.exec("echo 'runtime write' > /workspace/runtime.txt")
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("runtime.txt")).unwrap();
    assert_eq!(content, "runtime write\n");
}