dekopon-shell 0.30.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
use std::collections::BTreeMap;

use serde_json::Value;

use crate::{
    CapabilityCallResult, CapabilityInvoker, ExitCode,
    limits::{Budget, LimitExceeded},
};

pub(crate) mod cap;
pub(crate) mod encode;
pub(crate) mod jobs;
pub(crate) mod jq;
pub(crate) mod misc;
pub(crate) mod text;
pub(crate) mod xargs;

#[derive(Debug)]
pub(crate) struct CommandResult {
    pub value: Value,
    pub status: ExitCode,
    pub suppress_newline: bool,
    pub retained: Vec<crate::RetainedBytes>,
}

impl CommandResult {
    pub(crate) fn value(value: Value) -> Self {
        Self {
            value,
            status: ExitCode::SUCCESS,
            suppress_newline: false,
            retained: Vec::new(),
        }
    }

    pub(crate) fn status(status: ExitCode) -> Self {
        Self {
            value: Value::Null,
            status,
            suppress_newline: false,
            retained: Vec::new(),
        }
    }

    pub(crate) fn without_newline(mut self) -> Self {
        self.suppress_newline = true;
        self
    }

    pub(crate) fn lines(lines: Vec<String>) -> Self {
        if lines.is_empty() {
            return Self::status(ExitCode::SUCCESS);
        }
        Self::value(Value::String(lines.join("\n")))
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum CommandFailure {
    Status { message: String, status: ExitCode },
    Fatal(FatalError),
}

impl CommandFailure {
    pub(crate) fn usage(message: impl Into<String>) -> Self {
        Self::Status {
            message: message.into(),
            status: ExitCode::SYNTAX,
        }
    }

    pub(crate) fn failed(message: impl Into<String>) -> Self {
        Self::Status {
            message: message.into(),
            status: ExitCode::FAILURE,
        }
    }
}

impl From<LimitExceeded> for CommandFailure {
    fn from(limit: LimitExceeded) -> Self {
        Self::Fatal(FatalError::Limit(limit))
    }
}

impl From<LimitExceeded> for FatalError {
    fn from(limit: LimitExceeded) -> Self {
        Self::Limit(limit)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum FatalError {
    Limit(LimitExceeded),
    Unsupported(String),
    /// Terminal rather than recoverable, because that is the point of the construct: reporting a
    /// status and continuing with an empty string would be exactly the silent wrongness this shell
    /// exists to refuse.
    Assertion(String),
}

pub(crate) struct BuiltinContext<'a> {
    pub invoker: &'a dyn CapabilityInvoker,
    pub budget: &'a mut Budget,
    /// These are named in-memory buffers only, written by redirects; a lookup here must never touch
    /// a real filesystem path.
    pub buffers: &'a BTreeMap<String, Vec<u8>>,
    pub started_jobs: &'a [crate::JobId],
}

impl BuiltinContext<'_> {
    /// Capability calls are wall-clock expensive but step-cheap (the default budget allows 32 in 96
    /// steps), so the deadline is re-read on both sides; step-counting alone let a script overrun
    /// its deadline by minutes.
    pub(crate) fn invoke_proposal(
        &mut self,
        proposal: crate::CommandProposal,
    ) -> Result<CommandResult, CommandFailure> {
        self.budget.charge_capability_call()?;
        self.budget.check_deadline()?;
        let capability = proposal.capability.clone();
        let result = self.invoker.invoke(proposal);
        self.budget.check_deadline()?;
        let status = ExitCode::from_capability_result(&result);
        Ok(match result {
            CapabilityCallResult::Succeeded(output) => CommandResult {
                value: output,
                status,
                suppress_newline: false,
                retained: Vec::new(),
            },
            CapabilityCallResult::Denied { reason } => {
                return Err(CommandFailure::Status {
                    message: format!("{capability}: denied: {reason}"),
                    status,
                });
            }
            CapabilityCallResult::Failed { error, detail } => {
                let message = match detail {
                    Some(detail) => format!("{capability}: failed: {error}: {detail}"),
                    None => format!("{capability}: failed: {error}"),
                };
                return Err(CommandFailure::Status { message, status });
            }
            CapabilityCallResult::NotFound => {
                return Err(CommandFailure::Status {
                    message: format!("{capability}: capability not found"),
                    status,
                });
            }
        })
    }
}

pub(crate) trait Builtin {
    fn name(&self) -> &'static str;

    fn help(&self) -> &'static str;

    fn copies_stdin(&self) -> bool {
        false
    }

    fn run(
        &self,
        context: &mut BuiltinContext<'_>,
        arguments: &[String],
        input: Option<Value>,
    ) -> Result<CommandResult, CommandFailure>;
}

#[derive(Clone, Copy)]
pub(crate) enum BuiltinKind {
    Simple(&'static dyn Builtin),
    Lines(text::lines::LineCommand),
    TextStream(text::stream::TextStream),
    Extra(text::extra::ExtraStream),
    Base64,
    Jq,
    Xargs,
}

const REGISTRY: &[&dyn Builtin] = &[
    &jobs::Jobs,
    &jobs::Wait,
    &jobs::Kill,
    &misc::Sleep,
    &misc::Progress,
    &misc::Echo,
    &misc::Printf,
    &misc::Test,
    &misc::TestBracket,
    &misc::True,
    &misc::False,
    &misc::Cat,
    &cap::Cap,
];

pub(crate) fn lookup(name: &str) -> Option<BuiltinKind> {
    if let Some(command) = text::lines::LineCommand::lookup(name) {
        return Some(BuiltinKind::Lines(command));
    }
    if let Some(command) = match name {
        "grep" => Some(text::stream::TextStream::Grep),
        "sed" => Some(text::stream::TextStream::Sed),
        _ => None,
    } {
        return Some(BuiltinKind::TextStream(command));
    }
    if let Some(command) = match name {
        "cut" => Some(text::extra::ExtraStream::Cut),
        "uniq" => Some(text::extra::ExtraStream::Uniq),
        "wc" => Some(text::extra::ExtraStream::Wc),
        "sort" => Some(text::extra::ExtraStream::Sort),
        _ => None,
    } {
        return Some(BuiltinKind::Extra(command));
    }
    if name == "jq" {
        return Some(BuiltinKind::Jq);
    }
    if name == "base64" {
        return Some(BuiltinKind::Base64);
    }
    if name == xargs::NAME {
        return Some(BuiltinKind::Xargs);
    }
    REGISTRY
        .iter()
        .find(|builtin| builtin.name() == name)
        .map(|builtin| BuiltinKind::Simple(*builtin))
}

#[cfg(test)]
pub(crate) fn names() -> Vec<&'static str> {
    let mut names = REGISTRY
        .iter()
        .map(|builtin| builtin.name())
        .collect::<Vec<_>>();
    names.extend([
        "head", "tail", "base64", "grep", "sed", "cut", "uniq", "wc", "sort", "jq",
    ]);
    names.push(xargs::NAME);
    names.sort_unstable();
    names
}

pub(crate) fn unsupported_flag(command: &str, flag: &str, supported: &str) -> CommandFailure {
    let suffix = if supported.is_empty() {
        String::new()
    } else {
        format!(" (supported: {supported})")
    };
    CommandFailure::usage(format!(
        "{command}: option not yet supported: {flag}{suffix}"
    ))
}

pub(crate) fn help_result(name: &str, help: &str) -> CommandResult {
    let help = if help.is_empty() { "no flags" } else { help };
    CommandResult::value(Value::String(format!("{name}: {help}")))
}

#[cfg(test)]
pub(crate) mod test_support {

    use std::collections::BTreeMap;

    use serde_json::Value;

    use crate::{
        CapabilityCallResult, CapabilityInvoker,
        limits::{Budget, Limits},
    };

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

    pub(crate) struct NoCapabilities;

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

        fn invoke(&self, _: crate::CommandProposal) -> CapabilityCallResult {
            CapabilityCallResult::NotFound
        }
    }

    pub(crate) fn run_builtin(
        builtin: &dyn Builtin,
        arguments: &[&str],
        input: Option<Value>,
    ) -> Result<CommandResult, CommandFailure> {
        let mut buffers = BTreeMap::new();
        run_builtin_with(builtin, arguments, input, Limits::default(), &mut buffers)
    }

    pub(crate) fn run_builtin_with_invoker(
        builtin: &dyn Builtin,
        arguments: &[&str],
        invoker: &dyn CapabilityInvoker,
    ) -> Result<CommandResult, CommandFailure> {
        let mut budget = Budget::start(Limits::default());
        let mut buffers = BTreeMap::new();
        let mut context = BuiltinContext {
            invoker,
            budget: &mut budget,
            buffers: &mut buffers,
            started_jobs: &[],
        };
        let arguments = arguments
            .iter()
            .map(|argument| (*argument).to_owned())
            .collect::<Vec<_>>();
        builtin.run(&mut context, &arguments, None)
    }

    pub(crate) fn run_builtin_with(
        builtin: &dyn Builtin,
        arguments: &[&str],
        input: Option<Value>,
        limits: Limits,
        buffers: &mut BTreeMap<String, Vec<u8>>,
    ) -> Result<CommandResult, CommandFailure> {
        let invoker = NoCapabilities;
        let mut budget = Budget::start(limits);
        let mut context = BuiltinContext {
            invoker: &invoker,
            budget: &mut budget,
            buffers,
            started_jobs: &[],
        };
        let arguments = arguments
            .iter()
            .map(|argument| (*argument).to_owned())
            .collect::<Vec<_>>();
        builtin.run(&mut context, &arguments, input)
    }
}

#[cfg(test)]
mod tests {
    use crate::{CapabilityCallResult, CapabilityInvoker, ExitCode, Interpreter, Limits};

