1mod 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
53pub const SANDBOX_UNAVAILABLE_CODE: &str = "harness.sandbox_unavailable";
61
62#[derive(Clone, Debug, Default)]
72#[non_exhaustive]
73pub enum ShellIsolation {
74 #[default]
76 Host,
77 #[cfg(feature = "sandbox")]
79 OsSandbox(OsSandboxConfig),
80 #[cfg(feature = "docker")]
82 Container(ContainerConfig),
83 #[cfg(feature = "remote-shell")]
86 Remote(RemoteShellConfig),
87}
88
89impl ShellIsolation {
90 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#[derive(Clone, Debug)]
117pub struct ShellConfig {
118 pub isolation: ShellIsolation,
120 pub fail_if_unavailable: bool,
122 pub auto_allow_sandboxed: bool,
128 pub allow_unsandboxed_retry: bool,
131 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(tag = "kind", rename_all = "camelCase")]
160#[non_exhaustive]
161pub enum IsolationStatus {
162 Host,
164 OsSandbox {
166 enforcer: String,
168 },
169 Container {
171 image: String,
173 },
174 Remote {
177 provider: String,
179 #[serde(rename = "offHost")]
181 off_host: bool,
182 },
183 Degraded {
185 requested: String,
187 reason: String,
189 },
190}
191
192impl IsolationStatus {
193 pub fn behaves_as_host(&self) -> bool {
195 matches!(self, Self::Host | Self::Degraded { .. } | Self::Remote { off_host: false, .. })
196 }
197
198 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 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 pub fn isolates_msys2(&self) -> bool {
246 self.confines_reads()
247 }
248
249 pub fn isolation(&self) -> Isolation {
251 match self {
252 Self::Host | Self::Degraded { .. } => Isolation::Host,
253 Self::OsSandbox { .. } => Isolation::OsSandbox,
254 Self::Container { .. } | Self::Remote { off_host: true, .. } => Isolation::Container,
257 Self::Remote { off_host: false, .. } => Isolation::Host,
258 }
259 }
260}
261
262const 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
292pub const AUTO_ALLOW_UNAVAILABLE_CODE: &str = "harness.auto_allow_sandboxed_unavailable";
300
301#[derive(Debug, Clone)]
303pub(crate) struct ShellRuntime {
304 pub(crate) status: IsolationStatus,
306 #[cfg(feature = "sandbox")]
308 pub(crate) launcher: Option<SandboxLauncher>,
309 #[cfg(any(feature = "docker", feature = "remote-shell"))]
311 pub(crate) pooled: Option<PoolSource>,
312 pub(crate) protects_paths: bool,
317 pub(crate) guards_protected_names: bool,
320 pub(crate) read_only_runs: bool,
324 pub(crate) auto_allow_sandboxed: bool,
326}
327
328pub(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 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#[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 if launcher.config().egress.is_some() {
478 return Some("the sandbox reaches the network through an egress proxy".to_string());
479 }
480 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 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
517pub(crate) fn protected_paths_hold(root: &std::path::Path) -> bool {
521 protected_paths(root).unprotectable.is_empty()
522}
523
524pub(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}