Skip to main content

adk_harness/shell/
mod.rs

1//! Shell isolation and the per-session shell ledger (spec 3.1 §7.9).
2//!
3//! The shell follows the pattern Claude Code uses: the OS sandbox is off by default,
4//! host commands run behind per-command approval, the sandbox is opt-in, and a strict
5//! deployment can fail at startup when it is unavailable.
6
7mod background;
8#[cfg(any(feature = "docker", feature = "remote-shell"))]
9mod container;
10mod gate;
11mod ledger;
12#[cfg(feature = "sandbox")]
13mod os_sandbox;
14mod output;
15mod pids;
16mod protect;
17#[cfg(feature = "remote-shell")]
18mod remote;
19
20use std::fmt;
21
22use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
23use serde::{Deserialize, Serialize};
24
25pub use background::{
26    BackgroundShellConfig, MAX_UNATTENDED_SHELL_LIFETIME, SHELL_KILL, ShellInfo, ShellKillCause,
27    ShellKillTool, ShellStatus, ShellSupervisor,
28};
29pub(crate) use background::{Launch, LedgerNote, supervisor};
30#[cfg(any(feature = "docker", feature = "remote-shell"))]
31pub use container::ContainerBashTool;
32#[cfg(any(feature = "docker", feature = "remote-shell"))]
33pub(crate) use container::{ContainerCheckRefusal, ContainerPool, PoolSource};
34#[cfg(feature = "docker")]
35pub use container::{ContainerConfig, DEFAULT_CONTAINER_IMAGE};
36pub(crate) use gate::FileToolGate;
37#[cfg(feature = "sqlite")]
38pub use ledger::SqliteShellLedger;
39pub use ledger::{InMemoryShellLedger, ShellLedger, ShellLedgerEntry};
40#[cfg(feature = "sandbox")]
41pub use os_sandbox::{OsSandboxConfig, SandboxAccess, SandboxLauncher};
42pub use output::{SHELL_OUTPUT, ShellOutputTool, ShellOutputs};
43#[cfg(feature = "sqlite")]
44pub use pids::SqliteShellPidRegistry;
45pub use pids::{InMemoryShellPidRegistry, ShellPidRecord, ShellPidRegistry, reap_orphaned_shells};
46pub use protect::SANDBOX_PROTECTED_PATHS;
47pub(crate) use protect::protected_paths;
48#[cfg(feature = "remote-shell")]
49pub use remote::RemoteShellConfig;
50
51use crate::policy::Isolation;
52
53/// Error code of a requested sandbox that is not available (spec 3.1 §7.9).
54///
55/// # Example
56///
57/// ```rust
58/// assert_eq!(adk_harness::SANDBOX_UNAVAILABLE_CODE, "harness.sandbox_unavailable");
59/// ```
60pub const SANDBOX_UNAVAILABLE_CODE: &str = "harness.sandbox_unavailable";
61
62/// Where `bash` runs (spec 3.1 §7.9).
63///
64/// # Example
65///
66/// ```rust
67/// use adk_harness::ShellIsolation;
68///
69/// assert!(matches!(ShellIsolation::default(), ShellIsolation::Host));
70/// ```
71#[derive(Clone, Debug, Default)]
72#[non_exhaustive]
73pub enum ShellIsolation {
74    /// The devtools `bash` on the host, governed per call. The default.
75    #[default]
76    Host,
77    /// The OS sandbox (Seatbelt on macOS, bubblewrap on Linux).
78    #[cfg(feature = "sandbox")]
79    OsSandbox(OsSandboxConfig),
80    /// A container per session, with the workspace mounted at `/workspace`.
81    #[cfg(feature = "docker")]
82    Container(ContainerConfig),
83    /// An environment per session from a [`SandboxClient`](adk_sandbox::workspace::SandboxClient)
84    /// off this host — an E2B or Daytona microVM or a Modal Sandbox — with its own filesystem.
85    #[cfg(feature = "remote-shell")]
86    Remote(RemoteShellConfig),
87}
88
89impl ShellIsolation {
90    /// The requested isolation's name, as audit records and `IsolationStatus::Degraded`
91    /// report it.
92    pub fn requested_name(&self) -> &'static str {
93        match self {
94            Self::Host => "host",
95            #[cfg(feature = "sandbox")]
96            Self::OsSandbox(_) => "os_sandbox",
97            #[cfg(feature = "docker")]
98            Self::Container(_) => "container",
99            #[cfg(feature = "remote-shell")]
100            Self::Remote(_) => "remote",
101        }
102    }
103}
104
105/// How the harness shell is configured (spec 3.1 §7.9).
106///
107/// # Example
108///
109/// ```rust
110/// use adk_harness::ShellConfig;
111///
112/// let config = ShellConfig::default();
113/// assert!(!config.fail_if_unavailable);
114/// assert!(config.allow_unsandboxed_retry);
115/// ```
116#[derive(Clone, Debug)]
117pub struct ShellConfig {
118    /// Where commands run.
119    pub isolation: ShellIsolation,
120    /// Refuse to build, and refuse each call, when the requested sandbox is unavailable.
121    pub fail_if_unavailable: bool,
122    /// Run sandboxed commands without approval in Ask (spec 3.1 §9.2 I26). Turns on only
123    /// when the enforcer passes the nested read-only conformance probe (adk-sandbox S3) —
124    /// for a container, when its protected paths are mounted read-only — the sandbox
125    /// denies the network and every root-level protected path exists; the build fails
126    /// otherwise, naming the reason. No effect on the host or a degraded shell.
127    pub auto_allow_sandboxed: bool,
128    /// Offer an unsandboxed retry of a failed sandboxed command, behind a one-time
129    /// approval. `true` for host and OS sandbox, `false` for containers.
130    pub allow_unsandboxed_retry: bool,
131    /// Run host commands without approval in Auto.
132    pub allow_host_shell_in_auto: bool,
133}
134
135impl Default for ShellConfig {
136    fn default() -> Self {
137        Self {
138            isolation: ShellIsolation::Host,
139            fail_if_unavailable: false,
140            auto_allow_sandboxed: false,
141            allow_unsandboxed_retry: true,
142            allow_host_shell_in_auto: false,
143        }
144    }
145}
146
147/// The isolation `bash` actually runs under (spec 3.1 §7.9).
148///
149/// # Example
150///
151/// ```rust
152/// use adk_harness::IsolationStatus;
153///
154/// let degraded = IsolationStatus::Degraded { requested: "os_sandbox".into(), reason: "no bwrap".into() };
155/// assert!(degraded.behaves_as_host());
156/// assert_eq!(degraded.enforcer(), "host");
157/// ```
158#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(tag = "kind", rename_all = "camelCase")]
160#[non_exhaustive]
161pub enum IsolationStatus {
162    /// The host shell.
163    Host,
164    /// An active OS sandbox enforcer.
165    OsSandbox {
166        /// The enforcer's name (`seatbelt`, `bubblewrap`).
167        enforcer: String,
168    },
169    /// A container.
170    Container {
171        /// The container image.
172        image: String,
173    },
174    /// An environment from a sandbox client: a remote provider's microVM, or a client that
175    /// runs on this host.
176    Remote {
177        /// The client's provider name (`SandboxClient::provider`).
178        provider: String,
179        /// The environment runs off this host, so commands cannot reach the host's files.
180        #[serde(rename = "offHost")]
181        off_host: bool,
182    },
183    /// A sandbox was requested and is unavailable; commands run on the host.
184    Degraded {
185        /// The requested isolation.
186        requested: String,
187        /// Why it is unavailable.
188        reason: String,
189    },
190}
191
192impl IsolationStatus {
193    /// Whether commands run on the host.
194    pub fn behaves_as_host(&self) -> bool {
195        matches!(self, Self::Host | Self::Degraded { .. } | Self::Remote { off_host: false, .. })
196    }
197
198    /// The enforcer name recorded in audit records and annotations.
199    pub fn enforcer(&self) -> &str {
200        match self {
201            Self::Host | Self::Degraded { .. } => "host",
202            Self::OsSandbox { enforcer } => enforcer,
203            Self::Container { .. } => "container",
204            Self::Remote { .. } => "remote",
205        }
206    }
207
208    /// Whether the isolation confines the command's reads to the paths it grants: Seatbelt,
209    /// bubblewrap and a container do; the host, a degraded sandbox and the Windows
210    /// restricted-token sandbox, which reads what the user may read (spec 3.2 §10 W5), do not.
211    ///
212    /// # Example
213    ///
214    /// ```rust
215    /// use adk_harness::IsolationStatus;
216    ///
217    /// assert!(IsolationStatus::OsSandbox { enforcer: "seatbelt".into() }.confines_reads());
218    /// assert!(!IsolationStatus::OsSandbox { enforcer: "restricted-token".into() }.confines_reads());
219    /// assert!(!IsolationStatus::Host.confines_reads());
220    /// ```
221    pub fn confines_reads(&self) -> bool {
222        match self {
223            Self::Host | Self::Degraded { .. } => false,
224            Self::OsSandbox { enforcer } => enforcer != RESTRICTED_TOKEN,
225            Self::Container { .. } => true,
226            Self::Remote { off_host, .. } => *off_host,
227        }
228    }
229
230    /// Whether the isolation keeps every MSYS2 or Cygwin installation the command can start
231    /// apart from the user's own programs of it. The Windows restricted-token sandbox keeps
232    /// the shell's installation and those on its `PATH` apart, but a command that starts
233    /// another installation's program by its path can create that installation's namespace
234    /// for the user's next program of it to join (spec 3.2 §10 W5); the host shares them all.
235    ///
236    /// # Example
237    ///
238    /// ```rust
239    /// use adk_harness::IsolationStatus;
240    ///
241    /// assert!(IsolationStatus::OsSandbox { enforcer: "seatbelt".into() }.isolates_msys2());
242    /// assert!(!IsolationStatus::OsSandbox { enforcer: "restricted-token".into() }.isolates_msys2());
243    /// assert!(!IsolationStatus::Host.isolates_msys2());
244    /// ```
245    pub fn isolates_msys2(&self) -> bool {
246        self.confines_reads()
247    }
248
249    /// The policy's isolation class for this status.
250    pub fn isolation(&self) -> Isolation {
251        match self {
252            Self::Host | Self::Degraded { .. } => Isolation::Host,
253            Self::OsSandbox { .. } => Isolation::OsSandbox,
254            // An environment off the host is governed as a container is; one on the host as
255            // the host shell is.
256            Self::Container { .. } | Self::Remote { off_host: true, .. } => Isolation::Container,
257            Self::Remote { off_host: false, .. } => Isolation::Host,
258        }
259    }
260}
261
262/// The Windows restricted-token enforcer, which leaves the network open, does not confine
263/// reads and keeps only the MSYS2 installations of the shell and its `PATH` apart (spec 3.2
264/// §10 W5).
265const RESTRICTED_TOKEN: &str = "restricted-token";
266
267impl fmt::Display for IsolationStatus {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::Host => f.write_str("host (full user permissions, network)"),
271            Self::OsSandbox { enforcer } if enforcer == RESTRICTED_TOKEN => {
272                write!(
273                    f,
274                    "OS sandbox ({enforcer}, network not restricted, reads not confined, MSYS2 \
275                     installations off PATH not isolated)"
276                )
277            }
278            Self::OsSandbox { enforcer } => write!(f, "OS sandbox ({enforcer}, no network)"),
279            Self::Container { image } => write!(f, "container ({image})"),
280            Self::Remote { provider, off_host: true } => write!(f, "remote sandbox ({provider})"),
281            Self::Remote { provider, off_host: false } => {
282                write!(f, "{provider} sandbox client on this host (full user permissions, network)")
283            }
284            Self::Degraded { requested, reason } => write!(
285                f,
286                "host (full user permissions, network); requested {requested} is unavailable: {reason}"
287            ),
288        }
289    }
290}
291
292/// Error code of an `auto_allow_sandboxed` the sandbox cannot honour (spec 3.1 §7.9, I26).
293///
294/// # Example
295///
296/// ```rust
297/// assert_eq!(adk_harness::AUTO_ALLOW_UNAVAILABLE_CODE, "harness.auto_allow_sandboxed_unavailable");
298/// ```
299pub const AUTO_ALLOW_UNAVAILABLE_CODE: &str = "harness.auto_allow_sandboxed_unavailable";
300
301/// The shell as `build()` resolved it (spec 3.1 §7.2 step 1).
302#[derive(Debug, Clone)]
303pub(crate) struct ShellRuntime {
304    /// The isolation `bash` runs under.
305    pub(crate) status: IsolationStatus,
306    /// The launcher of an active OS sandbox.
307    #[cfg(feature = "sandbox")]
308    pub(crate) launcher: Option<SandboxLauncher>,
309    /// Where an active container or remote shell's environments come from.
310    #[cfg(any(feature = "docker", feature = "remote-shell"))]
311    pub(crate) pooled: Option<PoolSource>,
312    /// The sandbox denies the network, keeps protected paths read-only (adk-sandbox S3, proven
313    /// by the enforcer conformance probe) and keeps every root-level protected path from being
314    /// created or replaced, so sandboxed commands may run without approval where the mode table
315    /// allows it (I26).
316    pub(crate) protects_paths: bool,
317    /// The enforcer refuses writes to root-level protected paths by name (Seatbelt), so one
318    /// that does not exist or is a symbolic link needs no re-check per call.
319    pub(crate) guards_protected_names: bool,
320    /// An active OS sandbox runs a read-only launcher's commands with the workspace read-only
321    /// and no network, so Plan mode may run them without approval (spec 3.1 §7.4). The
322    /// Windows restricted-token enforcer does neither (spec 3.2 §10 W5).
323    pub(crate) read_only_runs: bool,
324    /// `auto_allow_sandboxed` is in effect.
325    pub(crate) auto_allow_sandboxed: bool,
326}
327
328/// Resolves the shell runtime at build time (spec 3.1 §7.2 step 1, §7.9 "Availability").
329///
330/// Probes the enforcer of a requested OS sandbox, or the container runtime of a requested
331/// container shell. An unavailable one fails the build under `fail_if_unavailable` and is
332/// otherwise `Degraded`: the host shell behind approvals, with `auto_allow_sandboxed` of no
333/// effect. An active one is checked for S3 semantics; an `auto_allow_sandboxed` it cannot
334/// honour fails the build with the reason.
335pub(crate) fn resolve_isolation(
336    config: &ShellConfig,
337    root: &std::path::Path,
338) -> Result<ShellRuntime> {
339    #[cfg(not(feature = "sandbox"))]
340    let _ = root;
341    let runtime = match &config.isolation {
342        ShellIsolation::Host => ShellRuntime {
343            status: IsolationStatus::Host,
344            #[cfg(feature = "sandbox")]
345            launcher: None,
346            #[cfg(any(feature = "docker", feature = "remote-shell"))]
347            pooled: None,
348            protects_paths: false,
349            guards_protected_names: false,
350            read_only_runs: false,
351            auto_allow_sandboxed: false,
352        },
353        #[cfg(feature = "sandbox")]
354        ShellIsolation::OsSandbox(sandbox) => {
355            let launcher = SandboxLauncher::new(sandbox.clone());
356            let status = launcher.status();
357            let active = matches!(status, IsolationStatus::OsSandbox { .. });
358            let refusal = if active { auto_allow_refusal(&launcher, root) } else { None };
359            if config.auto_allow_sandboxed
360                && let Some(reason) = &refusal
361            {
362                return Err(AdkError::new(
363                    ErrorComponent::Agent,
364                    ErrorCategory::InvalidInput,
365                    AUTO_ALLOW_UNAVAILABLE_CODE,
366                    format!(
367                        "auto_allow_sandboxed cannot turn on: {reason} (spec 3.1 §9.2 I26); \
368                         drop auto_allow_sandboxed to approve sandboxed commands one by one"
369                    ),
370                ));
371            }
372            ShellRuntime {
373                protects_paths: active && refusal.is_none(),
374                guards_protected_names: active && launcher.guards_protected_names(),
375                read_only_runs: active && launcher.keeps_read_only(),
376                auto_allow_sandboxed: config.auto_allow_sandboxed && active && refusal.is_none(),
377                launcher: active.then_some(launcher),
378                #[cfg(any(feature = "docker", feature = "remote-shell"))]
379                pooled: None,
380                status,
381            }
382        }
383        #[cfg(feature = "docker")]
384        ShellIsolation::Container(container) => {
385            let status = match container::probe(container) {
386                Ok(()) => IsolationStatus::Container { image: container.image.clone() },
387                Err(reason) => {
388                    IsolationStatus::Degraded { requested: "container".to_string(), reason }
389                }
390            };
391            let active = matches!(status, IsolationStatus::Container { .. });
392            let refusal =
393                if active { container::auto_allow_refusal(container, root) } else { None };
394            if config.auto_allow_sandboxed
395                && let Some(reason) = &refusal
396            {
397                return Err(AdkError::new(
398                    ErrorComponent::Agent,
399                    ErrorCategory::InvalidInput,
400                    AUTO_ALLOW_UNAVAILABLE_CODE,
401                    format!(
402                        "auto_allow_sandboxed cannot turn on: {reason} (spec 3.1 §9.2 I26); \
403                         drop auto_allow_sandboxed to approve container commands one by one"
404                    ),
405                ));
406            }
407            ShellRuntime {
408                protects_paths: active && refusal.is_none(),
409                guards_protected_names: false,
410                read_only_runs: false,
411                auto_allow_sandboxed: config.auto_allow_sandboxed && active && refusal.is_none(),
412                #[cfg(feature = "sandbox")]
413                launcher: None,
414                pooled: active.then(|| PoolSource::Container(container.clone())),
415                status,
416            }
417        }
418        #[cfg(feature = "remote-shell")]
419        ShellIsolation::Remote(remote) => {
420            let status = IsolationStatus::Remote {
421                provider: remote.client.provider().to_string(),
422                off_host: remote.client.capabilities().remote,
423            };
424            let refusal = remote.auto_allow_refusal();
425            if config.auto_allow_sandboxed
426                && let Some(reason) = &refusal
427            {
428                return Err(AdkError::new(
429                    ErrorComponent::Agent,
430                    ErrorCategory::InvalidInput,
431                    AUTO_ALLOW_UNAVAILABLE_CODE,
432                    format!(
433                        "auto_allow_sandboxed cannot turn on: {reason} (spec 3.1 §9.2 I26); \
434                         drop auto_allow_sandboxed to approve remote commands one by one"
435                    ),
436                ));
437            }
438            ShellRuntime {
439                // A command off the host reaches none of its protected paths.
440                protects_paths: refusal.is_none(),
441                guards_protected_names: false,
442                read_only_runs: false,
443                auto_allow_sandboxed: config.auto_allow_sandboxed && refusal.is_none(),
444                #[cfg(feature = "sandbox")]
445                launcher: None,
446                pooled: Some(PoolSource::Remote(remote.clone())),
447                status,
448            }
449        }
450    };
451    if let IsolationStatus::Degraded { requested, reason } = &runtime.status {
452        if config.fail_if_unavailable {
453            return Err(sandbox_unavailable(requested, reason));
454        }
455        tracing::warn!(
456            shell.requested = %requested,
457            shell.reason = %reason,
458            "requested shell sandbox is unavailable; bash runs on the host and every command needs approval in ask mode"
459        );
460    }
461    if config.auto_allow_sandboxed && !runtime.auto_allow_sandboxed {
462        tracing::warn!(
463            shell.isolation = %runtime.status,
464            "auto_allow_sandboxed has no effect: no sandbox or container is active"
465        );
466    }
467    Ok(runtime)
468}
469
470/// Why sandboxed commands cannot run unapproved, or `None` when they can (I26).
471#[cfg(feature = "sandbox")]
472fn auto_allow_refusal(launcher: &SandboxLauncher, root: &std::path::Path) -> Option<String> {
473    if launcher.config().network {
474        return Some("the sandbox allows the network".to_string());
475    }
476    // An unapproved command could send the workspace to a host the policy admits (#1281).
477    if launcher.config().egress.is_some() {
478        return Some("the sandbox reaches the network through an egress proxy".to_string());
479    }
480    // An unapproved command must not reach the network or read outside the workspace.
481    let mut open = Vec::new();
482    if !launcher.denies_network() {
483        open.push("does not restrict the network");
484    }
485    if !launcher.confines_reads() {
486        open.push("does not confine reads to the workspace");
487    }
488    if !launcher.isolates_msys2() {
489        open.push("does not isolate the MSYS2 installations off its PATH");
490    }
491    if !open.is_empty() {
492        return Some(format!(
493            "the {} sandbox {}",
494            adk_devtools::CommandLauncher::isolation(launcher),
495            open.join(" and ")
496        ));
497    }
498    if let Err(reason) = launcher.nested_read_only_conformance() {
499        return Some(reason);
500    }
501    // The conformance script proved that a missing or symlinked root-level protected path
502    // cannot be created or replaced.
503    if launcher.guards_protected_names() {
504        return None;
505    }
506    let protected = protected_paths(root);
507    (!protected.unprotectable.is_empty()).then(|| {
508        format!(
509            "these protected paths cannot be kept read-only inside the sandbox: {}; create them \
510             (a protected path that does not exist cannot be protected from creation) or \
511             replace the symlinks",
512            protected.describe_unprotectable()
513        )
514    })
515}
516
517/// Whether every root-level protected path of `root` still exists and can be kept
518/// read-only, re-checked per call while sandboxed commands run unapproved under an enforcer
519/// that does not guard protected names (I26).
520pub(crate) fn protected_paths_hold(root: &std::path::Path) -> bool {
521    protected_paths(root).unprotectable.is_empty()
522}
523
524/// Records `harness.bash.retry_unsandboxed` for an unsandboxed retry the policy decided
525/// (spec 3.1 §9.3, `source: "policy"`); the tool records the consumption.
526pub(crate) async fn record_retry_requested(
527    audit: Option<crate::audit::HarnessAudit>,
528    ledger: &dyn ShellLedger,
529    request: &adk_core::ToolPolicyRequest,
530    call_id: Option<&str>,
531    decision: &adk_core::PolicyDecision,
532) {
533    let Some(audit) = audit else { return };
534    let retry_of = request.args.get("retry_of").and_then(serde_json::Value::as_str);
535    let failed = match retry_of {
536        Some(retry_of) => ledger
537            .get(&request.app_name, &request.user_id, &request.session_id, retry_of)
538            .await
539            .ok()
540            .flatten(),
541        None => None,
542    };
543    let decision = match decision {
544        adk_core::PolicyDecision::Allow => "allow",
545        adk_core::PolicyDecision::Deny { .. } => "deny",
546        adk_core::PolicyDecision::RequireApproval { .. } => "require_approval",
547    };
548    let record = audit
549        .record(
550            "harness.bash.retry_unsandboxed",
551            serde_json::json!({
552                "functionCallId": call_id,
553                "retryOf": retry_of,
554                "failedEnforcer": failed.as_ref().and_then(|entry| entry.enforcer.clone()),
555                "failureDigest": failed.as_ref().map(ShellLedgerEntry::digest),
556                "decision": decision,
557                "source": "policy",
558            }),
559        )
560        .await;
561    if let Err(error) = record {
562        tracing::warn!(error = %error, "could not record harness.bash.retry_unsandboxed");
563    }
564}
565
566pub(crate) fn sandbox_unavailable(requested: &str, reason: &str) -> AdkError {
567    AdkError::new(
568        ErrorComponent::Agent,
569        ErrorCategory::Unavailable,
570        SANDBOX_UNAVAILABLE_CODE,
571        format!(
572            "the requested {requested} shell is unavailable ({reason}) and fail_if_unavailable \
573             is set; install the sandbox or drop fail_if_unavailable to run on the host behind approvals"
574        ),
575    )
576}