dekopon-shell 0.72.0

Sandboxed bash-flavored script interpreter whose commands dispatch to Dekopon capabilities
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
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use dekopon_process::{ExitCode, LimitExceeded};
use std::{thread, time::Duration};

use serde_json::Value;

use super::{BuiltinContext, CommandFailure, CommandResult};

pub(super) const ECHO_HELP: &str = "-n -e -E";

pub(crate) fn echo(
    _context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    let mut suppress_newline = false;
    let mut escapes = false;
    let mut words = arguments;
    // -n, -e, -E and their bundles are consumed as flags, matching busybox echo; leaving -e
    // unconsumed would print it as data, corrupting the value the script produced.
    while let Some(first) = words.first() {
        if !is_echo_flags(first) {
            break;
        }
        for flag in first.chars().skip(1) {
            match flag {
                'n' => suppress_newline = true,
                'e' => escapes = true,
                _ => escapes = false,
            }
        }
        words = &words[1..];
    }
    let joined = words.join(" ");
    let text = if escapes {
        interpret_escapes(&joined)
    } else {
        joined
    };
    let result = CommandResult::value(Value::String(text));
    Ok(if suppress_newline {
        result.without_newline()
    } else {
        result
    })
}

fn is_echo_flags(argument: &str) -> bool {
    argument.len() > 1
        && argument.starts_with('-')
        && argument
            .chars()
            .skip(1)
            .all(|flag| matches!(flag, 'n' | 'e' | 'E'))
}

fn interpret_escapes(text: &str) -> String {
    let mut output = String::with_capacity(text.len());
    let mut characters = text.chars();
    while let Some(character) = characters.next() {
        if character != '\\' {
            output.push(character);
            continue;
        }
        match characters.next() {
            Some('n') => output.push('\n'),
            Some('t') => output.push('\t'),
            Some('r') => output.push('\r'),
            Some('\\') => output.push('\\'),
            Some(other) => {
                output.push('\\');
                output.push(other);
            }
            None => output.push('\\'),
        }
    }
    output
}

pub(crate) fn printf(
    _context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    let Some((format, values)) = arguments.split_first() else {
        return Err(CommandFailure::usage(
            "printf: a format argument is required",
        ));
    };
    let rendered = format_text(format, values)?;
    Ok(CommandResult::value(Value::String(rendered)).without_newline())
}

#[allow(
    clippy::map_err_ignore,
    reason = "both discarded values are ParseFloatError over a `%d` or `%f` argument the message \
              quotes back in full; \"invalid float literal\" adds nothing to naming the operand \
              that was not a number"
)]
fn format_text(format: &str, values: &[String]) -> Result<String, CommandFailure> {
    let mut output = String::new();
    let mut next = values.iter();
    let mut characters = format.chars().peekable();

    while let Some(character) = characters.next() {
        match character {
            '\\' => match characters.next() {
                Some('n') => output.push('\n'),
                Some('t') => output.push('\t'),
                Some('r') => output.push('\r'),
                Some('\\') => output.push('\\'),
                Some(other) => {
                    output.push('\\');
                    output.push(other);
                }
                None => output.push('\\'),
            },
            '%' => match characters.next() {
                Some('%') => output.push('%'),
                Some('s') => output.push_str(next.next().map_or("", String::as_str)),
                Some('d') => {
                    let argument = next.next().map_or("0", String::as_str);
                    let number = argument.trim().parse::<f64>().map_err(|_| {
                        CommandFailure::usage(format!("printf: {argument:?} is not a number"))
                    })?;
                    output.push_str(&format!("{}", number.trunc() as i64));
                }
                Some('f') => {
                    let argument = next.next().map_or("0", String::as_str);
                    let number = argument.trim().parse::<f64>().map_err(|_| {
                        CommandFailure::usage(format!("printf: {argument:?} is not a number"))
                    })?;
                    output.push_str(&format!("{number:.6}"));
                }
                Some(other) => {
                    return Err(CommandFailure::usage(format!(
                        "printf: conversion %{other} is not supported; use %s, %d, %f, or %%"
                    )));
                }
                None => output.push('%'),
            },
            other => output.push(other),
        }
    }
    Ok(output)
}

