aither-sandbox 0.8.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use std::future::Future;
use std::path::{Path, PathBuf};
use std::process::{Output, Stdio};
use std::time::Duration;

use askama::Template;
use futures_lite::io::AsyncWriteExt;

use crate::shell_session::{ContainerShellRuntime, SshServer};
use crate::tool_runtime::{PreparedTools, ToolBundle, ToolRuntimeError, ToolTarget};

/// Trusted initialization transport, separate from agent command execution.
pub trait ToolTransport: Send + Sync {
    /// Runs an initialization script and optionally streams a verified tool archive.
    fn run(
        &self,
        script: &str,
        input: Option<Vec<u8>>,
    ) -> impl Future<Output = Result<Output, ToolRuntimeError>> + Send;
}

/// Tool initialization over an already authorized SSH destination.
#[derive(Debug, Clone)]
pub struct SshToolTransport {
    server: SshServer,
}

impl SshToolTransport {
    /// Binds provisioning to the configured SSH server, not a model-provided target.
    #[must_use]
    pub const fn new(server: SshServer) -> Self {
        Self { server }
    }
}

impl ToolTransport for SshToolTransport {
    async fn run(&self, script: &str, input: Option<Vec<u8>>) -> Result<Output, ToolRuntimeError> {
        let mut command = async_process::Command::new("ssh");
        command
            .args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--"])
            .arg(&self.server.target)
            .arg(shell_words::join(["sh", "-c", script]));
        run_command(command, input).await
    }
}

/// Tool initialization using the configured container executor.
#[derive(Debug, Clone)]
pub struct ContainerToolTransport {
    runtime: ContainerShellRuntime,
}

impl ContainerToolTransport {
    /// Binds initialization to an existing container runtime.
    #[must_use]
    pub const fn new(runtime: ContainerShellRuntime) -> Self {
        Self { runtime }
    }
}

impl ToolTransport for ContainerToolTransport {
    async fn run(&self, script: &str, input: Option<Vec<u8>>) -> Result<Output, ToolRuntimeError> {
        let exec = self.runtime.exec();
        let (kill_tx, kill_rx) = async_channel::bounded(1);
        let (input_tx, input_rx) = async_channel::unbounded();
        if let Some(input) = input {
            input_tx
                .try_send(input)
                .map_err(|_| ToolRuntimeError::InitializationInterrupted)?;
        }
        drop(input_tx);
        let execution = exec.exec_boxed(
            self.runtime.container_id(),
            script,
            "/",
            kill_rx,
            input_rx,
            None,
        );
        let result = futures_lite::future::or(
            async { execution.await.map_err(ToolRuntimeError::Container) },
            async {
                async_io::Timer::after(Duration::from_secs(120)).await;
                let _ = kill_tx.try_send(());
                Err(ToolRuntimeError::InitializationTimeout)
            },
        )
        .await?;
        match result {
            crate::ContainerExecOutcome::Completed(output) => Ok(output),
            crate::ContainerExecOutcome::Killed => Err(ToolRuntimeError::InitializationInterrupted),
        }
    }
}

async fn run_command(
    mut command: async_process::Command,
    input: Option<Vec<u8>>,
) -> Result<Output, ToolRuntimeError> {
    command
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let mut child = command.spawn()?;
    let mut stdin = child
        .stdin
        .take()
        .ok_or(ToolRuntimeError::InitializationInterrupted)?;
    futures_lite::future::or(
        async {
            let send = async {
                if let Some(bytes) = input {
                    stdin.write_all(&bytes).await?;
                }
                drop(stdin);
                Ok::<(), ToolRuntimeError>(())
            };
            let (transferred, output) = futures_lite::future::zip(send, child.output()).await;
            transferred?;
            Ok(output?)
        },
        async {
            async_io::Timer::after(Duration::from_secs(120)).await;
            Err(ToolRuntimeError::InitializationTimeout)
        },
    )
    .await
}

/// Platform information from the target execution environment.
#[derive(Debug, Clone)]
pub struct ToolEnvironmentInfo {
    /// Target platform, not the coordinator's platform.
    pub target: ToolTarget,
    /// Target-owned cache directory outside agent workspaces.
    pub cache_root: PathBuf,
}

/// Probes a trusted backend during initialization, never during model commands.
///
/// # Errors
/// Rejects probe failure, malformed output or unsupported target platforms.
pub async fn probe_tool_environment(
    transport: &impl ToolTransport,
) -> Result<ToolEnvironmentInfo, ToolRuntimeError> {
    let output = transport
        .run(include_str!("../templates/tool_probe.sh"), None)
        .await?;
    let output = successful_output(output)?;
    let mut lines = output.lines();
    let os = lines.next().ok_or(ToolRuntimeError::InvalidProbe)?;
    let arch = lines.next().ok_or(ToolRuntimeError::InvalidProbe)?;
    let home = lines.next().ok_or(ToolRuntimeError::InvalidProbe)?;
    if lines.next().is_some() || !home.starts_with('/') {
        return Err(ToolRuntimeError::InvalidProbe);
    }
    let target = ToolTarget::from_probe(os, arch)?;
    Ok(ToolEnvironmentInfo {
        target,
        cache_root: Path::new(home).join(".cache/aither/tools"),
    })
}

