aither-sandbox 0.28.0

Terminal-first command execution with heel sandboxing
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
//! Permission handling for terminal execution modes.
//!
//! Different terminal modes have different permission requirements:
//! - `Sandboxed`: No approval needed; outbound network is available by
//!   default, filtered per-domain via [`PermissionHandler::check_domain`]
//!   and audited by higher layers
//! - `Unsafe`: Per-script approval required

use std::future::Future;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::CommandRole;
use crate::script_language::ScriptLanguage;
use crate::ssh::SshServer;

/// Permission mode for terminal execution.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TerminalMode {
    /// Sandboxed execution without extra host privileges.
    ///
    /// Outbound network is available by default, filtered per-domain through
    /// the configured network policy and always audited.
    #[default]
    Sandboxed,

    /// Unsafe execution without sandbox.
    /// Full system access. Requires per-script approval.
    Unsafe,
}

impl TerminalMode {
    /// Returns whether this mode requires user approval.
    #[must_use]
    pub const fn requires_approval(self) -> bool {
        matches!(self, Self::Unsafe)
    }

    /// Returns whether approval is needed per-script (vs first-use only).
    #[must_use]
    pub const fn requires_per_script_approval(self) -> bool {
        matches!(self, Self::Unsafe)
    }

    /// Returns a human-readable description of this mode.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::Sandboxed => "sandboxed",
            Self::Unsafe => "unsafe (no sandbox, full access)",
        }
    }
}

/// A request for a permission beyond the sandbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PermissionRequest<'a> {
    /// A command that needs a mode beyond the sandbox.
    Command {
        /// The mode the command needs.
        mode: TerminalMode,
        /// The script to run.
        script: &'a str,
        /// The language the script is written in.
        language: ScriptLanguage,
    },
    /// A sandboxed command's connection to a network domain that is not
    /// already allowed.
    Domain {
        /// The host being connected to.
        domain: &'a str,
        /// The port being connected to.
        port: u16,
    },
    /// The first command on an SSH server: whether commands may run there at
    /// all. Approving it lets the terminal connect and prepare the server:
    /// the managed tools in its cache directory and, when it has no `heel`,
    /// the distribution's pinned `heel` for its platform in
    /// `~/.local/bin`. Once approved, the server's later commands, a
    /// subagent's included, are not asked about again while it stays in the
    /// registry; each still passes the admission its mode needs.
    Location {
        /// The server the command names.
        server: &'a SshServer,
        /// Who asks: the main agent or a subagent.
        role: CommandRole,
    },
}

/// How [`PermissionHandler::review`] decided a request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Review {
    /// Granted; nothing else is asked.
    Approved,
    /// Refused, with the reason the model reads.
    Denied(String),
    /// Not decided; the request goes on to the handler's own route.
    Passed,
}

