bashkit 0.20.1

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
//! Shell diagnostics carry bash's non-interactive `$0: line N: ` prefix.
//!
//! Standard diagnostic expectations were checked against real bash 5.2 running the
//! same text as `bash SCRIPT` (so `$0` is `SCRIPT`) or `bash -c '...'` (so
//! `$0` is `bash`). Coreutils-style builtins are external programs in bash and
//! keep their own `cat: ...` form; usage lines stay unprefixed. Resource tests
//! also cover the intentional diagnostic-name cap and shared execution budget.

use bashkit::{Bash, ExecOptions};
use std::sync::{Arc, Mutex};

/// Run `script` the way `bash SCRIPT` would: `$0` is `SCRIPT`.
async fn run_script(script: &str) -> (String, i32) {
    let mut bash = Bash::new();
    let r = bash
        .exec_with_options(script, ExecOptions::new().arg0("SCRIPT"))
        .await
        .unwrap();
    (r.stderr.to_string(), r.exit_code)
}

/// Run `script` the way `bash -c` would: `$0` is the default `bash`.
async fn run_c(script: &str) -> (String, i32) {
    let mut bash = Bash::new();
    let r = bash.exec(script).await.unwrap();
    (r.stderr.to_string(), r.exit_code)
}

#[tokio::test]
async fn command_not_found_in_script_file() {
    let (err, code) = run_script("echo a >/dev/null\ncomando\n").await;
    assert_eq!(err, "SCRIPT: line 2: comando: command not found\n");
    assert_eq!(code, 127);
}

#[tokio::test]
async fn command_not_found_in_dash_c() {
    let (err, code) = run_c("comando").await;
    assert_eq!(err, "bash: line 1: comando: command not found\n");
    assert_eq!(code, 127);
}

#[tokio::test]
async fn missing_absolute_path_command() {
    let (err, code) = run_script("\n/abs/missing\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 2: /abs/missing: No such file or directory\n"
    );
    assert_eq!(code, 127);
}

#[tokio::test]
async fn input_redirect_failure() {
    let (err, code) = run_script("cat < dados.txt\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 1: dados.txt: No such file or directory\n"
    );
    assert_eq!(code, 1);
}

#[tokio::test]
async fn mapfile_redirect_failure() {
    let (err, _) = run_script("mapfile -t a < dados.txt\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 1: dados.txt: No such file or directory\n"
    );
}

