Skip to main content

aither_sandbox/
policy.rs

1//! Script policies: the embedder's rules on what a script may run.
2//!
3//! The sandbox decides where a script runs and what it can reach; whether a
4//! script should run at all — a toolchain preference, a ban on killing by
5//! name, a rule against polling, an approval for a server — is the
6//! embedder's. Every [`ScriptPolicy`] given to the
7//! [`ShellBuilder`](crate::ShellBuilder) sees each script before it runs, parsed when it
8//! is shell, with the directory it starts in, the call it came from and the
9//! policy's own state for the agent that runs it, and decides [`Pass`],
10//! [`Allow`], [`Ask`] or [`Refuse`]. With no policy the sandbox refuses
11//! nothing, and a script that stays inside the sandbox on the home
12//! environment runs.
13//!
14//! A script that crosses the sandbox boundary — it runs unsandboxed or on a
15//! remote location — runs only after an [`Allow`] or an approved [`Ask`];
16//! with only [`Pass`]es it is asked.
17//!
18//! [`Pass`]: ScriptDecision::Pass
19//! [`Allow`]: ScriptDecision::Allow
20//! [`Ask`]: ScriptDecision::Ask
21//! [`Refuse`]: ScriptDecision::Refuse
22
23use std::fmt;
24use std::future::Future;
25use std::path::PathBuf;
26use std::pin::Pin;
27use std::sync::Arc;
28
29use aither_core::llm::tool::{ApprovalRequest, CallIdentity};
30use schemars::JsonSchema;
31use serde::{Deserialize, Serialize};
32
33use crate::container::ContainerPath;
34use crate::interpreter::Interpreter;
35use crate::shell_syntax::{ShellParseError, ShellScript};
36use crate::terminal::DirectoryResetReason;
37
38/// How a script came to the terminal.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum ScriptOrigin {
41    /// A `terminal` call the caller waits on.
42    Foreground,
43    /// A `terminal` call that detaches the script (`background: true`).
44    Background,
45    /// A [`Shell::run`](crate::Shell::run): the embedder's own script,
46    /// waited on.
47    Run,
48}
49
50// Whether a script runs inside the sandbox. Undocumented in rustdoc: the
51// schema's descriptions are the embedder's.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
53#[serde(rename_all = "snake_case")]
54#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
55pub enum SandboxMode {
56    // Inside the sandbox.
57    #[default]
58    Sandboxed,
59    // Outside it, with the access of the user who runs the agent.
60    Unsandboxed,
61}
62
63impl SandboxMode {
64    /// The mode as a phrase in a sentence about a script.
65    #[must_use]
66    pub const fn description(self) -> &'static str {
67        match self {
68            Self::Sandboxed => "sandboxed",
69            Self::Unsandboxed => "unsandboxed (no sandbox, full access)",
70        }
71    }
72}
73
74/// A directory a script starts or ends in, as the backend that runs it
75/// names it.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum ScriptDir {
78    /// A directory of the host the agent runs on.
79    Host(PathBuf),
80    /// A directory in the container the script runs in.
81    Container {
82        /// The directory as the script sees it.
83        inside: ContainerPath,
84        /// The host side of that directory, for resolving what the script
85        /// names against the host's files.
86        host: PathBuf,
87    },
88    /// The script runs on a remote server, whose directories the sandbox
89    /// does not follow.
90    Remote {
91        /// The name of the server, as the call gave it as its `location`.
92        server: String,
93    },
94}
95
96impl ScriptDir {
97    /// The directory on the host the script's relative paths resolve
98    /// against; `None` for a script that runs on a remote server.
99    #[must_use]
100    pub fn host(&self) -> Option<&std::path::Path> {
101        match self {
102            Self::Host(dir) | Self::Container { host: dir, .. } => Some(dir),
103            Self::Remote { .. } => None,
104        }
105    }
106}
107
108/// A script about to run, as a [`ScriptPolicy`] and the shell's
109/// [`TreatOutput`](crate::TreatOutput) see it.
110#[derive(Debug, Clone, Copy)]
111pub struct ScriptCheck<'a> {
112    /// The id the script's task gets when it runs; the [`ScriptEnd`] that
113    /// reports how it ended carries the same id.
114    pub task_id: &'a str,
115    /// The script as written.
116    pub script: &'a str,
117    /// The language it is written in.
118    pub interpreter: Interpreter,
119    /// The script parsed as shell: `None` for a script in another language,
120    /// an error when it is not valid shell.
121    pub shell: Option<Result<&'a ShellScript, &'a ShellParseError>>,
122    /// How the script came to the terminal.
123    pub origin: ScriptOrigin,
124    /// Whether the script runs inside the sandbox.
125    pub sandbox: SandboxMode,
126    /// The configured server the script runs on; `None` for the home
127    /// environment.
128    pub location: Option<&'a str>,
129    /// The directory the script starts in, fixed when the script was
130    /// admitted: for a foreground script of the main agent the directory the
131    /// shell carried from the previous one, for a run the directory it
132    /// names, otherwise the terminal's own directory. The launch starts in
133    /// the same directory.
134    pub start: &'a ScriptDir,
135    /// The tool call that carries the script and the agent that made it,
136    /// when the caller identified one.
137    pub call: Option<&'a CallIdentity>,
138}
139
140/// How a script a [`ScriptPolicy`] was asked about ended.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum ScriptOutcome {
143    /// It never started: a policy, the command gate or an approval refused
144    /// it, or its launch could not be prepared.
145    NotRun,
146    /// It started but could not be run to an exit status.
147    Failed,
148    /// It exited with `code`.
149    Exited {
150        /// The exit status.
151        code: i32,
152    },
153}
154
155/// What a script did to the directory the shell carries to the next
156/// foreground script.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum Carry {
159    /// The shell ended in another directory, which the next foreground
160    /// script starts in.
161    Moved,
162    /// The directory the shell ended in is not carried; the next script
163    /// starts where this one did.
164    Reset(DirectoryResetReason),
165    /// The shell ended where the script started.
166    Unchanged,
167    /// The script carries nothing: it ran in the background, failed to
168    /// start or was refused, or the terminal carries no directory.
169    NotCarried,
170}
171
172/// The end of a script a [`ScriptPolicy`] was asked about.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct ScriptEnd<'a> {
175    /// The task id the [`ScriptCheck`] carried.
176    pub task_id: &'a str,
177    /// How it ended.
178    pub outcome: ScriptOutcome,
179    /// The directory the terminal's next foreground script starts in now
180    /// this one has ended, settled under the lock that updates the carried
181    /// directory: the end of one script is the start of the next, whatever
182    /// calls run in parallel.
183    pub end: &'a ScriptDir,
184    /// What the script did to the carried directory.
185    pub carry: Carry,
186}
187
188/// A script a [`ScriptPolicy`] refused; the model reads [`Self::text`] as
189/// the call's result.
190///
191/// Tools return it as their error, so an agent loop tells a policy's
192/// refusal from any other failure by downcasting.
193#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
194#[error("{text}")]
195pub struct ScriptRefusal {
196    text: String,
197}
198
199impl ScriptRefusal {
200    /// A refusal the model reads as `text`.
201    #[must_use]
202    pub fn new(text: impl Into<String>) -> Self {
203        Self { text: text.into() }
204    }
205
206    /// The text the model reads.
207    #[must_use]
208    pub fn text(&self) -> &str {
209        &self.text
210    }
211}
212
213/// What a [`ScriptPolicy`] decided about one script.
214///
215/// When several policies decide, the strictest wins: [`Refuse`], then
216/// [`Ask`], then [`Allow`], then [`Pass`].
217///
218/// [`Pass`]: Self::Pass
219/// [`Allow`]: Self::Allow
220/// [`Ask`]: Self::Ask
221/// [`Refuse`]: Self::Refuse
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum ScriptDecision {
224    /// The policy has no opinion on the script.
225    Pass,
226    /// The policy approves the script: one that crosses the sandbox
227    /// boundary runs without being asked.
228    Allow,
229    /// The script runs only if the approver approves `request`.
230    Ask(ApprovalRequest),
231    /// The script does not run; the model reads the refusal in its place.
232    Refuse(ScriptRefusal),
233}
234
235impl ScriptDecision {
236    const fn strictness(&self) -> u8 {
237        match self {
238            Self::Pass => 0,
239            Self::Allow => 1,
240            Self::Ask(_) => 2,
241            Self::Refuse(_) => 3,
242        }
243    }
244
245    /// Folds `decisions`, in registration order, into the strictest; of
246    /// equally strict ones the first stands, so the model reads the first
247    /// refusal and the approver is asked the first question.
248    #[must_use]
249    pub fn strictest(decisions: impl IntoIterator<Item = Self>) -> Self {
250        decisions
251            .into_iter()
252            .fold(Self::Pass, |strictest, decision| {
253                if decision.strictness() > strictest.strictness() {
254                    decision
255                } else {
256                    strictest
257                }
258            })
259    }
260}
261
262/// Decides whether a script may run, before it does.
263///
264/// Every script of the `terminal` tool, the main agent's and every
265/// subagent's, and every [`Shell::run`](crate::Shell::run),
266/// is put to every policy of its shell ahead of the approval it needs. The
267/// policies of one shell decide concurrently and the strictest decision wins.
268///
269/// A policy keeps what it remembers in its [`State`](Self::State): every
270/// agent's terminal, each subagent's included, starts with a fresh one and
271/// shares it with nobody else. Calls run in parallel, so the state is shared
272/// by reference and the policy chooses how to synchronise it.
273pub trait ScriptPolicy: Send + Sync + 'static {
274    /// What the policy remembers for one agent.
275    type State: Default + Send + Sync + 'static;
276
277    /// Decides on `script`.
278    fn check(
279        &self,
280        script: &ScriptCheck<'_>,
281        state: &Self::State,
282    ) -> impl Future<Output = ScriptDecision> + Send;
283
284    /// Told once how every script put to [`Self::check`] ended, whichever
285    /// policy decided what: refused, never started, failed or exited. The
286    /// result of a foreground script reaches the caller only after this
287    /// returns, so a state it records holds for the agent's next call; a
288    /// background script's end is told after its call returned.
289    fn ended(&self, end: &ScriptEnd<'_>, state: &Self::State) -> impl Future<Output = ()> + Send {
290        let _ = (end, state);
291        std::future::ready(())
292    }
293}
294
295/// Object-safe twin of [`ScriptPolicy`]: the policy, before it is bound to
296/// an agent.
297trait ScriptPolicyImpl: Send + Sync {
298    fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl>;
299}
300
301impl<T: ScriptPolicy> ScriptPolicyImpl for T {
302    fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl> {
303        Arc::new(Bound {
304            policy: self,
305            state: T::State::default(),
306        })
307    }
308}
309
310/// A policy with one agent's state.
311struct Bound<T: ScriptPolicy> {
312    policy: Arc<T>,
313    state: T::State,
314}
315
316trait BoundPolicyImpl: Send + Sync {
317    fn check<'a>(
318        &'a self,
319        script: &'a ScriptCheck<'a>,
320    ) -> Pin<Box<dyn Future<Output = ScriptDecision> + Send + 'a>>;
321
322    fn ended<'a>(&'a self, end: &'a ScriptEnd<'a>)
323    -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
324}
325
326impl<T: ScriptPolicy> BoundPolicyImpl for Bound<T> {
327    fn check<'a>(
328        &'a self,
329        script: &'a ScriptCheck<'a>,
330    ) -> Pin<Box<dyn Future<Output = ScriptDecision> + Send + 'a>> {
331        Box::pin(self.policy.check(script, &self.state))
332    }
333
334    fn ended<'a>(
335        &'a self,
336        end: &'a ScriptEnd<'a>,
337    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
338        Box::pin(self.policy.ended(end, &self.state))
339    }
340}
341
342/// A type-erased [`ScriptPolicy`].
343#[derive(Clone)]
344pub struct AnyScriptPolicy(Arc<dyn ScriptPolicyImpl>);
345
346impl AnyScriptPolicy {
347    /// Erases `policy`.
348    #[must_use]
349    pub fn new(policy: impl ScriptPolicy) -> Self {
350        Self(Arc::new(policy))
351    }
352}
353
354impl fmt::Debug for AnyScriptPolicy {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        f.write_str("AnyScriptPolicy")
357    }
358}
359
360/// A shell's policies, each bound to the state of the agent the shell
361/// serves.
362#[derive(Clone, Default)]
363pub struct ScriptPolicies {
364    policies: Arc<[AnyScriptPolicy]>,
365    bound: Arc<[Arc<dyn BoundPolicyImpl>]>,
366}
367
368impl ScriptPolicies {
369    /// `policies`, bound to a fresh agent.
370    #[must_use]
371    pub fn new(policies: Vec<AnyScriptPolicy>) -> Self {
372        let policies: Arc<[AnyScriptPolicy]> = policies.into();
373        Self {
374            bound: Self::bind(&policies),
375            policies,
376        }
377    }
378
379    fn bind(policies: &[AnyScriptPolicy]) -> Arc<[Arc<dyn BoundPolicyImpl>]> {
380        policies
381            .iter()
382            .map(|policy| policy.0.clone().bind())
383            .collect()
384    }
385
386    /// The same policies, bound to another agent with fresh state.
387    #[must_use]
388    pub fn for_agent(&self) -> Self {
389        Self {
390            policies: self.policies.clone(),
391            bound: Self::bind(&self.policies),
392        }
393    }
394
395    /// Whether no policy is registered.
396    #[must_use]
397    pub fn is_empty(&self) -> bool {
398        self.bound.is_empty()
399    }
400
401    /// Puts `script` to every policy; the strictest decision wins, the
402    /// first of equally strict ones in registration order.
403    pub async fn check(&self, script: &ScriptCheck<'_>) -> ScriptDecision {
404        let decisions =
405            futures::future::join_all(self.bound.iter().map(|policy| policy.check(script))).await;
406        ScriptDecision::strictest(decisions)
407    }
408
409    /// Tells every policy how a checked script ended, and where the
410    /// terminal's next foreground script starts.
411    pub async fn ended(
412        &self,
413        task_id: &str,
414        outcome: ScriptOutcome,
415        end: &ScriptDir,
416        carry: Carry,
417    ) {
418        if self.is_empty() {
419            return;
420        }
421        let end = ScriptEnd {
422            task_id,
423            outcome,
424            end,
425            carry,
426        };
427        futures::future::join_all(self.bound.iter().map(|policy| policy.ended(&end))).await;
428    }
429}
430
431impl fmt::Debug for ScriptPolicies {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.debug_struct("ScriptPolicies")
434            .field("policies", &self.policies.len())
435            .finish_non_exhaustive()
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use std::sync::atomic::{AtomicUsize, Ordering};
442
443    use aither_core::llm::tool::ApprovalKind;
444
445    use super::*;
446
447    /// Refuses every script after the first `allowed` its agent ran.
448    struct Quota {
449        allowed: usize,
450    }
451
452    impl ScriptPolicy for Quota {
453        type State = AtomicUsize;
454
455        fn check(
456            &self,
457            _script: &ScriptCheck<'_>,
458            state: &AtomicUsize,
459        ) -> impl Future<Output = ScriptDecision> + Send {
460            std::future::ready(if state.fetch_add(1, Ordering::SeqCst) < self.allowed {
461                ScriptDecision::Allow
462            } else {
463                ScriptDecision::Refuse(ScriptRefusal::new("over quota"))
464            })
465        }
466    }
467
468    /// Decides the same way on every script.
469    struct Always(ScriptDecision);
470
471    impl ScriptPolicy for Always {
472        type State = ();
473
474        fn check(
475            &self,
476            _script: &ScriptCheck<'_>,
477            (): &(),
478        ) -> impl Future<Output = ScriptDecision> + Send {
479            std::future::ready(self.0.clone())
480        }
481    }
482
483    fn refuse(text: &str) -> ScriptDecision {
484        ScriptDecision::Refuse(ScriptRefusal::new(text))
485    }
486
487    fn ask(subject: &str) -> ScriptDecision {
488        ScriptDecision::Ask(ApprovalRequest::new(ApprovalKind::new("test"), subject))
489    }
490
491    fn check(task_id: &str) -> ScriptCheck<'_> {
492        static START: std::sync::LazyLock<ScriptDir> =
493            std::sync::LazyLock::new(|| ScriptDir::Host(PathBuf::from("/")));
494        ScriptCheck {
495            task_id,
496            script: "true",
497            interpreter: Interpreter::Shell,
498            shell: None,
499            origin: ScriptOrigin::Foreground,
500            sandbox: SandboxMode::Sandboxed,
501            location: None,
502            start: &START,
503            call: None,
504        }
505    }
506
507    fn policies(decisions: impl IntoIterator<Item = ScriptDecision>) -> ScriptPolicies {
508        ScriptPolicies::new(
509            decisions
510                .into_iter()
511                .map(|decision| AnyScriptPolicy::new(Always(decision)))
512                .collect(),
513        )
514    }
515
516    #[tokio::test]
517    async fn each_agent_binds_fresh_state() {
518        let main = ScriptPolicies::new(vec![AnyScriptPolicy::new(Quota { allowed: 1 })]);
519        let view = main.clone();
520        let subagent = main.for_agent();
521        assert_eq!(main.check(&check("a")).await, ScriptDecision::Allow);
522        assert_eq!(main.check(&check("b")).await, refuse("over quota"));
523        assert!(
524            matches!(view.check(&check("c")).await, ScriptDecision::Refuse(_)),
525            "a view of the main agent's registry shares its state"
526        );
527        assert_eq!(
528            subagent.check(&check("d")).await,
529            ScriptDecision::Allow,
530            "the subagent's state is its own"
531        );
532    }
533
534    #[tokio::test]
535    async fn the_strictest_decision_wins() {
536        let order = [
537            ScriptDecision::Pass,
538            ScriptDecision::Allow,
539            ask("first question"),
540            refuse("first refusal"),
541        ];
542        // Whatever the registration order, the stricter of two stands.
543        for (weak, strong) in order
544            .iter()
545            .enumerate()
546            .flat_map(|(i, weak)| order[i + 1..].iter().map(move |strong| (weak, strong)))
547        {
548            for pair in [[weak, strong], [strong, weak]] {
549                let policies = policies(pair.into_iter().cloned());
550                assert_eq!(&policies.check(&check("a")).await, strong);
551            }
552        }
553        assert_eq!(
554            policies([ScriptDecision::Allow, ScriptDecision::Pass])
555                .check(&check("b"))
556                .await,
557            ScriptDecision::Allow
558        );
559    }
560
561    #[tokio::test]
562    async fn the_first_of_equally_strict_decisions_in_registration_order_stands() {
563        let policies = policies([
564            ScriptDecision::Allow,
565            ask("first question"),
566            ask("second question"),
567            refuse("first refusal"),
568            refuse("second refusal"),
569        ]);
570        assert_eq!(policies.check(&check("a")).await, refuse("first refusal"));
571        let asking = super::ScriptPolicies::new(vec![
572            AnyScriptPolicy::new(Always(ask("first question"))),
573            AnyScriptPolicy::new(Always(ask("second question"))),
574        ]);
575        assert_eq!(asking.check(&check("b")).await, ask("first question"));
576        assert!(ScriptPolicies::default().is_empty());
577        assert_eq!(
578            ScriptPolicies::default().check(&check("c")).await,
579            ScriptDecision::Pass
580        );
581    }
582}