pub(super) const TEST_HELP: &str = "! -z -n = == != < > -eq -ne -lt -le -gt -ge";

pub(crate) fn test(
    _context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    evaluate_test("test", arguments)
}

pub(crate) fn test_bracket(
    _context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    let Some((last, rest)) = arguments.split_last() else {
        return Err(CommandFailure::usage("[: missing closing `]`"));
    };
    if last != "]" {
        return Err(CommandFailure::usage("[: missing closing `]`"));
    }
    evaluate_test("[", rest)
}

/// Evaluates the curated `test` expression grammar.
///
/// File tests (`-f`, `-d`, `-e`, `-r`, `-w`, `-x`) are absent: there is no filesystem, so accepting
/// them would answer a question this shell cannot ask.
pub(crate) fn evaluate_test(
    command: &str,
    arguments: &[String],
) -> Result<CommandResult, CommandFailure> {
    // Leading !s are counted in a loop, not recursion: argv length is attacker-controlled via array
    // expansion, and one stack frame per ! could build a 20,000-deep stack and abort the process.
    let mut negations = 0usize;
    let mut arguments = arguments;
    while arguments.first().is_some_and(|first| first == "!") {
        negations += 1;
        arguments = &arguments[1..];
    }
    let negated = negations % 2 == 1;

    let truth = match arguments {
        [] => false,
        [single] => !single.is_empty(),
        [flag, operand] => match flag.as_str() {
            "-z" => operand.is_empty(),
            "-n" => !operand.is_empty(),
            "-f" | "-d" | "-e" | "-r" | "-w" | "-x" | "-s" => {
                return Err(CommandFailure::usage(format!(
                    "{command}: file test {flag} is not supported: this shell has no filesystem"
                )));
            }
            other => {
                return Err(CommandFailure::usage(format!(
                    "{command}: unary operator {other:?} is not supported"
                )));
            }
        },
        [left, operator, right] => match operator.as_str() {
            "=" | "==" => left == right,
            "!=" => left != right,
            "<" => left < right,
            ">" => left > right,
            "-eq" | "-ne" | "-lt" | "-le" | "-gt" | "-ge" => {
                let left = parse_number(command, left)?;
                let right = parse_number(command, right)?;
                match operator.as_str() {
                    "-eq" => (left - right).abs() < f64::EPSILON,
                    "-ne" => (left - right).abs() >= f64::EPSILON,
                    "-lt" => left < right,
                    "-le" => left <= right,
                    "-gt" => left > right,
                    _ => left >= right,
                }
            }
            other => {
                return Err(CommandFailure::usage(format!(
                    "{command}: binary operator {other:?} is not supported"
                )));
            }
        },
        _ => {
            return Err(CommandFailure::usage(format!(
                "{command}: expected at most three operands; combine conditions with `&&` or `||`"
            )));
        }
    };

    Ok(CommandResult::status(if truth != negated {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }))
}

#[allow(
    clippy::map_err_ignore,
    reason = "ParseFloatError has one meaning, \"not a float literal\", over an operand the \
              message quotes back in full"
)]
fn parse_number(command: &str, text: &str) -> Result<f64, CommandFailure> {
    text.trim()
        .parse::<f64>()
        .map_err(|_| CommandFailure::usage(format!("{command}: {text:?} is not a number")))
}

pub(crate) fn succeed(
    _context: &mut BuiltinContext<'_>,
    _arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    Ok(CommandResult::status(ExitCode::SUCCESS))
}

pub(crate) fn fail(
    _context: &mut BuiltinContext<'_>,
    _arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    Ok(CommandResult::status(ExitCode::FAILURE))
}