#[derive(Debug)]
struct InstallTool {
    command: String,
    sha256: String,
}

#[derive(Template)]
#[template(path = "tool_install.sh", escape = "none")]
struct ToolInstallTemplate<'a> {
    root: std::borrow::Cow<'a, str>,
    cache_key: String,
    tools: Vec<InstallTool>,
    macos: bool,
    probe_only: bool,
}

#[derive(Template)]
#[template(path = "tool_verify.sh", escape = "none")]
struct ToolVerifyTemplate<'a> {
    directory: std::borrow::Cow<'a, str>,
    tools: Vec<InstallTool>,
}

impl ToolBundle {
    pub(crate) async fn verify_container_mount(
        &self,
        transport: &impl ToolTransport,
    ) -> Result<PreparedTools, ToolRuntimeError> {
        use procfs_core::FromRead;
        let directory = self.container_directory()?;
        let output = successful_output(transport.run("cat /proc/self/mountinfo", None).await?)?;
        let mounts = procfs_core::process::MountInfos::from_read(output.as_bytes())?;
        if !mounts
            .iter()
            .any(|mount| mount.mount_point == directory && mount.mount_options.contains_key("ro"))
            || mounts.iter().any(|mount| {
                mount.mount_point.starts_with(&directory) && !mount.mount_options.contains_key("ro")
            })
        {
            return Err(ToolRuntimeError::MissingReadonlyMount(directory));
        }
        let script = ToolVerifyTemplate {
            directory: shell_words::quote(
                directory.to_str().ok_or(ToolRuntimeError::InvalidProbe)?,
            ),
            tools: self
                .binaries
                .iter()
                .map(|binary| InstallTool {
                    command: binary.tool.command().into(),
                    sha256: hex::encode(binary.sha256),
                })
                .collect(),
        }
        .render()?;
        let output = successful_output(transport.run(&script, None).await?)?;
        let catalog = self.catalog();
        catalog.verify_versions(&output)?;
        Ok(PreparedTools {
            bin_dir: directory.join("bin"),
            catalog,
        })
    }

    /// Installs verified artifacts through a backend's independent initialization transport.
    ///
    /// # Errors
    /// Rejects failed transfers, a tampered cache or invalid activation output.
    pub async fn prepare_remote<F, Fut>(
        &self,
        transport: &impl ToolTransport,
        root: &Path,
        authorize: F,
    ) -> Result<PreparedTools, ToolRuntimeError>
    where
        F: FnOnce() -> Fut + Send,
        Fut: Future<Output = Result<(), ToolRuntimeError>> + Send,
    {
        let root_text = root.to_str().ok_or(ToolRuntimeError::InvalidProbe)?;
        let mut template = ToolInstallTemplate {
            root: shell_words::quote(root_text),
            cache_key: self.cache_key()?,
            tools: self
                .binaries
                .iter()
                .map(|binary| InstallTool {
                    command: binary.tool.command().into(),
                    sha256: hex::encode(binary.sha256),
                })
                .collect(),
            macos: self.target().os() == "macos",
            probe_only: true,
        };
        let probe = transport.run(&template.render()?, None).await?;
        let output = if probe.status.code() == Some(3) {
            authorize().await?;
            template.probe_only = false;
            let bundle = self.clone();
            let archive = blocking::unblock(move || bundle.archive()).await?;
            transport.run(&template.render()?, Some(archive)).await?
        } else {
            probe
        };
        let path = successful_output(output)?;
        let mut lines = path.lines();
        let bin_dir = lines.next().ok_or(ToolRuntimeError::InvalidProbe)?;
        if lines.next().is_some() || !bin_dir.starts_with('/') {
            return Err(ToolRuntimeError::InvalidProbe);
        }
        Ok(PreparedTools {
            bin_dir: bin_dir.into(),
            catalog: self.catalog(),
        })
    }

    fn archive(&self) -> Result<Vec<u8>, ToolRuntimeError> {
        let mut archive = tar::Builder::new(Vec::new());
        for binary in self.binaries.iter() {
            let mut header = tar::Header::new_gnu();
            header.set_size(binary.bytes.len() as u64);
            header.set_mode(0o555);
            header.set_cksum();
            archive.append_data(
                &mut header,
                Path::new("bin").join(binary.tool.command()),
                binary.bytes.as_ref(),
            )?;
        }
        Ok(archive.into_inner()?)
    }
}