    use super::{lookup, names, test_support::NoCapabilities, xargs};

    #[test]
    fn the_registry_covers_every_documented_builtin() {
        let expected = [
            "[",
            "base64",
            "cap",
            "cat",
            "cut",
            "echo",
            "false",
            "grep",
            "head",
            "jobs",
            "jq",
            "kill",
            "printf",
            "progress",
            "sed",
            "sleep",
            "sort",
            "tail",
            "test",
            "true",
            "uniq",
            "wait",
            "wc",
            xargs::NAME,
        ];
        let mut expected = expected.to_vec();
        expected.sort_unstable();
        assert_eq!(names(), expected);
        for name in expected {
            assert!(lookup(name).is_some(), "{name} must resolve");
        }
        assert!(lookup("definitely-not-a-builtin").is_none());
    }

    #[test]
    fn every_builtin_answers_help_at_exit_zero_before_its_own_usage_rules_apply() {
        for name in names() {
            let outcome =
                Interpreter::new(Limits::default()).run(&format!("{name} --help"), &NoCapabilities);
            assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{name}: {outcome:?}");
            assert!(
                outcome.output.starts_with(&format!("{name}: ")),
                "{name}: {}",
                outcome.output
            );
        }
    }

    #[test]
    fn help_names_the_exact_flags_a_few_representative_builtins_accept() {
        let run = |script: &str| Interpreter::new(Limits::default()).run(script, &NoCapabilities);

        assert_eq!(run("grep --help").output, "grep: -v -i -c -n -E");
        assert_eq!(run("true --help").output, "true: no flags");
        assert_eq!(run("cat --help").output, "cat: no flags");
        assert_eq!(run("progress --help").output, "progress: --eta");
        assert_eq!(
            run(&format!("{} --help", xargs::NAME)).output,
            "xargs: -I -n"
        );
        assert_eq!(
            run("[ --help").output,
            "[: ! -z -n = == != < > -eq -ne -lt -le -gt -ge"
        );
    }