pub(crate) fn progress(
    context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    let mut text = None;
    let mut eta = None;
    let mut has_eta = false;
    let mut arguments = arguments.iter();
    while let Some(argument) = arguments.next() {
        if argument == "--eta" {
            if has_eta {
                return Err(CommandFailure::usage(
                    "progress: --eta may appear only once",
                ));
            }
            has_eta = true;
            let seconds = arguments
                .next()
                .ok_or_else(|| CommandFailure::usage("progress: --eta requires seconds"))?;
            if seconds == "--eta" {
                return Err(CommandFailure::usage(
                    "progress: --eta may appear only once",
                ));
            }
            eta = seconds
                .parse::<u32>()
                .ok()
                .filter(|seconds| (1..=3600).contains(seconds))
                .map(|seconds| Duration::from_secs(u64::from(seconds)));
        } else if text.replace(argument.as_str()).is_some() {
            return Err(CommandFailure::usage(
                "progress: exactly one text operand is required; quote the text",
            ));
        }
    }
    let text = text.ok_or_else(|| {
        CommandFailure::usage("progress: exactly one text operand is required; quote the text")
    })?;
    context.invoker.note(text, eta);
    Ok(CommandResult::status(ExitCode::SUCCESS))
}

pub(crate) fn sleep(
    context: &mut BuiltinContext<'_>,
    arguments: &[String],
    _input: Option<Value>,
) -> Result<CommandResult, CommandFailure> {
    let [seconds] = arguments else {
        return Err(CommandFailure::usage(
            "sleep: exactly one duration in seconds is required",
        ));
    };
    #[allow(
        clippy::map_err_ignore,
        reason = "ParseFloatError has one meaning, \"not a float literal\", over an operand \
                  the message quotes back in full; the range and finiteness checks that \
                  follow are what carry the interesting rejections"
    )]
    let seconds = seconds.trim().parse::<f64>().map_err(|_| {
        CommandFailure::usage(format!("sleep: {seconds:?} is not a number of seconds"))
    })?;
    if !seconds.is_finite() || seconds < 0.0 {
        return Err(CommandFailure::usage(
            "sleep: the duration must be a finite, non-negative number of seconds",
        ));
    }

    // Sleep is capped by the remaining deadline; the fallible duration conversion is deliberate
    // since it panics above roughly 1.8e19 seconds, and an astronomical sleep must not abort
    // the process.
    let requested = Duration::try_from_secs_f64(seconds).unwrap_or(Duration::MAX);
    let mut left = requested;
    loop {
        if context.budget.tree().is_cancelled() {
            return Err(LimitExceeded::Cancelled.into());
        }
        context.budget.check_deadline()?;
        if left.is_zero() {
            break;
        }
        let slice = left
            .min(context.budget.remaining())
            .min(Duration::from_secs(1));
        thread::sleep(slice);
        left = left.saturating_sub(slice);
    }
    Ok(CommandResult::status(ExitCode::SUCCESS))
}