/// Trait for handling permission requests.
///
/// Implementors decide whether to allow terminal executions based on mode and script.
pub trait PermissionHandler: Send + Sync {
    /// Checks if the given mode and script are allowed.
    ///
    /// For `Sandboxed` mode, this should always return `Ok(true)`.
    /// For `Unsafe` mode, this should prompt for each script, which is
    /// source in `language`.
    fn check(
        &self,
        mode: TerminalMode,
        script: &str,
        language: ScriptLanguage,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send;

    /// Returns whether `check` will suspend waiting for an external approval.
    ///
    /// This is used by higher-level runtimes to surface pause/resume lifecycle
    /// events only when a permission request will actually block.
    fn will_wait_for_approval(
        &self,
        mode: TerminalMode,
        script: &str,
        language: ScriptLanguage,
    ) -> impl Future<Output = bool> + Send {
        let _ = (mode, script, language);
        async { false }
    }

    /// Decides `request` before the handler's own route is asked.
    ///
    /// The terminal calls this first for every command that needs a mode
    /// beyond the sandbox and for every domain for which
    /// [`domain_needs_approval`](Self::domain_needs_approval) holds. Only a
    /// request this passes reaches [`will_wait_for_approval`](Self::will_wait_for_approval)
    /// and [`check`](Self::check) or [`check_domain`](Self::check_domain), so
    /// a request decided here never reports waiting on anyone.
    ///
    /// The default passes every request.
    fn review(&self, request: &PermissionRequest<'_>) -> impl Future<Output = Review> + Send {
        let _ = request;
        async { Review::Passed }
    }

    /// The handler a subagent's terminal uses, when it must differ from the
    /// one its launcher uses (for example because it labels who is asking).
    ///
    /// `None`, the default, means the subagent shares this handler, so its
    /// requests reach exactly the route the launcher's do.
    fn for_subagent(&self) -> Option<Self>
    where
        Self: Sized,
    {
        None
    }

    /// Whether commands may run on `server`, asked once by the first command
    /// that names it, after [`review`](Self::review) passed the
    /// [`PermissionRequest::Location`]. `role` says whether a subagent asks,
    /// so the handler can put a subagent's request to its main agent.
    ///
    /// Default implementation denies every server (fail-safe).
    fn check_location(
        &self,
        server: &SshServer,
        role: CommandRole,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send {
        let _ = (server, role);
        async { Ok(false) }
    }

    /// Whether [`check_location`](Self::check_location) will suspend waiting
    /// for someone's decision, as opposed to answering from a decision it
    /// remembers or a fixed policy. The default is `false`.
    fn will_wait_for_location(
        &self,
        server: &SshServer,
        role: CommandRole,
    ) -> impl Future<Output = bool> + Send {
        let _ = (server, role);
        async { false }
    }

    /// Checks if a network domain is allowed.
    ///
    /// Called for each network connection attempt in `Sandboxed` mode.
    /// The implementation may prompt the user, check against a whitelist, etc.
    ///
    /// Default implementation denies all domains (fail-safe).
    fn check_domain(&self, domain: &str, port: u16) -> impl Future<Output = bool> + Send {
        let _ = (domain, port);
        async { false }
    }

    /// Whether [`check_domain`](Self::check_domain) would have to ask
    /// someone about this domain, as opposed to deciding it silently (a
    /// default allow-list, a domain already approved, a fixed policy).
    ///
    /// Only such a domain is put to [`review`](Self::review). The default
    /// is `false`.
    fn domain_needs_approval(&self, domain: &str, port: u16) -> impl Future<Output = bool> + Send {
        let _ = (domain, port);
        async { false }
    }

    /// Records that `domain` was approved by a reviewer, the way the handler
    /// records a domain its user approved, so that
    /// [`domain_needs_approval`](Self::domain_needs_approval) no longer holds
    /// for it. A handler whose `domain_needs_approval` can hold implements
    /// this; the default does nothing.
    fn remember_domain(&self, domain: &str, port: u16) -> impl Future<Output = ()> + Send {
        let _ = (domain, port);
        async {}
    }

    /// The decision for a connection to `domain`: the review step first, for
    /// a domain that needs approval, then [`check_domain`](Self::check_domain).
    ///
    /// The terminal's network policy calls this. A handler wrapping another
    /// forwards the individual methods and leaves this one provided.
    fn authorize_domain(&self, domain: &str, port: u16) -> impl Future<Output = bool> + Send {
        async move {
            if self.domain_needs_approval(domain, port).await {
                match self
                    .review(&PermissionRequest::Domain { domain, port })
                    .await
                {
                    Review::Approved => {
                        self.remember_domain(domain, port).await;
                        return true;
                    }
                    Review::Denied(reason) => {
                        tracing::info!(domain, port, %reason, "network domain denied by review");
                        return false;
                    }
                    Review::Passed => {}
                }
            }
            self.check_domain(domain, port).await
        }
    }
}

/// Error type for permission operations.
#[derive(Debug, thiserror::Error)]
pub enum PermissionError {
    /// Permission was denied by the user.
    #[error("permission denied: {0}")]
    Denied(String),

    /// Permission check was interrupted.
    #[error("permission check interrupted")]
    Interrupted,

    /// Internal error during permission check.
    #[error("permission error: {0}")]
    Internal(#[from] anyhow::Error),
}

/// A simple permission handler that allows all sandboxed operations
/// and denies everything else.
#[derive(Debug, Clone, Copy, Default)]
pub struct DenyUnsafe;

impl PermissionHandler for DenyUnsafe {
    fn check(
        &self,
        mode: TerminalMode,
        _script: &str,
        _language: ScriptLanguage,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send {
        std::future::ready(match mode {
            TerminalMode::Sandboxed => Ok(true),
            TerminalMode::Unsafe => Err(PermissionError::Denied(format!(
                "sandbox blocked {} execution; approval is required to escalate this command, but no interactive approval handler is configured",
                mode.description()
            ))),
        })
    }

    fn will_wait_for_approval(
        &self,
        _mode: TerminalMode,
        _script: &str,
        _language: ScriptLanguage,
    ) -> impl Future<Output = bool> + Send {
        std::future::ready(false)
    }
}

/// A no-op permission handler that allows every execution mode and domain.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopPermissionHandler;

impl PermissionHandler for NoopPermissionHandler {
    fn check(
        &self,
        _mode: TerminalMode,
        _script: &str,
        _language: ScriptLanguage,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send {
        std::future::ready(Ok(true))
    }

    fn will_wait_for_approval(
        &self,
        _mode: TerminalMode,
        _script: &str,
        _language: ScriptLanguage,
    ) -> impl Future<Output = bool> + Send {
        std::future::ready(false)
    }

    fn check_domain(&self, _domain: &str, _port: u16) -> impl Future<Output = bool> + Send {
        std::future::ready(true)
    }

    fn check_location(
        &self,
        _server: &SshServer,
        _role: CommandRole,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send {
        std::future::ready(Ok(true))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_deny_unsafe() {
        let handler = DenyUnsafe;

        // Sandboxed should be allowed
        assert!(
            handler
                .check(TerminalMode::Sandboxed, "ls", ScriptLanguage::Shell)
                .await
                .unwrap()
        );

        // Unsafe should be denied
        assert!(
            handler
                .check(TerminalMode::Unsafe, "rm -rf /", ScriptLanguage::Shell)
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn test_noop_permission_handler() {
        let handler = NoopPermissionHandler;

        assert!(
            handler
                .check(TerminalMode::Sandboxed, "ls", ScriptLanguage::Shell)
                .await
                .unwrap()
        );
        assert!(
            handler
                .check(TerminalMode::Unsafe, "rm -rf /", ScriptLanguage::Shell)
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_deny_unsafe_check_domain() {
        let handler = DenyUnsafe;

        // Default implementation denies all domains
        assert!(!handler.check_domain("example.com", 443).await);
        assert!(!handler.check_domain("api.github.com", 80).await);
    }

    #[tokio::test]
    async fn only_the_noop_handler_allows_a_location_by_default() {
        let server = SshServer {
            name: "build".to_string(),
            target: "builder@build.internal".to_string(),
        };
        assert!(
            !DenyUnsafe
                .check_location(&server, CommandRole::Main)
                .await
                .unwrap()
        );
        assert!(
            NoopPermissionHandler
                .check_location(&server, CommandRole::Subagent)
                .await
                .unwrap()
        );
    }

    #[test]
    fn a_location_request_names_the_server_and_who_asks() {
        let server = SshServer {
            name: "build".to_string(),
            target: "builder@build.internal".to_string(),
        };
        assert_eq!(
            serde_json::to_value(PermissionRequest::Location {
                server: &server,
                role: CommandRole::Subagent,
            })
            .unwrap(),
            serde_json::json!({
                "kind": "location",
                "server": { "name": "build", "target": "builder@build.internal" },
                "role": "subagent",
            })
        );
    }

    #[tokio::test]
    async fn test_noop_permission_handler_check_domain() {
        let handler = NoopPermissionHandler;

        // NoopPermissionHandler allows all domains
        assert!(handler.check_domain("example.com", 443).await);
        assert!(handler.check_domain("malicious.com", 80).await);
    }
}