Skip to main content

dekopon_shell/
lib.rs

1//! ```
2//! use std::io::Write;
3//!
4//! use dekopon_shell::{
5//!     CapabilityCallResult, CapabilityInvoker, Interpreter, Streams,
6//! };
7//! use dekopon_process::{Limits, ShellThreads};
8//! use serde_json::json;
9//!
10//! /// One provider word, `probe`, whose `upper --text <s>` proposes `cli-probe.upper`.
11//! struct Fixture;
12//!
13//! impl CapabilityInvoker for Fixture {
14//!     fn granted(&self) -> Vec<String> {
15//!         vec!["cli-probe.upper".to_owned()]
16//!     }
17//!
18//!     fn command_words(&self) -> Vec<String> {
19//!         vec!["probe".to_owned()]
20//!     }
21//!
22//!     fn run(&self, call: dekopon_shell::RunCall, streams: Streams, tree: &dekopon_process::TreeContext) -> dekopon_shell::RunResult {
23//!         let argv = call.argv.iter().map(ToString::to_string).collect::<Vec<_>>();
24//!         match argv.as_slice() {
25//!             [command, flag, text] if call.word == "probe" && command == "upper" && flag == "--text" => {
26//!                 let capability = "cli-probe.upper".to_owned();
27//!                 let input = json!({ "text": text });
28//!                 let result = self.invoke(dekopon_shell::CommandProposal::new(capability.clone(), input.clone(), None), streams, tree);
29//!                 dekopon_shell::RunResult::Invoked { capability, input, secret_use: None, result }
30//!             }
31//!             _ => dekopon_shell::render_command(streams, "", "usage: probe upper --text <text>".to_owned(), 2),
32//!         }
33//!     }
34//!
35//!     fn invoke(
36//!         &self,
37//!         proposal: dekopon_shell::CommandProposal,
38//!         streams: Streams,
39//!         _tree: &dekopon_process::TreeContext,
40//!     ) -> CapabilityCallResult {
41//!         let dekopon_shell::CommandProposal { capability, input, secret_use, .. } = proposal;
42//!         if secret_use.is_some() {
43//!             return dekopon_shell::secret_use_unsupported();
44//!         }
45//!         assert_eq!(capability, "cli-probe.upper");
46//!         let text = input["text"].as_str().unwrap_or_default().to_uppercase();
47//!         let mut stdout = std::os::unix::net::UnixStream::from(streams.stdout);
48//!         match writeln!(stdout, "{text}") {
49//!             Ok(()) => CapabilityCallResult::Succeeded,
50//!             Err(_) => CapabilityCallResult::Exited {
51//!                 status: std::num::NonZeroU8::new(141).unwrap(),
52//!                 stderr: String::new(),
53//!             },
54//!         }
55//!     }
56//! }
57//!
58//! let runtime = tokio::runtime::Runtime::new().unwrap();
59//! let threads = ShellThreads::new(16, runtime.handle().clone());
60//! let outcome = Interpreter::new(Limits::default(), threads)
61//!     .run("probe upper --text hi | cat", &Fixture);
62//! assert_eq!(outcome.exit_code.get(), 0);
63//! assert_eq!(outcome.output, "HI");
64//! ```
65
66#![cfg_attr(test, allow(clippy::unwrap_used))]
67#![forbid(unsafe_code)]
68#![cfg_attr(
69    test,
70    allow(
71        clippy::disallowed_methods,
72        clippy::disallowed_types,
73        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
74    )
75)]
76use crate::interp::telemetry::StageObservation;
77use dekopon_process::{CallBudget, ExitCode, Limits, ShellThreads, TreeContext, pipe};
78use std::{collections::BTreeMap, sync::Arc, time::Duration};
79
80use serde_json::Value;
81
82mod ast;
83mod builtins;
84mod interp;
85mod job;
86pub use job::{JobControl, JobRefusal, JobSeed};
87mod jq_worker;
88mod lexer;
89pub use jq_worker::{run_jq_worker_if_requested, set_jq_worker_executable};
90pub mod limits;
91mod parser;
92mod proposal;
93pub use proposal::{CommandProposal, CommandReport, CommandReportOutcome};
94pub mod value;
95
96use dekopon_core::{ProviderFailureDetail, SecretUseProposal};
97
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct CapabilityDescription {
100    pub capability: String,
101    pub description: String,
102}
103
104#[derive(Debug)]
105pub struct Streams {
106    pub stdin: Option<std::os::fd::OwnedFd>,
107    pub stdout: std::os::fd::OwnedFd,
108}
109
110impl Streams {
111    #[must_use]
112    pub fn reply(self, value: &Value) -> CapabilityCallResult {
113        use std::io::Write;
114        if value.is_null() {
115            return CapabilityCallResult::Succeeded;
116        }
117        let mut stdout = std::os::unix::net::UnixStream::from(self.stdout);
118        match writeln!(stdout, "{}", value::display(value)) {
119            Ok(()) => CapabilityCallResult::Succeeded,
120            Err(_closed) => CapabilityCallResult::Exited {
121                status: std::num::NonZeroU8::new(141).unwrap_or(std::num::NonZeroU8::MIN),
122                stderr: String::new(),
123            },
124        }
125    }
126}
127
128#[derive(Clone, Debug, PartialEq)]
129pub enum CapabilityCallResult {
130    Succeeded,
131    SucceededWithStderr(String),
132    Exited {
133        status: std::num::NonZeroU8,
134        stderr: String,
135    },
136    Denied {
137        reason: String,
138    },
139    Failed {
140        error: String,
141        detail: Option<ProviderFailureDetail>,
142    },
143    NotFound,
144}
145
146#[derive(Debug)]
147pub enum CommandRun {
148    Rendered {
149        stdout: String,
150        stderr: String,
151        status: u8,
152    },
153    Failed {
154        message: String,
155    },
156    Errored {
157        message: String,
158    },
159    Denied {
160        reason: String,
161    },
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub enum Arg {
166    Text(String),
167    Asset(dekopon_core::AssetNumber),
168}
169
170impl std::fmt::Display for Arg {
171    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        match self {
173            Self::Text(text) => formatter.write_str(text),
174            Self::Asset(number) => number.fmt(formatter),
175        }
176    }
177}
178
179pub struct RunCall {
180    pub word: String,
181    pub argv: Vec<Arg>,
182}
183
184pub enum RunResult {
185    Invoked {
186        capability: String,
187        input: Value,
188        secret_use: Option<SecretUseProposal>,
189        result: CapabilityCallResult,
190    },
191    Returned(CapabilityCallResult),
192    Uncertain(CapabilityCallResult),
193}
194
195pub fn render_command(streams: Streams, stdout: &str, stderr: String, status: u8) -> RunResult {
196    use std::io::Write as _;
197    let mut output = std::os::unix::net::UnixStream::from(streams.stdout);
198    if let Err(error) = output.write_all(stdout.as_bytes()) {
199        tracing::warn!(
200            event = "shell_command_stdout_failed",
201            error.kind = ?error.kind(),
202            errno = error.raw_os_error(),
203            "shell.command_stdout.failed"
204        );
205        return RunResult::Returned(CapabilityCallResult::Failed {
206            error: "command stdout could not be written".to_owned(),
207            detail: None,
208        });
209    }
210    RunResult::Returned(match std::num::NonZeroU8::new(status) {
211        Some(status) => CapabilityCallResult::Exited { status, stderr },
212        None if stderr.is_empty() => CapabilityCallResult::Succeeded,
213        None => CapabilityCallResult::SucceededWithStderr(stderr),
214    })
215}
216
217pub fn render_run(call: RunCall, parsed: Option<CommandRun>, streams: Streams) -> RunResult {
218    match parsed {
219        Some(CommandRun::Rendered {
220            stdout,
221            stderr,
222            status,
223        }) => render_command(streams, &stdout, stderr, status),
224        Some(CommandRun::Failed { message }) => render_command(streams, "", message, 2),
225        Some(CommandRun::Errored { message }) => {
226            RunResult::Returned(CapabilityCallResult::Failed {
227                error: message,
228                detail: None,
229            })
230        }
231        Some(CommandRun::Denied { reason }) => {
232            RunResult::Returned(CapabilityCallResult::Denied { reason })
233        }
234        None => render_command(
235            streams,
236            "",
237            format!("dekopon-shell: {}: command not found\n", call.word),
238            127,
239        ),
240    }
241}
242
243pub trait CapabilityInvoker: Send + Sync {
244    fn participant_handle(&self) -> Option<&str> {
245        None
246    }
247
248    fn cancel_signals(&self) -> Vec<dekopon_process::CancelSignal> {
249        Vec::new()
250    }
251
252    fn granted(&self) -> Vec<String>;
253
254    fn is_granted(&self, capability: &str) -> bool {
255        self.granted().iter().any(|granted| granted == capability)
256    }
257
258    fn command_words(&self) -> Vec<String> {
259        Vec::new()
260    }
261
262    fn command_word_help(&self) -> BTreeMap<String, String> {
263        BTreeMap::new()
264    }
265
266    fn has_command_word(&self, word: &str) -> bool {
267        self.command_words()
268            .iter()
269            .any(|candidate| candidate == word)
270    }
271
272    fn run(&self, call: RunCall, streams: Streams, _tree: &TreeContext) -> RunResult {
273        render_run(call, None, streams)
274    }
275
276    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
277        let _ = capability;
278        None
279    }
280
281    fn note(&self, text: &str, eta: Option<Duration>) {
282        let _ = (text, eta);
283    }
284
285    fn script_started(&self, _tree: &mut TreeContext) {}
286
287    fn script_finished(&self) {}
288
289    fn job_control(&self) -> Option<&dyn JobControl> {
290        None
291    }
292
293    fn invoke(
294        &self,
295        proposal: CommandProposal,
296        streams: Streams,
297        tree: &TreeContext,
298    ) -> CapabilityCallResult;
299}
300
301#[must_use]
302pub fn secret_use_unsupported() -> CapabilityCallResult {
303    CapabilityCallResult::Denied {
304        reason: "secret references require a broker-backed capability".to_owned(),
305    }
306}
307
308impl<T: CapabilityInvoker + ?Sized> CapabilityInvoker for Arc<T> {
309    fn participant_handle(&self) -> Option<&str> {
310        self.as_ref().participant_handle()
311    }
312
313    fn cancel_signals(&self) -> Vec<dekopon_process::CancelSignal> {
314        self.as_ref().cancel_signals()
315    }
316
317    fn granted(&self) -> Vec<String> {
318        self.as_ref().granted()
319    }
320
321    fn is_granted(&self, capability: &str) -> bool {
322        self.as_ref().is_granted(capability)
323    }
324
325    fn command_words(&self) -> Vec<String> {
326        self.as_ref().command_words()
327    }
328
329    fn command_word_help(&self) -> BTreeMap<String, String> {
330        self.as_ref().command_word_help()
331    }
332
333    fn has_command_word(&self, word: &str) -> bool {
334        self.as_ref().has_command_word(word)
335    }
336
337    fn run(&self, call: RunCall, streams: Streams, tree: &TreeContext) -> RunResult {
338        self.as_ref().run(call, streams, tree)
339    }
340
341    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
342        self.as_ref().describe(capability)
343    }
344
345    fn note(&self, text: &str, eta: Option<Duration>) {
346        self.as_ref().note(text, eta);
347    }
348
349    fn script_started(&self, tree: &mut TreeContext) {
350        self.as_ref().script_started(tree);
351    }
352
353    fn script_finished(&self) {
354        self.as_ref().script_finished();
355    }
356
357    fn job_control(&self) -> Option<&dyn JobControl> {
358        self.as_ref().job_control()
359    }
360
361    fn invoke(
362        &self,
363        proposal: CommandProposal,
364        streams: Streams,
365        tree: &TreeContext,
366    ) -> CapabilityCallResult {
367        self.as_ref().invoke(proposal, streams, tree)
368    }
369}
370
371impl From<&CapabilityCallResult> for ExitCode {
372    fn from(result: &CapabilityCallResult) -> Self {
373        match result {
374            CapabilityCallResult::Succeeded | CapabilityCallResult::SucceededWithStderr(_) => {
375                Self::SUCCESS
376            }
377            CapabilityCallResult::Exited { status, .. } => Self::from(status.get()),
378            CapabilityCallResult::Failed { .. } => Self::FAILURE,
379            CapabilityCallResult::Denied { .. } => Self::DENIED,
380            CapabilityCallResult::NotFound => Self::NOT_FOUND,
381        }
382    }
383}
384
385#[derive(Clone, Debug, Eq, PartialEq)]
386pub struct ScriptOutcome {
387    pub output: String,
388    pub exit_code: ExitCode,
389    pub truncated: bool,
390    pub capability_calls: u32,
391    pub steps: u64,
392}
393
394impl ScriptOutcome {
395    #[must_use]
396    pub fn refused(limit: dekopon_process::LimitExceeded) -> Self {
397        let fatal = builtins::FatalError::Limit(limit);
398        Self {
399            output: interp::fatal_message(&fatal),
400            exit_code: interp::telemetry::fatal_exit_code(&fatal),
401            truncated: false,
402            capability_calls: 0,
403            steps: 0,
404        }
405    }
406}
407
408#[derive(Debug)]
409pub struct ChildStdin(pipe::PipeReader<StageObservation>);
410
411impl ChildStdin {
412    pub fn adopt(socket: std::os::unix::net::UnixStream) -> std::io::Result<Self> {
413        pipe::PipeReader::from_socket(socket, None, crate::interp::telemetry::stage_read).map(Self)
414    }
415}
416
417#[derive(Clone, Debug)]
418pub struct Interpreter {
419    limits: Limits,
420    threads: ShellThreads,
421}
422
423impl Interpreter {
424    #[must_use]
425    pub fn new(limits: Limits, threads: ShellThreads) -> Self {
426        Self { limits, threads }
427    }
428
429    #[must_use]
430    pub fn limits(&self) -> Limits {
431        self.limits
432    }
433
434    pub fn run(&self, script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
435        self.run_with_tree(
436            script,
437            invoker,
438            &TreeContext::new(
439                self.limits,
440                CallBudget::new(self.limits.max_capability_calls),
441                self.threads.clone(),
442            )
443            .with_cancel(invoker.cancel_signals()),
444        )
445    }
446
447    pub fn run_with_tree(
448        &self,
449        script: &str,
450        invoker: &dyn CapabilityInvoker,
451        tree: &TreeContext,
452    ) -> ScriptOutcome {
453        interp::run_with_tree(script, None, None, invoker, self.limits, tree)
454    }
455
456    pub fn run_child(
457        &self,
458        script: &str,
459        stdin: Option<ChildStdin>,
460        invoker: &dyn CapabilityInvoker,
461        tree: &TreeContext,
462    ) -> ScriptOutcome {
463        let stdin = stdin.map(|ChildStdin(reader)| reader);
464        interp::run_with_tree(script, None, stdin, invoker, self.limits, tree)
465    }
466
467    pub fn run_seed(
468        &self,
469        seed: JobSeed,
470        invoker: &dyn CapabilityInvoker,
471        tree: &TreeContext,
472    ) -> ScriptOutcome {
473        interp::run_seed(seed, invoker, self.limits, tree)
474    }
475
476    pub fn run_with_prev(
477        &self,
478        script: &str,
479        prev: &str,
480        invoker: &dyn CapabilityInvoker,
481    ) -> ScriptOutcome {
482        interp::run(script, Some(prev), invoker, self.limits, &self.threads)
483    }
484}
485
486#[cfg(test)]
487pub(crate) fn test_threads() -> ShellThreads {
488    test_threads_up_to(16)
489}
490
491#[cfg(test)]
492pub(crate) fn test_threads_up_to(maximum: u32) -> ShellThreads {
493    static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
494        tokio::runtime::Builder::new_multi_thread()
495            .worker_threads(1)
496            .enable_all()
497            .build()
498            .unwrap()
499    });
500    ShellThreads::new(maximum, RUNTIME.handle().clone())
501}
502
503#[cfg(test)]
504mod tests {
505    use parking_lot::Mutex;
506    use std::{
507        collections::BTreeMap,
508        sync::{
509            Arc,
510            atomic::{AtomicU32, Ordering},
511        },
512        time::{Duration, Instant},
513    };
514
515    use dekopon_core::{SecretDrn, SecretUseProposal};
516    use serde_json::{Value, json};
517
518    use super::{
519        CapabilityCallResult, CapabilityDescription, CapabilityInvoker, CommandRun, ExitCode,
520        Interpreter,
521    };
522    use dekopon_process::{CallBudget, Limits, TreeContext};
523
524    #[derive(Default)]
525    enum Completion {
526        #[default]
527        Parsed,
528        Uncertain,
529        NotExecuted,
530    }
531
532    #[derive(Default)]
533    struct RecordingInvoker {
534        secret_uses: Mutex<Vec<Option<SecretUseProposal>>>,
535        scripts_finished: AtomicU32,
536        tree: Option<TreeContext>,
537        retained: Mutex<Vec<u64>>,
538        completion: Completion,
539        admitted: Mutex<Vec<u32>>,
540    }
541
542    impl RecordingInvoker {
543        fn parse_command(
544            &self,
545            word: &str,
546            argv: &[String],
547            stdin_piped: bool,
548        ) -> Option<Result<crate::CommandProposal, CommandRun>> {
549            if matches!(word, "retained" | "render") {
550                let stdout = if word == "retained" {
551                    self.retained.lock().push(self.tree.as_ref()?.value_bytes());
552                    String::new()
553                } else {
554                    "abcdefgh".to_owned()
555                };
556                return Some(Err(CommandRun::Rendered {
557                    stdout,
558                    stderr: String::new(),
559                    status: 0,
560                }));
561            }
562            Some(Ok(crate::CommandProposal {
563                capability: word.to_owned(),
564                input: json!({ "argv": argv, "stdin": stdin_piped.then_some("") }),
565                secret_use: None,
566                report: None,
567            }))
568        }
569    }
570
571    impl CapabilityInvoker for RecordingInvoker {
572        fn granted(&self) -> Vec<String> {
573            vec!["cli-probe.upper".to_owned()]
574        }
575
576        fn is_granted(&self, capability: &str) -> bool {
577            capability == "gh.pr-view" || capability == "gh-extra"
578        }
579
580        fn command_words(&self) -> Vec<String> {
581            vec!["gh".to_owned()]
582        }
583
584        fn command_word_help(&self) -> BTreeMap<String, String> {
585            BTreeMap::from([("gh".to_owned(), "gh: recorded help".to_owned())])
586        }
587
588        fn has_command_word(&self, word: &str) -> bool {
589            matches!(word, "gh-extra" | "retained" | "render")
590        }
591
592        fn run(
593            &self,
594            call: crate::RunCall,
595            streams: crate::Streams,
596            tree: &dekopon_process::TreeContext,
597        ) -> crate::RunResult {
598            self.admitted.lock().push(tree.calls().used());
599            match self.completion {
600                Completion::Parsed => {}
601                Completion::Uncertain => {
602                    return crate::RunResult::Uncertain(CapabilityCallResult::Failed {
603                        error: "execution outcome is unknown".to_owned(),
604                        detail: None,
605                    });
606                }
607                Completion::NotExecuted => {
608                    return crate::RunResult::Returned(CapabilityCallResult::Denied {
609                        reason: "not granted".to_owned(),
610                    });
611                }
612            }
613            let argv = call
614                .argv
615                .iter()
616                .map(ToString::to_string)
617                .collect::<Vec<_>>();
618            match self.parse_command(&call.word, &argv, streams.stdin.is_some()) {
619                Some(Ok(proposal)) => {
620                    let capability = proposal.capability.clone();
621                    let input = proposal.input.clone();
622                    let secret_use = proposal.secret_use.clone();
623                    if !self.is_granted(&capability) {
624                        return crate::render_command(
625                            streams,
626                            "",
627                            format!(
628                                "dekopon-shell: {}: requires capability {}, which is not granted in this session\n",
629                                call.word, capability
630                            ),
631                            127,
632                        );
633                    }
634                    let result = self.invoke(proposal, streams, tree);
635                    crate::RunResult::Invoked {
636                        capability,
637                        input,
638                        secret_use,
639                        result,
640                    }
641                }
642                Some(Err(rendered)) => crate::render_run(call, Some(rendered), streams),
643                None => crate::render_run(call, None, streams),
644            }
645        }
646
647        fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
648            Some(CapabilityDescription {
649                capability: capability.to_owned(),
650                description: "recorded".to_owned(),
651            })
652        }
653
654        fn invoke(
655            &self,
656            proposal: super::CommandProposal,
657            streams: super::Streams,
658            _tree: &dekopon_process::TreeContext,
659        ) -> CapabilityCallResult {
660            let input = proposal.input;
661            let secret_use = proposal.secret_use;
662            self.secret_uses.lock().push(secret_use);
663            streams.reply(&input)
664        }
665
666        fn script_finished(&self) {
667            self.scripts_finished.fetch_add(1, Ordering::Relaxed);
668        }
669    }
670
671    struct Cancellation(dekopon_process::CancelSignal);
672
673    impl CapabilityInvoker for Cancellation {
674        fn cancel_signals(&self) -> Vec<dekopon_process::CancelSignal> {
675            vec![self.0.clone()]
676        }
677        fn granted(&self) -> Vec<String> {
678            Vec::new()
679        }
680        fn invoke(
681            &self,
682            _: super::CommandProposal,
683            _streams: super::Streams,
684            _tree: &dekopon_process::TreeContext,
685        ) -> CapabilityCallResult {
686            CapabilityCallResult::NotFound
687        }
688    }
689
690    #[test]
691    fn a_budget_of_n_never_executes_call_n_plus_one() {
692        for maximum in [0, 1, 3] {
693            let invoker = RecordingInvoker::default();
694            let limits = Limits {
695                max_capability_calls: maximum,
696                ..Limits::default()
697            };
698            let script = (0..=maximum)
699                .map(|_| "gh.pr-view")
700                .collect::<Vec<_>>()
701                .join("; ");
702            let outcome = Interpreter::new(limits, crate::test_threads()).run(&script, &invoker);
703            assert_eq!(
704                invoker.secret_uses.lock().len(),
705                usize::try_from(maximum).unwrap()
706            );
707            assert_eq!(outcome.capability_calls, maximum);
708            assert_eq!(*invoker.admitted.lock(), (1..=maximum).collect::<Vec<_>>());
709        }
710    }
711
712    #[test]
713    fn an_uncertain_outcome_stays_charged() {
714        let invoker = RecordingInvoker {
715            completion: Completion::Uncertain,
716            ..RecordingInvoker::default()
717        };
718        let limits = Limits {
719            max_capability_calls: 1,
720            ..Limits::default()
721        };
722        let outcome = Interpreter::new(limits, crate::test_threads()).run("late", &invoker);
723        assert_eq!(*invoker.admitted.lock(), vec![1]);
724        assert_eq!(outcome.capability_calls, 1);
725    }
726
727    #[test]
728    fn a_definite_not_executed_outcome_is_refunded() {
729        let invoker = RecordingInvoker {
730            completion: Completion::NotExecuted,
731            ..RecordingInvoker::default()
732        };
733        let limits = Limits {
734            max_capability_calls: 1,
735            ..Limits::default()
736        };
737        let outcome = Interpreter::new(limits, crate::test_threads()).run("late", &invoker);
738        assert_eq!(*invoker.admitted.lock(), vec![1]);
739        assert_eq!(outcome.capability_calls, 0);
740    }
741
742    #[test]
743    fn a_capability_invoked_from_an_unresolved_word_still_spends_a_call() {
744        let invoker = RecordingInvoker::default();
745        let limits = Limits {
746            max_capability_calls: 1,
747            ..Limits::default()
748        };
749        let outcome = Interpreter::new(limits, crate::test_threads()).run("gh.pr-view", &invoker);
750        assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
751        assert_eq!(outcome.capability_calls, 1);
752        assert_eq!(invoker.secret_uses.lock().len(), 1);
753    }
754
755    #[test]
756    fn a_cancelled_loop_stops_before_exhausting_steps() {
757        let (handle, cancelled) = dekopon_process::CancelSignal::pair();
758        handle.cancel();
759        let limits = Limits {
760            max_steps: 100_000,
761            ..Limits::default()
762        };
763        let outcome = Interpreter::new(limits, crate::test_threads())
764            .run("while true; do :; done", &Cancellation(cancelled));
765        assert_eq!(outcome.exit_code, ExitCode::CANCELLED);
766        assert_eq!(
767            super::interp::telemetry::fatal_outcome(&super::builtins::FatalError::Limit(
768                dekopon_process::LimitExceeded::Cancelled
769            )),
770            "cancelled"
771        );
772        assert!(outcome.steps < 100);
773    }
774
775    #[test]
776    fn run_with_prev_refuses_an_already_cancelled_invoker() {
777        let (handle, signal) = dekopon_process::CancelSignal::pair();
778        handle.cancel();
779        let outcome = Interpreter::new(Limits::default(), crate::test_threads()).run_with_prev(
780            "echo ok",
781            "",
782            &Cancellation(signal),
783        );
784        assert_eq!(outcome.exit_code, ExitCode::CANCELLED);
785    }
786
787    #[test]
788    fn a_sleep_wakes_for_cancellation_without_waiting_for_the_deadline() {
789        let (flip, cancelled) = dekopon_process::CancelSignal::pair();
790        let worker = std::thread::spawn(move || {
791            std::thread::sleep(Duration::from_millis(200));
792            flip.cancel();
793        });
794        let start = Instant::now();
795        let outcome = Interpreter::new(
796            Limits {
797                timeout: Duration::from_secs(310),
798                ..Limits::default()
799            },
800            crate::test_threads(),
801        )
802        .run("sleep 300", &Cancellation(cancelled));
803        worker.join().expect("cancel worker");
804        assert_eq!(outcome.exit_code, ExitCode::CANCELLED);
805        assert!(start.elapsed() < Duration::from_millis(1500));
806    }
807
808    #[test]
809    fn interpreters_in_one_tree_share_calls_and_deadline() {
810        let limits = Limits {
811            timeout: Duration::from_millis(80),
812            max_capability_calls: 1,
813            ..Limits::default()
814        };
815        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
816        let invoker = RecordingInvoker::default();
817        let interpreter = Interpreter::new(limits, crate::test_threads());
818        assert_eq!(
819            interpreter
820                .run_with_tree("gh-extra one", &invoker, &tree)
821                .capability_calls,
822            1
823        );
824        let second_interpreter = Interpreter::new(limits, crate::test_threads());
825        let second = second_interpreter.run_with_tree("gh-extra two", &invoker, &tree);
826        assert_eq!(second.exit_code, ExitCode::SYNTAX);
827        assert_eq!(tree.calls().used(), 1);
828        std::thread::sleep(Duration::from_millis(100));
829        assert_eq!(
830            second_interpreter
831                .run_with_tree("echo late", &invoker, &tree)
832                .exit_code,
833            ExitCode::TIMEOUT
834        );
835    }
836
837    #[test]
838    fn replacements_and_scope_drops_refund_retained_bytes() {
839        let limits = Limits {
840            max_value_bytes: 128,
841            ..Limits::default()
842        };
843        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
844        let script = "f() { local y=abcdefgh; }; x=abcdefgh; ".to_owned()
845            + &"x=ijklmnop; f; echo abcdefgh > buf; ".repeat(20);
846        let outcome = Interpreter::new(limits, crate::test_threads()).run_with_tree(
847            &script,
848            &RecordingInvoker::default(),
849            &tree,
850        );
851        assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
852        assert_eq!(tree.value_bytes(), 0);
853    }
854
855    #[test]
856    fn substitution_arguments_keep_their_charges_until_the_command_finishes() {
857        let invoker = RecordingInvoker::default();
858        let limits = Limits {
859            max_value_bytes: 512,
860            ..Limits::default()
861        };
862        let tree = TreeContext::new(limits, CallBudget::new(4), crate::test_threads());
863        let word = format!("\"$(printf {})\"", "x".repeat(256));
864        let interpreter = Interpreter::new(limits, crate::test_threads());
865        let failed = interpreter.run_with_tree(&format!("gh-extra {word} {word}"), &invoker, &tree);
866        assert_eq!(failed.exit_code, ExitCode::SYNTAX, "{}", failed.output);
867        assert!(invoker.secret_uses.lock().is_empty());
868        assert_eq!(tree.value_bytes(), 0);
869        let script = format!("gh-extra {word} > /dev/null; gh-extra {word} > /dev/null");
870        assert_eq!(tree.value_bytes(), 0);
871        let next = interpreter.run_with_tree(&script, &invoker, &tree);
872        assert_eq!(next.exit_code, ExitCode::SUCCESS, "{}", next.output);
873        assert_eq!(tree.value_bytes(), 0);
874    }
875
876    #[test]
877    fn substitution_refunds_trailing_line_feeds_before_the_next_capture() {
878        let limits = Limits {
879            max_value_bytes: 256,
880            ..Limits::default()
881        };
882        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
883        let invoker = RecordingInvoker {
884            tree: Some(tree.clone()),
885            ..RecordingInvoker::default()
886        };
887        let outcome = Interpreter::new(limits, crate::test_threads()).run_with_tree(
888            "v=$(printf 'x\\n\\n'); retained; w=$(printf 12345678); retained",
889            &invoker,
890            &tree,
891        );
892        assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{outcome:?}");
893        assert_eq!(*invoker.retained.lock(), vec![49, 73]);
894        assert_eq!(tree.value_bytes(), 0);
895    }
896
897    #[test]
898    fn local_assignment_in_a_snapshot_does_not_copy_uncharged_globals() {
899        let limits = Limits {
900            max_value_bytes: 2 * 1024 * 1024 + 96 * 1024,
901            ..Limits::default()
902        };
903        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
904        let script = format!(
905            "big={}; f() {{ local n=0; n=1 sleep 1 | cat; }}; f",
906            "x".repeat(64 * 1024)
907        );
908        let outcome = Interpreter::new(limits, crate::test_threads()).run_with_tree(
909            &script,
910            &RecordingInvoker::default(),
911            &tree,
912        );
913        assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{outcome:?}");
914        assert_eq!(tree.value_bytes(), 0);
915    }
916
917    #[test]
918    fn four_kib_value_headroom_is_enforced_and_streaming_bytes_are_not_retained() {
919        let limits = Limits {
920            max_value_bytes: 2 * 1024 * 1024 + 4096,
921            ..Limits::default()
922        };
923        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
924        let interpreter = Interpreter::new(limits, crate::test_threads());
925        let invoker = RecordingInvoker::default();
926        for script in [
927            "v=$(while true; do printf xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; done | cat)",
928            "while true; do printf xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; done | sort",
929            "while true; do printf xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; done | tail -n 200",
930        ] {
931            let outcome = interpreter.run_with_tree(script, &invoker, &tree);
932            assert_ne!(
933                outcome.exit_code,
934                ExitCode::SUCCESS,
935                "{script}: {outcome:?}"
936            );
937            assert!(
938                outcome.output.contains("bytes of values"),
939                "{script}: {outcome:?}"
940            );
941            assert_eq!(tree.value_bytes(), 0, "{script}");
942        }
943        let streaming_limits = Limits {
944            max_value_bytes: 2 * 2 * 1024 * 1024 + 4096,
945            ..limits
946        };
947        let streaming_tree =
948            TreeContext::new(streaming_limits, CallBudget::new(1), crate::test_threads());
949        let script = format!("printf '{}' | cat | wc -c", "x".repeat(1024 * 1024));
950        let streamed = Interpreter::new(streaming_limits, crate::test_threads()).run_with_tree(
951            &script,
952            &invoker,
953            &streaming_tree,
954        );
955        assert_eq!(streamed.exit_code, ExitCode::SUCCESS, "{streamed:?}");
956        assert_eq!(streamed.output, "1048576");
957        assert_eq!(streaming_tree.value_bytes(), 0);
958    }
959
960    #[test]
961    fn redirect_keeps_source_charge_while_copying_to_a_buffer() {
962        let limits = Limits {
963            max_value_bytes: 15,
964            ..Limits::default()
965        };
966        let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
967        let invoker = RecordingInvoker {
968            tree: Some(tree.clone()),
969            ..RecordingInvoker::default()
970        };
971        let outcome = Interpreter::new(limits, crate::test_threads()).run_with_tree(
972            "render > buf",
973            &invoker,
974            &tree,
975        );
976        assert_ne!(outcome.exit_code, ExitCode::SUCCESS, "{outcome:?}");
977        assert!(outcome.output.contains("bytes of values"), "{outcome:?}");
978        assert_eq!(tree.value_bytes(), 0);
979    }
980
981    #[test]
982    fn storage_adopts_moved_charges_and_refunds_unset_and_replacement() {
983        for (maximum, script, expected) in [
984            (
985                128,
986                "x=$(printf abcdefgh); retained; x=a; retained; unset x; retained",
987                vec![56, 49, 32],
988            ),
989            (
990                128,
991                "printf abcdefgh > buf; retained; : > buf; retained; render >> buf; retained; : > buf; retained",
992                vec![40, 32, 40, 32],
993            ),
994            (
995                128,
996                "render > buf; retained; render >> buf; retained; : > buf; retained",
997                vec![40, 48, 32],
998            ),
999            (
1000                128,
1001                "cat <<EOF\n$(printf abcdefgh)\nEOF\nretained",
1002                vec![32],
1003            ),
1004        ] {
1005            let limits = Limits {
1006                max_value_bytes: maximum,
1007                ..Limits::default()
1008            };
1009            let tree = TreeContext::new(limits, CallBudget::new(1), crate::test_threads());
1010            let invoker = RecordingInvoker {
1011                tree: Some(tree.clone()),
1012                ..RecordingInvoker::default()
1013            };
1014            let outcome = Interpreter::new(limits, crate::test_threads())
1015                .run_with_tree(script, &invoker, &tree);
1016            assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
1017            assert_eq!(*invoker.retained.lock(), expected, "{script}");
1018            assert_eq!(tree.value_bytes(), 0);
1019        }
1020    }
1021
1022    fn streams() -> (super::Streams, std::os::unix::net::UnixStream) {
1023        let (stdout, reader) = std::os::unix::net::UnixStream::pair().expect("socketpair");
1024        let streams = super::Streams {
1025            stdin: None,
1026            stdout: stdout.into(),
1027        };
1028        (streams, reader)
1029    }
1030
1031    fn proposal() -> SecretUseProposal {
1032        SecretUseProposal::HttpBearer {
1033            secret: "drn:secret:api/token"
1034                .parse::<SecretDrn>()
1035                .expect("canonical DRN"),
1036        }
1037    }
1038
1039    #[test]
1040    fn an_arc_hands_a_secret_use_proposal_to_the_invoker_behind_it_unchanged() {
1041        let inner = Arc::new(RecordingInvoker::default());
1042        let shared: Arc<dyn CapabilityInvoker> = Arc::clone(&inner) as Arc<dyn CapabilityInvoker>;
1043
1044        assert_eq!(
1045            shared.invoke(
1046                super::CommandProposal::new("http-probe.fetch", json!({"url": "https://x"}), None),
1047                streams().0,
1048                &dekopon_process::TreeContext::new(
1049                    dekopon_process::Limits::default(),
1050                    dekopon_process::CallBudget::new(64),
1051                    crate::test_threads()
1052                )
1053            ),
1054            CapabilityCallResult::Succeeded
1055        );
1056        assert_eq!(
1057            shared.invoke(
1058                super::CommandProposal::new("http-probe.fetch", json!({}), Some(proposal())),
1059                streams().0,
1060                &dekopon_process::TreeContext::new(
1061                    dekopon_process::Limits::default(),
1062                    dekopon_process::CallBudget::new(64),
1063                    crate::test_threads()
1064                )
1065            ),
1066            CapabilityCallResult::Succeeded
1067        );
1068
1069        assert_eq!(
1070            *inner.secret_uses.lock(),
1071            vec![None, Some(proposal())],
1072            "the pointer altered a proposal on its way to the invoker behind it"
1073        );
1074    }
1075
1076    #[test]
1077    fn an_arc_forwards_the_defaulted_methods_instead_of_inheriting_their_defaults() {
1078        let inner = Arc::new(RecordingInvoker::default());
1079        let shared: Arc<dyn CapabilityInvoker> = Arc::clone(&inner) as Arc<dyn CapabilityInvoker>;
1080
1081        shared.script_finished();
1082        assert_eq!(inner.scripts_finished.load(Ordering::Relaxed), 1);
1083
1084        assert_eq!(shared.granted(), vec!["cli-probe.upper".to_owned()]);
1085        assert!(shared.is_granted("gh.pr-view"));
1086        assert_eq!(shared.command_words(), vec!["gh".to_owned()]);
1087        assert_eq!(
1088            shared.command_word_help(),
1089            BTreeMap::from([("gh".to_owned(), "gh: recorded help".to_owned())])
1090        );
1091        assert!(shared.has_command_word("gh-extra"));
1092        assert_eq!(
1093            shared.describe("gh.pr-view").map(|it| it.description),
1094            Some("recorded".to_owned())
1095        );
1096    }
1097
1098    struct ProposingInvoker {
1099        secret_use: Option<SecretUseProposal>,
1100        invocations: Mutex<Vec<(String, Value, Option<SecretUseProposal>)>>,
1101    }
1102
1103    impl ProposingInvoker {
1104        fn proposing(secret_use: Option<SecretUseProposal>) -> Self {
1105            Self {
1106                secret_use,
1107                invocations: Mutex::new(Vec::new()),
1108            }
1109        }
1110    }
1111
1112    impl ProposingInvoker {
1113        fn parse_command(
1114            &self,
1115            word: &str,
1116            argv: &[String],
1117            stdin_piped: bool,
1118        ) -> Option<Result<crate::CommandProposal, CommandRun>> {
1119            (word == "httpprobe").then(|| {
1120                Ok(crate::CommandProposal {
1121                    capability: "http-probe.fetch".to_owned(),
1122                    input: json!({ "argv": argv, "stdin": stdin_piped.then_some("") }),
1123                    secret_use: self.secret_use.clone(),
1124                    report: None,
1125                })
1126            })
1127        }
1128    }
1129
1130    impl CapabilityInvoker for ProposingInvoker {
1131        fn granted(&self) -> Vec<String> {
1132            vec!["http-probe.fetch".to_owned()]
1133        }
1134
1135        fn command_words(&self) -> Vec<String> {
1136            vec!["httpprobe".to_owned()]
1137        }
1138
1139        fn run(
1140            &self,
1141            call: crate::RunCall,
1142            streams: crate::Streams,
1143            tree: &dekopon_process::TreeContext,
1144        ) -> crate::RunResult {
1145            let argv = call
1146                .argv
1147                .iter()
1148                .map(ToString::to_string)
1149                .collect::<Vec<_>>();
1150            match self.parse_command(&call.word, &argv, streams.stdin.is_some()) {
1151                Some(Ok(proposal)) => {
1152                    let capability = proposal.capability.clone();
1153                    let input = proposal.input.clone();
1154                    let secret_use = proposal.secret_use.clone();
1155                    if !self.is_granted(&capability) {
1156                        return crate::render_command(
1157                            streams,
1158                            "",
1159                            format!(
1160                                "dekopon-shell: {}: requires capability {}, which is not granted in this session\n",
1161                                call.word, capability
1162                            ),
1163                            127,
1164                        );
1165                    }
1166                    let result = self.invoke(proposal, streams, tree);
1167                    crate::RunResult::Invoked {
1168                        capability,
1169                        input,
1170                        secret_use,
1171                        result,
1172                    }
1173                }
1174                Some(Err(rendered)) => crate::render_run(call, Some(rendered), streams),
1175                None => crate::render_run(call, None, streams),
1176            }
1177        }
1178
1179        fn invoke(
1180            &self,
1181            proposal: super::CommandProposal,
1182            streams: super::Streams,
1183            _tree: &dekopon_process::TreeContext,
1184        ) -> CapabilityCallResult {
1185            let capability = proposal.capability;
1186            let input = proposal.input;
1187            let secret_use = proposal.secret_use;
1188            self.invocations
1189                .lock()
1190                .push((capability.to_owned(), input, secret_use));
1191            streams.reply(&json!({"status": 200}))
1192        }
1193    }
1194
1195    #[test]
1196    fn a_provider_proposal_hands_its_secret_use_to_invoke() {
1197        for secret_use in [Some(proposal()), None] {
1198            let invoker = ProposingInvoker::proposing(secret_use.clone());
1199            let outcome = Interpreter::new(Limits::default(), crate::test_threads())
1200                .run("httpprobe fetch --url https://x", &invoker);
1201            assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
1202            assert_eq!(outcome.output, r#"{"status":200}"#);
1203            assert_eq!(outcome.capability_calls, 1);
1204            assert_eq!(
1205                *invoker.invocations.lock(),
1206                vec![(
1207                    "http-probe.fetch".to_owned(),
1208                    json!({"argv": ["fetch", "--url", "https://x"], "stdin": null}),
1209                    secret_use,
1210                )],
1211                "the proposal's secret use did not reach invoke unchanged"
1212            );
1213        }
1214    }
1215
1216    struct ChildInputInvoker {
1217        seen: Mutex<Vec<bool>>,
1218        read: bool,
1219    }
1220
1221    impl ChildInputInvoker {
1222        fn parse_command(
1223            &self,
1224            word: &str,
1225            _argv: &[String],
1226            stdin_piped: bool,
1227        ) -> Option<Result<crate::CommandProposal, CommandRun>> {
1228            self.seen.lock().push(stdin_piped);
1229            (word == "httpprobe").then(|| {
1230                Ok(crate::CommandProposal {
1231                    capability: "http-probe.fetch".to_owned(),
1232                    input: serde_json::Value::Null,
1233                    secret_use: None,
1234                    report: None,
1235                })
1236            })
1237        }
1238    }
1239
1240    impl CapabilityInvoker for ChildInputInvoker {
1241        fn granted(&self) -> Vec<String> {
1242            vec!["http-probe.fetch".to_owned()]
1243        }
1244
1245        fn command_words(&self) -> Vec<String> {
1246            vec!["httpprobe".to_owned()]
1247        }
1248
1249        fn run(
1250            &self,
1251            call: crate::RunCall,
1252            streams: crate::Streams,
1253            tree: &dekopon_process::TreeContext,
1254        ) -> crate::RunResult {
1255            let argv = call
1256                .argv
1257                .iter()
1258                .map(ToString::to_string)
1259                .collect::<Vec<_>>();
1260            match self.parse_command(&call.word, &argv, streams.stdin.is_some()) {
1261                Some(Ok(proposal)) => {
1262                    let capability = proposal.capability.clone();
1263                    let input = proposal.input.clone();
1264                    let secret_use = proposal.secret_use.clone();
1265                    if !self.is_granted(&capability) {
1266                        return crate::render_command(
1267                            streams,
1268                            "",
1269                            format!(
1270                                "dekopon-shell: {}: requires capability {}, which is not granted in this session\n",
1271                                call.word, capability
1272                            ),
1273                            127,
1274                        );
1275                    }
1276                    let result = self.invoke(proposal, streams, tree);
1277                    crate::RunResult::Invoked {
1278                        capability,
1279                        input,
1280                        secret_use,
1281                        result,
1282                    }
1283                }
1284                Some(Err(rendered)) => crate::render_run(call, Some(rendered), streams),
1285                None => crate::render_run(call, None, streams),
1286            }
1287        }
1288
1289        fn invoke(
1290            &self,
1291            _proposal: super::CommandProposal,
1292            streams: super::Streams,
1293            _tree: &dekopon_process::TreeContext,
1294        ) -> CapabilityCallResult {
1295            if self.read {
1296                let Some(fd) = streams.stdin else {
1297                    panic!("provider must receive its script stdin");
1298                };
1299                let mut stdin = std::os::unix::net::UnixStream::from(fd);
1300                use std::io::Read as _;
1301                let mut bytes = [0; 64];
1302                let _ = stdin.read(&mut bytes).expect("provider reads stdin");
1303            }
1304            CapabilityCallResult::Succeeded
1305        }
1306    }
1307
1308    fn child_with_input(
1309        script: &str,
1310        invoker: &ChildInputInvoker,
1311        input: &[u8],
1312    ) -> super::ScriptOutcome {
1313        use std::io::Write as _;
1314        let (read, mut write) = std::os::unix::net::UnixStream::pair().expect("script stdin");
1315        let stdin = super::ChildStdin::adopt(read).expect("child adopts stdin");
1316        write.write_all(input).expect("input bytes");
1317        drop(write);
1318        let limits = Limits::default();
1319        Interpreter::new(limits, crate::test_threads()).run_child(
1320            script,
1321            Some(stdin),
1322            invoker,
1323            &TreeContext::new(limits, CallBudget::new(16), crate::test_threads()),
1324        )
1325    }
1326
1327    #[test]
1328    fn compound_and_function_pipes_do_not_pass_input_to_inner_provider() {
1329        let invoker = ChildInputInvoker {
1330            seen: Mutex::new(Vec::new()),
1331            read: false,
1332        };
1333        let output = child_with_input(
1334            "f() { httpprobe; }; printf pipe | f; printf pipe | { httpprobe; }",
1335            &invoker,
1336            b"script input",
1337        );
1338        assert_eq!(output.exit_code, ExitCode::SUCCESS, "{}", output.output);
1339        assert_eq!(*invoker.seen.lock(), [false, false]);
1340    }
1341
1342    #[test]
1343    fn sequential_provider_then_read_share_script_stdin() {
1344        let invoker = ChildInputInvoker {
1345            seen: Mutex::new(Vec::new()),
1346            read: true,
1347        };
1348        let output = child_with_input("httpprobe; read x; echo done", &invoker, b"first\nsecond\n");
1349        assert_eq!(output.exit_code, ExitCode::SUCCESS, "{}", output.output);
1350        assert_eq!(*invoker.seen.lock(), [true]);
1351    }
1352
1353    #[test]
1354    fn provider_that_never_reads_idle_script_stdin_returns_promptly() {
1355        let invoker = ChildInputInvoker {
1356            seen: Mutex::new(Vec::new()),
1357            read: false,
1358        };
1359        let (reader, _writer) = std::os::unix::net::UnixStream::pair().expect("idle stdin");
1360        let limits = Limits::default();
1361        let start = std::time::Instant::now();
1362        let outcome = Interpreter::new(limits, crate::test_threads()).run_child(
1363            "httpprobe",
1364            Some(super::ChildStdin::adopt(reader).expect("child adopts stdin")),
1365            &invoker,
1366            &TreeContext::new(limits, CallBudget::new(16), crate::test_threads()),
1367        );
1368        assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
1369        assert!(start.elapsed() < std::time::Duration::from_millis(1500));
1370        assert_eq!(*invoker.seen.lock(), [true]);
1371    }
1372
1373    struct PanickingInputInvoker {
1374        stop: dekopon_process::CancelSignal,
1375    }
1376
1377    impl PanickingInputInvoker {
1378        fn parse_command(
1379            &self,
1380            word: &str,
1381            _argv: &[String],
1382            stdin_piped: bool,
1383        ) -> Option<Result<crate::CommandProposal, CommandRun>> {
1384            assert!(stdin_piped, "child stage inherits script stdin");
1385            (word == "httpprobe").then(|| {
1386                Ok(crate::CommandProposal {
1387                    capability: "http-probe.fetch".to_owned(),
1388                    input: serde_json::Value::Null,
1389                    secret_use: None,
1390                    report: None,
1391                })
1392            })
1393        }
1394    }
1395
1396    impl CapabilityInvoker for PanickingInputInvoker {
1397        fn cancel_signals(&self) -> Vec<dekopon_process::CancelSignal> {
1398            vec![self.stop.clone()]
1399        }
1400
1401        fn granted(&self) -> Vec<String> {
1402            vec!["http-probe.fetch".to_owned()]
1403        }
1404
1405        fn command_words(&self) -> Vec<String> {
1406            vec!["httpprobe".to_owned()]
1407        }
1408
1409        fn run(
1410            &self,
1411            call: crate::RunCall,
1412            streams: crate::Streams,
1413            tree: &dekopon_process::TreeContext,
1414        ) -> crate::RunResult {
1415            let argv = call
1416                .argv
1417                .iter()
1418                .map(ToString::to_string)
1419                .collect::<Vec<_>>();
1420            match self.parse_command(&call.word, &argv, streams.stdin.is_some()) {
1421                Some(Ok(proposal)) => {
1422                    let capability = proposal.capability.clone();
1423                    let input = proposal.input.clone();
1424                    let secret_use = proposal.secret_use.clone();
1425                    if !self.is_granted(&capability) {
1426                        return crate::render_command(
1427                            streams,
1428                            "",
1429                            format!(
1430                                "dekopon-shell: {}: requires capability {}, which is not granted in this session\n",
1431                                call.word, capability
1432                            ),
1433                            127,
1434                        );
1435                    }
1436                    let result = self.invoke(proposal, streams, tree);
1437                    crate::RunResult::Invoked {
1438                        capability,
1439                        input,
1440                        secret_use,
1441                        result,
1442                    }
1443                }
1444                Some(Err(rendered)) => crate::render_run(call, Some(rendered), streams),
1445                None => crate::render_run(call, None, streams),
1446            }
1447        }
1448
1449        fn invoke(
1450            &self,
1451            _proposal: super::CommandProposal,
1452            _streams: super::Streams,
1453            _tree: &dekopon_process::TreeContext,
1454        ) -> CapabilityCallResult {
1455            panic!("the provider panicked with idle inherited stdin")
1456        }
1457    }
1458
1459    #[test]
1460    fn panicking_provider_with_idle_inherited_stdin_releases_the_feeder() {
1461        let (stop, stop_for_worker) = dekopon_process::CancelSignal::pair();
1462        let (read, _idle_writer) = std::os::unix::net::UnixStream::pair().expect("idle stdin");
1463        let stdin = super::ChildStdin::adopt(read).expect("adopt before peer closes");
1464        let (finished, result) = std::sync::mpsc::channel();
1465        let worker = std::thread::spawn(move || {
1466            let limits = Limits::default();
1467            let invoker = PanickingInputInvoker {
1468                stop: stop_for_worker,
1469            };
1470            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1471                Interpreter::new(limits, crate::test_threads()).run_child(
1472                    "httpprobe",
1473                    Some(stdin),
1474                    &invoker,
1475                    &TreeContext::new(limits, CallBudget::new(16), crate::test_threads())
1476                        .with_cancel(invoker.cancel_signals()),
1477                )
1478            }))
1479            .is_err();
1480            finished.send(panicked).expect("test receives the panic");
1481        });
1482        let answer = result.recv_timeout(std::time::Duration::from_secs(3));
1483        stop.cancel();
1484        if answer.is_err() {
1485            result
1486                .recv_timeout(std::time::Duration::from_secs(3))
1487                .expect("worker cleans up after cancel");
1488        }
1489        worker.join().expect("worker joined before asserting");
1490        assert!(answer.expect("provider panic returns promptly"));
1491    }
1492
1493    #[test]
1494    fn exit_codes_follow_the_documented_mapping() {
1495        assert_eq!(ExitCode::SUCCESS.get(), 0);
1496        assert_eq!(ExitCode::FAILURE.get(), 1);
1497        assert_eq!(ExitCode::SYNTAX.get(), 2);
1498        assert_eq!(ExitCode::TIMEOUT.get(), 124);
1499        assert_eq!(ExitCode::DENIED.get(), 126);
1500        assert_eq!(ExitCode::NOT_FOUND.get(), 127);
1501    }
1502
1503    #[test]
1504    fn capability_results_map_onto_distinct_codes() {
1505        assert_eq!(
1506            ExitCode::from(&CapabilityCallResult::Succeeded),
1507            ExitCode::SUCCESS
1508        );
1509        assert_eq!(
1510            ExitCode::from(&CapabilityCallResult::Failed {
1511                error: "boom".to_owned(),
1512                detail: None
1513            }),
1514            ExitCode::FAILURE
1515        );
1516        assert_eq!(
1517            ExitCode::from(&CapabilityCallResult::Denied {
1518                reason: "policy".to_owned()
1519            }),
1520            ExitCode::DENIED
1521        );
1522        assert_eq!(
1523            ExitCode::from(&CapabilityCallResult::NotFound),
1524            ExitCode::NOT_FOUND
1525        );
1526    }
1527
1528    #[test]
1529    fn script_exit_wraps_like_bash() {
1530        assert_eq!(ExitCode::from_script_exit(0).get(), 0);
1531        assert_eq!(ExitCode::from_script_exit(7).get(), 7);
1532        assert_eq!(ExitCode::from_script_exit(256).get(), 0);
1533        assert_eq!(ExitCode::from_script_exit(257).get(), 1);
1534        assert_eq!(ExitCode::from_script_exit(-1).get(), 255);
1535    }
1536}
1537
1538#[cfg(test)]
1539mod asset_tests;