pub(crate) fn cat_stream(
    arguments: &[String],
    mut emit: impl FnMut(&str) -> Result<bool, CommandFailure>,
) -> Result<(), CommandFailure> {
    for name in arguments {
        if name.starts_with('-') && name.len() > 1 {
            return Err(CommandFailure::usage(format!(
                "cat: unsupported flag {name}"
            )));
        }
        if !emit(name)? {
            break;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use dekopon_process::ExitCode;
    use parking_lot::Mutex;
    use std::{sync::Arc, time::Duration};

    use serde_json::{Value, json};

    use crate::{
        CapabilityCallResult, CapabilityInvoker, Interpreter,
        builtins::{
            CommandFailure,
            test_support::{cat as Cat, run_builtin, run_builtin_with, run_builtin_with_invoker},
        },
    };
    use dekopon_process::Limits;

    use super::{
        echo as Echo, fail as False, printf as Printf, progress as Progress, sleep as Sleep,
        succeed as True, test as Test, test_bracket as TestBracket,
    };

    #[derive(Default)]
    struct Notes(Mutex<Vec<(String, Option<Duration>)>>);

    impl CapabilityInvoker for Notes {
        fn granted(&self) -> Vec<String> {
            Vec::new()
        }

        fn invoke(
            &self,
            _: crate::CommandProposal,
            _streams: crate::Streams,
            _tree: &dekopon_process::TreeContext,
        ) -> CapabilityCallResult {
            panic!("progress must not invoke a capability")
        }

        fn note(&self, text: &str, eta: Option<Duration>) {
            self.0.lock().push((text.to_owned(), eta));
        }
    }

    #[test]
    fn progress_passes_raw_text_and_eta_in_either_order_through_an_arc() {
        let notes = Arc::new(Notes::default());
        for arguments in [
            vec![" <@rendering> ", "--eta", "40"],
            vec!["--eta", "40", " <@rendering> "],
        ] {
            let result = run_builtin_with_invoker(Progress, &arguments, &notes).unwrap();
            assert_eq!(result.status, ExitCode::SUCCESS);
            assert_eq!(result.value, Value::Null);
        }
        assert_eq!(
            *notes.0.lock(),
            vec![(" <@rendering> ".to_owned(), Some(Duration::from_secs(40))); 2]
        );
    }

    #[test]
    fn progress_ignores_invalid_eta_without_rejecting_the_note() {
        let notes = Notes::default();
        for seconds in ["0", "3601", "-5", "4.5", "soon"] {
            let result =
                run_builtin_with_invoker(Progress, &["x", "--eta", seconds], &notes).unwrap();
            assert_eq!(result.status, ExitCode::SUCCESS);
        }
        assert_eq!(*notes.0.lock(), vec![("x".to_owned(), None); 5]);
    }

    #[test]
    fn malformed_progress_never_reaches_the_invoker() {
        let notes = Notes::default();
        for arguments in [
            vec![],
            vec!["two", "words"],
            vec!["x", "--eta"],
            vec!["--eta", "--eta", "x"],
            vec!["--eta", "1", "x", "--eta", "2"],
        ] {
            assert!(matches!(
                run_builtin_with_invoker(Progress, &arguments, &notes),
                Err(CommandFailure::Status {
                    status: ExitCode::SYNTAX,
                    ..
                })
            ));
        }
        assert!(notes.0.lock().is_empty());
    }

    #[test]
    fn progress_adds_no_script_output() {
        let notes = Notes::default();
        let result = Interpreter::new(Limits::default(), crate::test_threads())
            .run("progress \"x\"; echo done", &notes);
        assert_eq!(result.exit_code, ExitCode::SUCCESS);
        assert_eq!(result.output, "done");
        assert_eq!(result.capability_calls, 0);
        assert_eq!(*notes.0.lock(), vec![("x".to_owned(), None)]);
    }

    #[test]
    fn echo_joins_arguments_with_spaces() {
        let result = run_builtin(Echo, &["a", "b"], None).expect("echo runs");
        assert_eq!(result.value, json!("a b"));
        assert!(!result.suppress_newline);
        assert!(
            run_builtin(Echo, &["-n", "a"], None)
                .expect("echo runs")
                .suppress_newline
        );
    }

    #[test]
    fn echo_consumes_its_flag_bundles_instead_of_printing_them() {
        assert_eq!(
            run_builtin(Echo, &["-e", "a\\nb"], None)
                .expect("echo runs")
                .value,
            json!("a\nb")
        );
        assert_eq!(
            run_builtin(Echo, &["-E", "a\\nb"], None)
                .expect("echo runs")
                .value,
            json!("a\\nb")
        );
        let bundled = run_builtin(Echo, &["-ne", "a\\tb"], None).expect("echo runs");
        assert_eq!(bundled.value, json!("a\tb"));
        assert!(bundled.suppress_newline);
        assert_eq!(
            run_builtin(Echo, &["-x", "a"], None)
                .expect("echo runs")
                .value,
            json!("-x a")
        );
    }

    #[test]
    fn printf_renders_the_curated_conversions() {
        assert_eq!(
            run_builtin(Printf, &["%s=%d\\n", "count", "7"], None)
                .expect("printf runs")
                .value,
            json!("count=7\n")
        );
        assert_eq!(
            run_builtin(Printf, &["%f", "1.5"], None)
                .expect("printf runs")
                .value,
            json!("1.500000")
        );
        assert_eq!(
            run_builtin(Printf, &["100%%"], None)
                .expect("printf runs")
                .value,
            json!("100%")
        );
        assert!(run_builtin(Printf, &["%q", "x"], None).is_err());
    }

    #[test]
    fn test_evaluates_string_and_numeric_comparisons() {
        let status = |arguments: &[&str]| {
            run_builtin(Test, arguments, None)
                .expect("test runs")
                .status
        };
        assert_eq!(status(&["-z", ""]), ExitCode::SUCCESS);
        assert_eq!(status(&["-n", ""]), ExitCode::FAILURE);
        assert_eq!(status(&["a", "=", "a"]), ExitCode::SUCCESS);
        assert_eq!(status(&["a", "!=", "a"]), ExitCode::FAILURE);
        assert_eq!(status(&["2", "-gt", "1"]), ExitCode::SUCCESS);
        assert_eq!(status(&["2", "-le", "1"]), ExitCode::FAILURE);
        assert_eq!(status(&["!", "-z", "x"]), ExitCode::SUCCESS);
    }

    #[test]
    fn stacked_negations_are_counted_not_recursed() {
        let status = |arguments: &[&str]| {
            run_builtin(Test, arguments, None)
                .expect("test runs")
                .status
        };
        assert_eq!(status(&["!", "!", "-n", "x"]), ExitCode::SUCCESS);
        assert_eq!(status(&["!", "!", "!", "-n", "x"]), ExitCode::FAILURE);

        let bangs = vec!["!"; 50_000];
        let mut arguments = bangs.clone();
        arguments.extend(["-n", "x"]);
        assert_eq!(status(&arguments), ExitCode::SUCCESS);
    }

    #[test]
    fn bracket_requires_its_closing_bracket() {
        assert_eq!(
            run_builtin(TestBracket, &["a", "=", "a", "]"], None)
                .expect("[ runs")
                .status,
            ExitCode::SUCCESS
        );
        assert!(run_builtin(TestBracket, &["a", "=", "a"], None).is_err());
    }

    #[test]
    fn file_tests_are_rejected_because_there_is_no_filesystem() {
        let failure = run_builtin(Test, &["-f", "/etc/passwd"], None)
            .expect_err("file tests are not supported");
        let CommandFailure::Status { message, .. } = failure else {
            panic!("a file test must stay recoverable");
        };
        assert!(message.contains("no filesystem"), "{message}");
    }

    #[test]
    fn true_and_false_carry_their_conventional_statuses() {
        assert_eq!(
            run_builtin(True, &[], None).expect("true runs").status,
            ExitCode::SUCCESS
        );
        assert_eq!(
            run_builtin(False, &[], None).expect("false runs").status,
            ExitCode::FAILURE
        );
    }

    #[test]
    fn sleep_is_capped_by_the_remaining_deadline() {
        let limits = Limits {
            timeout: Duration::from_millis(30),
            ..Limits::default()
        };
        let started = std::time::Instant::now();
        let failure = run_builtin_with(Sleep, &["30"], None, limits)
            .expect_err("an oversized sleep trips the deadline");
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "sleep was not capped"
        );
        assert!(matches!(failure, CommandFailure::Fatal(_)));
    }

    #[test]
    fn sleep_rejects_malformed_durations() {
        assert!(run_builtin(Sleep, &["soon"], None).is_err());
        assert!(run_builtin(Sleep, &["-1"], None).is_err());
        assert!(run_builtin(Sleep, &[], None).is_err());
    }

    #[test]
    fn an_astronomical_sleep_is_clamped_rather_than_panicking() {
        let limits = Limits {
            timeout: Duration::from_millis(20),
            ..Limits::default()
        };
        for duration in ["1e30", "99999999999999999999", "1e300"] {
            let started = std::time::Instant::now();
            let failure = run_builtin_with(Sleep, &[duration], None, limits)
                .expect_err("an oversized sleep trips the deadline");
            assert!(matches!(failure, CommandFailure::Fatal(_)), "{duration}");
            assert!(started.elapsed() < Duration::from_secs(5), "{duration}");
        }
    }

    #[test]
    fn cat_without_arguments_preserves_input() {
        let result =
            run_builtin_with(Cat, &[], Some(json!("hi")), Limits::default()).expect("cat runs");
        assert_eq!(result.value, json!("hi"));
    }
}