#[tokio::test]
async fn readonly_assignment() {
    let (err, code) = run_script("readonly ro=1\nro=2\n").await;
    assert_eq!(err, "SCRIPT: line 2: ro: readonly variable\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn declare_p_missing() {
    let (err, code) = run_script("declare -p naoexiste\n").await;
    assert_eq!(err, "SCRIPT: line 1: declare: naoexiste: not found\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn source_missing_file_has_prefix_and_newline() {
    let (err, code) = run_script("echo 1 >/dev/null\n. ./lib.sh\necho after >&2\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 2: ./lib.sh: No such file or directory\nafter\n"
    );
    assert_eq!(code, 0);
    let (err, _) = run_script("source ./lib.sh\n").await;
    assert_eq!(err, "SCRIPT: line 1: ./lib.sh: No such file or directory\n");
}

#[tokio::test]
async fn source_without_argument() {
    let (err, code) = run_script("source\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 1: source: filename argument required\n\
         source: usage: source filename [arguments]\n"
    );
    assert_eq!(code, 2);
}

#[tokio::test]
async fn nounset_error() {
    let (err, code) = run_script("set -u\necho $naodefinida\n").await;
    assert_eq!(err, "SCRIPT: line 2: naodefinida: unbound variable\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn param_error_if_unset_message() {
    let (err, code) = run_script("\necho ${obrigatorio:?precisa definir}\n").await;
    assert_eq!(err, "SCRIPT: line 2: obrigatorio: precisa definir\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn error_inside_function_reports_line_of_failing_command() {
    let (err, code) = run_script("f() {\n  echo in >/dev/null\n  nocmd\n}\nf\n").await;
    assert_eq!(err, "SCRIPT: line 3: nocmd: command not found\n");
    assert_eq!(code, 127);
}

#[tokio::test]
async fn eval_syntax_error_uses_dollar_zero() {
    let (err, code) = run_script("\neval 'echo \"x'\n").await;
    assert!(err.starts_with("SCRIPT: eval: line 2: "), "{err}");
    for line in err.lines() {
        assert!(line.starts_with("SCRIPT: eval: line 2: "), "{err}");
    }
    assert_eq!(code, 2);
}

#[tokio::test]
async fn type_not_found_in_dash_c() {
    let (err, code) = run_c("type h").await;
    assert_eq!(err, "bash: line 1: type: h: not found\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn builtin_usage_line_stays_unprefixed() {
    let (err, code) = run_c("umask -x").await;
    assert_eq!(
        err,
        "bash: line 1: umask: -x: invalid option\numask: usage: umask [-p] [-S] [mode]\n"
    );
    assert_eq!(code, 2);
}

#[tokio::test]
async fn shell_builtin_without_bash_tag_gets_prefix() {
    let (err, code) = run_script("\ncd /nonexist\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 2: cd: /nonexist: No such file or directory\n"
    );
    assert_eq!(code, 1);
}

#[tokio::test]
async fn arithmetic_error_uses_dollar_zero() {
    let (err, code) = run_script("echo $((1/0))\n").await;
    assert_eq!(
        err,
        "SCRIPT: line 1: 1/0: division by 0 (error token is \"0\")\n"
    );
    assert_eq!(code, 1);
}

#[tokio::test]
async fn coreutils_builtin_stays_unprefixed() {
    let (err, code) = run_script("cat missing\n").await;
    assert_eq!(err, "cat: missing: No such file or directory\n");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn child_shell_reports_its_own_name_and_line() {
    let (err, code) = run_script("\nbash -c 'nocmd'\n").await;
    assert_eq!(err, "bash: line 1: nocmd: command not found\n");
    assert_eq!(code, 127);
}

#[tokio::test]
async fn sourced_file_reports_its_own_path_and_line() {
    let mut bash = Bash::new();
    bash.exec("printf 'echo in >/dev/null\\nnocmd\\n' > /tmp/lib.sh")
        .await
        .unwrap();
    let r = bash
        .exec_with_options(
            "\n\nsource /tmp/lib.sh\n",
            ExecOptions::new().arg0("SCRIPT"),
        )
        .await
        .unwrap();
    assert_eq!(r.stderr, "/tmp/lib.sh: line 2: nocmd: command not found\n");
}

#[tokio::test]
async fn streaming_callback_sees_prefixed_text() {
    let seen: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
    let seen_cb = seen.clone();
    let mut bash = Bash::new();
    bash.exec_with_options(
        "echo a\nnocmd\n",
        ExecOptions::new()
            .arg0("SCRIPT")
            .streaming(Box::new(move |_stdout, stderr| {
                seen_cb.lock().unwrap().push_str(stderr);
            })),
    )
    .await
    .unwrap();
    assert_eq!(
        *seen.lock().unwrap(),
        "SCRIPT: line 2: nocmd: command not found\n"
    );
}

#[tokio::test]
async fn interactive_mode_keeps_bare_prefix() {
    let mut bash = Bash::new();
    bash.set_interactive(true);
    let r = bash.exec("nocmd").await.unwrap();
    assert_eq!(r.stderr, "bash: nocmd: command not found\n");
}

// --- Arithmetic diagnostics stay inside the diagnostic budget (TM-INF-022) ---
//
// `$(( ))` echoes two attacker-controlled fragments into one line: the whole
// expression, and the unparsed rest as the "error token". Both were unbounded,
// so one bounded expression produced a diagnostic about twice its size.
// `arithmetic_fuzz` (nightly fuzz run 270) found a 507-byte expression that
// rendered 1,076 bytes of stderr, over the 1 KiB cap
// `bashkit::testing::assert_no_leak` holds every builtin to.

/// Same cap as `bashkit::testing::MAX_STDERR_BYTES`.
const MAX_DIAG: usize = 1024;

/// The reduced `arithmetic_fuzz` crash. The rejected `#` sits near the front,
/// so the unparsed rest -- the "error token" -- is nearly as long as the
/// expression echoed before it. That doubling is what went over the cap.
fn long_bad_expression() -> String {
    format!("~#{}", "~".repeat(500))
}

#[tokio::test]
async fn long_arithmetic_expansion_diagnostic_is_bounded() {
    let (err, code) = run_c(&format!("echo $(({}))", long_bad_expression())).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    // Truncation keeps the part that says what went wrong.
    assert!(err.starts_with("bash: line 1: "), "{err}");
    assert!(err.contains("syntax error"), "{err}");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn long_arithmetic_command_diagnostic_is_bounded() {
    let (err, code) = run_c(&format!("(({}))", long_bad_expression())).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    assert!(err.contains("syntax error"), "{err}");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn long_let_diagnostic_is_bounded() {
    let (err, code) = run_c(&format!("let '{}'", long_bad_expression())).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    assert!(err.contains("syntax error"), "{err}");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn long_cond_arithmetic_diagnostic_is_bounded() {
    let (err, _) = run_c(&format!("[[ {} -eq 1 ]]", long_bad_expression())).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    assert!(err.contains("syntax error"), "{err}");
}

#[tokio::test]
async fn long_division_by_zero_diagnostic_is_bounded() {
    // The error token here is the right-hand side, echoed from the source.
    let (err, code) = run_c(&format!("echo $((1/(0{}) ))", "+0".repeat(400))).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    assert!(err.contains("division by 0"), "{err}");
    assert_eq!(code, 1);
}

#[tokio::test]
async fn long_bad_number_diagnostic_is_bounded() {
    let (err, code) = run_c(&format!("echo $((1{}x))", "9".repeat(600))).await;
    assert!(
        err.len() <= MAX_DIAG,
        "stderr is {} bytes:\n{err}",
        err.len()
    );
    assert_eq!(code, 1);
}

#[tokio::test]
async fn short_arithmetic_diagnostics_are_not_truncated() {
    // The common case stays byte for byte with bash 5.2.
    let (err, code) = run_c("echo $((1/0))").await;
    assert_eq!(
        err,
        "bash: line 1: 1/0: division by 0 (error token is \"0\")\n"
    );
    assert_eq!(code, 1);

    let (err, code) = run_c("echo $((1/(0+0)))").await;
    assert_eq!(
        err,
        "bash: line 1: 1/(0+0): division by 0 (error token is \"(0+0)\")\n"
    );
    assert_eq!(code, 1);

    // An expression under the cap is still echoed whole, with no marker.
    let expr = format!("{}#x", "~".repeat(100));
    let (err, _) = run_c(&format!("echo $(({expr}))")).await;
    assert!(err.contains(&expr), "{err}");
    assert!(!err.contains("..."), "{err}");
}

/// Small-budget reproduction: the original stderr fits; repeating $0 does not.
#[tokio::test]
async fn diagnostic_prefix_amplification_hits_shared_memory_budget() {
    for (redirect, streaming) in [
        ("", false),
        ("", true),
        (" 2>/tmp/diagnostics", true),
        (" 2>&1", true),
        (" 2>/dev/null", true),
    ] {
        let mut bash = Bash::builder()
            .limits(
                bashkit::ExecutionLimits::new()
                    .timeout(std::time::Duration::from_secs(600))
                    .max_live_intermediate_bytes(8192)
                    .max_stderr_bytes(64),
            )
            .build();
        let seen = Arc::new(Mutex::new(String::new()));
        let seen_cb = seen.clone();
        let script = format!(
            "bash -c 'unalias {{1..100}}' '{}'{}",
            "x".repeat(128),
            redirect
        );
        let options = if streaming {
            ExecOptions::new().streaming(Box::new(move |stdout, stderr| {
                let mut seen = seen_cb.lock().unwrap();
                seen.push_str(stdout);
                seen.push_str(stderr);
            }))
        } else {
            ExecOptions::new()
        };
        let error = bash
            .exec_with_options(&script, options)
            .await
            .expect_err("prefix amplification must fail before routing or capture");
        assert!(
            error.to_string().contains("live intermediate"),
            "{redirect}: {error}"
        );
        assert!(seen.lock().unwrap().is_empty());
        let recovered = bash.exec("echo recovered").await.unwrap();
        assert_eq!(recovered.stdout, "recovered\n");
    }
}

#[tokio::test]
async fn diagnostic_name_is_bounded_utf8_without_changing_arg0() {
    let name = "€".repeat(400);
    let mut bash = Bash::new();
    let script = format!("bash -c 'echo ${{#0}}; unalias absent' '{name}'");
    let result = bash.exec(&script).await.unwrap();
    assert_eq!(result.stdout, "400\n");
    assert_eq!(
        result.stderr,
        format!("{}: line 1: unalias: absent: not found\n", "€".repeat(341))
    );
}

/// Replace the `line N` counter with `line N*` so oracle comparisons hold
/// across bash versions: bash 5.x numbers `bash -c` text from line 1 while the
/// macOS bash 3.2 oracle numbers it from line 0. Our own output stays pinned
/// to the bash 5.2 contract asserted below.
fn normalize_line_numbers(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(idx) = rest.find("line ") {
        let (head, tail) = rest.split_at(idx);
        out.push_str(head);
        let digits = tail[5..].chars().take_while(char::is_ascii_digit).count();
        if digits == 0 {
            out.push_str("line ");
            rest = &tail[5..];
        } else {
            out.push_str("line N*");
            rest = &tail[5 + digits..];
        }
    }
    out.push_str(rest);
    out
}

#[tokio::test]
async fn diagnostic_prefix_matches_bash_and_redirect_keeps_full_output() {
    let name = "child".repeat(24);
    let body = "unalias first second third";
    let oracle = std::process::Command::new("bash")
        .env_clear()
        .env("PATH", std::env::var_os("PATH").unwrap_or_default())
        .args(["-c", body, &name])
        .output()
        .unwrap();
    let script = format!("bash -c '{body}' '{name}'");
    let mut bash = Bash::builder()
        .limits(bashkit::ExecutionLimits::new().max_live_intermediate_bytes(8192))
        .build();
    let result = bash.exec(&script).await.unwrap();
    let stderr = String::from_utf8_lossy(result.stderr.as_bytes()).into_owned();
    let line1 = format!("{name}: line 1: unalias: ");
    let expected = line1.clone()
        + "first: not found\n"
        + &line1
        + "second: not found\n"
        + &line1
        + "third: not found\n";
    assert_eq!(stderr, expected);
    assert_eq!(
        normalize_line_numbers(&stderr),
        normalize_line_numbers(&String::from_utf8_lossy(&oracle.stderr))
    );
    assert_eq!(result.stdout.as_bytes(), oracle.stdout);
    assert_eq!(Some(result.exit_code), oracle.status.code());

    let mut bash = Bash::builder()
        .limits(
            bashkit::ExecutionLimits::new()
                .max_live_intermediate_bytes(8192)
                .max_stderr_bytes(64),
        )
        .build();
    // Redirect the builtin before the child captures stderr. An outer
    // redirect receives the child's already capped capture.
    let result = bash
        .exec(&format!(
            "bash -c '{body} 2>/tmp/diagnostics' '{name}'; cat /tmp/diagnostics"
        ))
        .await
        .unwrap();
    assert!(result.stderr.is_empty());
    let stdout = String::from_utf8_lossy(result.stdout.as_bytes()).into_owned();
    assert_eq!(stdout, expected);
    assert_eq!(
        normalize_line_numbers(&stdout),
        normalize_line_numbers(&String::from_utf8_lossy(&oracle.stderr))
    );
}