fn successful_output(output: Output) -> Result<String, ToolRuntimeError> {
    if !output.status.success() {
        return Err(ToolRuntimeError::InitializationCommand {
            status: output.status.code(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        });
    }
    Ok(String::from_utf8(output.stdout)?)
}

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

    #[derive(Template)]
    #[template(path = "test_tool_mountinfo.txt", escape = "none")]
    struct MountInfoTemplate<'a> {
        directory: &'a str,
        options: &'a str,
        nested: bool,
        nested_options: &'a str,
    }

    struct MountTransport {
        mountinfo: String,
    }

    impl ToolTransport for MountTransport {
        fn run(
            &self,
            script: &str,
            input: Option<Vec<u8>>,
        ) -> impl Future<Output = Result<Output, ToolRuntimeError>> + Send {
            use std::os::unix::process::ExitStatusExt;
            assert!(input.is_none());
            let stdout = if script == "cat /proc/self/mountinfo" {
                self.mountinfo.as_bytes().to_vec()
            } else {
                assert!(script.contains("heel run --network deny"));
                let mut versions = Vec::new();
                for tool in crate::ManagedTool::ALL {
                    versions.extend_from_slice(tool.command().as_bytes());
                    versions.extend_from_slice(b" 1.0.0\0");
                }
                versions
            };
            std::future::ready(Ok(Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout,
                stderr: Vec::new(),
            }))
        }
    }

    #[tokio::test]
    async fn container_tools_require_readonly_mount_and_no_writable_descendants() {
        let bundle = crate::tool_runtime::tests::bundle();
        let directory = bundle.container_directory().unwrap();
        for (options, nested, nested_options, accepted) in [
            ("ro", false, "rw", true),
            ("ro", true, "ro", true),
            ("rw", false, "rw", false),
            ("ro", true, "rw", false),
        ] {
            let transport = MountTransport {
                mountinfo: MountInfoTemplate {
                    directory: directory.to_str().unwrap(),
                    options,
                    nested,
                    nested_options,
                }
                .render()
                .unwrap(),
            };
            let result = bundle.verify_container_mount(&transport).await;
            if accepted {
                assert_eq!(result.unwrap().bin_dir(), &directory.join("bin"));
            } else {
                assert!(matches!(
                    result,
                    Err(ToolRuntimeError::MissingReadonlyMount(_))
                ));
            }
        }
        let missing = MountTransport {
            mountinfo: String::new(),
        };
        assert!(matches!(
            bundle.verify_container_mount(&missing).await,
            Err(ToolRuntimeError::MissingReadonlyMount(_))
        ));
    }

    struct LocalTransport;
    impl ToolTransport for LocalTransport {
        async fn run(
            &self,
            script: &str,
            input: Option<Vec<u8>>,
        ) -> Result<Output, ToolRuntimeError> {
            let mut command = async_process::Command::new("sh");
            command.args(["-c", script]);
            run_command(command, input).await
        }
    }

    #[tokio::test]
    async fn initialization_script_installs_and_warm_cache_skips_transfer() {
        let root = tempfile::tempdir().unwrap();
        let bundle = crate::tool_runtime::tests::bundle();
        let first = bundle
            .prepare_remote(&LocalTransport, root.path(), || async { Ok(()) })
            .await
            .unwrap();
        let second = bundle
            .prepare_remote(&LocalTransport, root.path(), || async {
                Err(ToolRuntimeError::InstallDenied(
                    "warm cache must not ask".into(),
                ))
            })
            .await
            .unwrap();
        assert_eq!(first.bin_dir(), second.bin_dir());
        for tool in crate::ManagedTool::ALL {
            assert!(first.bin_dir().join(tool.command()).is_file());
        }
    }

    #[tokio::test]
    async fn denied_remote_install_never_activates_tools() {
        let root = tempfile::tempdir().unwrap();
        let bundle = crate::tool_runtime::tests::bundle();
        let result = bundle
            .prepare_remote(&LocalTransport, root.path(), || async {
                Err(ToolRuntimeError::InstallDenied("test server".into()))
            })
            .await;
        assert!(matches!(result, Err(ToolRuntimeError::InstallDenied(_))));
        let activation = root.path().join(bundle.cache_key().unwrap());
        assert_eq!(
            async_fs::symlink_metadata(activation)
                .await
                .unwrap_err()
                .kind(),
            std::io::ErrorKind::NotFound
        );
    }

    #[tokio::test]
    async fn concurrent_remote_activation_is_atomic() {
        let root = tempfile::tempdir().unwrap();
        let bundle = crate::tool_runtime::tests::bundle();
        let (first, second) = futures_lite::future::zip(
            bundle.prepare_remote(&LocalTransport, root.path(), || async { Ok(()) }),
            bundle.prepare_remote(&LocalTransport, root.path(), || async { Ok(()) }),
        )
        .await;
        assert_eq!(first.unwrap().bin_dir(), second.unwrap().bin_dir());
    }
}