    #[test]
    fn unsupported_flag_names_the_accepted_subset() {
        let result =
            Interpreter::new(Limits::default()).run("grep -q a <<EOF\na\nEOF", &NoCapabilities);
        assert_eq!(result.exit_code, ExitCode::SYNTAX);
        assert!(
            result
                .output
                .contains("grep: option not yet supported: -q (supported: -v -i -c -n -E)"),
            "{result:?}"
        );
    }

    struct HttpGranted;

    impl CapabilityInvoker for HttpGranted {
        fn granted(&self) -> Vec<String> {
            vec!["http-probe.fetch".to_owned()]
        }

        fn invoke(&self, proposal: crate::CommandProposal) -> CapabilityCallResult {
            if proposal.secret_use.is_some() {
                return crate::secret_use_unsupported();
            }
            CapabilityCallResult::Failed {
                error: "curl reached a capability".to_owned(),
                detail: None,
            }
        }
    }

    #[test]
    fn curl_is_not_a_builtin_and_exits_127_even_with_an_http_capability_granted() {
        assert!(lookup("curl").is_none());
        let outcome = Interpreter::new(Limits::default()).run("curl https://x", &HttpGranted);
        assert_eq!(outcome.exit_code, ExitCode::NOT_FOUND, "{}", outcome.output);
        assert_eq!(outcome.output, "dekopon-shell: curl: command not found");
        assert_eq!(outcome.capability_calls, 0);
    }
}