summaryrefslogtreecommitdiffstats
path: root/src/sandbox/agent.rs
blob: 09a6f93cdd150c8fa21a17b4ce7376a830ee20d5 (plain)
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
//! The ephemeral sandbox agent: what runs *inside* the sandbox.
//!
//! One connection, one lease, one life: the agent dials the hub (outbound
//! rendezvous — the hub never needs a route into an untrusted box), accepts
//! `Run`/`Put`/`Get` frames for as long as the hub keeps the connection alive,
//! and dies — taking its child processes with it — when the connection drops
//! or its TTL expires. There is no state between leases by design: the sandbox
//! is disposable, the TTL is the guarantee, and a leaked sandbox is a bug in
//! the TTL watchdog, not a lifecycle question.
//!
//! The TTL watchdog is the backstop under every failure mode: hub crashes,
//! network partition, a hub bug that forgets `Destroy`. The hub keeps it fed
//! with `Ping` frames while a run is in flight; silence longer than the TTL
//! means nobody is coming, so the agent kills its child and exits.

use std::io::BufReader;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crossbeam_channel::unbounded;

use crate::error::{Error, Result};
use crate::sandbox::wire::{self, Frame};

/// CLI-shaped arguments for the `sandbox-agent` binary.
#[derive(Debug, Clone)]
pub struct AgentOptions {
    pub hub: String,
    pub token: String,
    pub profile: String,
    pub ttl: Duration,
    /// The identity the hub knows this sandbox by. A provisioner (Kata CR,
    /// containerd run, a test) passes the nonce it registered with the hub;
    /// the hello frame carries it back so the rendezvous can be matched.
    pub agent_id: Option<String>,
}

pub fn serve(opts: &AgentOptions) -> Result<()> {
    let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?;
    let agent_id = opts
        .agent_id
        .clone()
        .unwrap_or_else(|| format!("sandbox-{}", std::process::id()));
    wire::write_frame(
        &mut stream.try_clone()?,
        &Frame::Hello {
            token: opts.token.clone(),
            agent_id: agent_id.clone(),
            profiles: vec![opts.profile.clone()],
        },
    )?;

    let mut reader = BufReader::new(stream.try_clone()?);
    let writer = Arc::new(Mutex::new(stream));
    let ttl = match wire::read_frame(&mut reader)? {
        Some(Frame::HelloAck { ttl_secs }) => Duration::from_secs(ttl_secs.max(1)),
        Some(other) => return Err(Error::invalid(format!("agent: expected hello_ack, got {other:?}"))),
        None => return Err(Error::other("agent: hub closed the connection at rendezvous")),
    };

    let blobs = blob_dir(&agent_id);
    std::fs::create_dir_all(&blobs)?;

    // Shared watchdog state: the reader thread stamps every inbound frame;
    // the watchdog exits (killing the child) when the hub goes silent.
    let last_inbound = Arc::new(Mutex::new(Instant::now()));
    let child = Arc::new(Mutex::new(None::<u32>));
    let alive = Arc::new(AtomicBool::new(true));
    {
        let (last, child, alive, ttl) =
            (last_inbound.clone(), child.clone(), alive.clone(), ttl);
        std::thread::spawn(move || loop {
            std::thread::sleep(Duration::from_millis(1000));
            let quiet = last.lock().unwrap().elapsed();
            if quiet > ttl {
                eprintln!("agent: hub silent for {quiet:?} past the TTL; dying");
                if let Some(pid) = *child.lock().unwrap() {
                    unsafe {
                        libc::kill(pid as i32, libc::SIGKILL);
                    }
                }
                std::process::exit(1);
            }
            if !alive.load(Ordering::Relaxed) {
                return;
            }
        });
    }

    let mut outcome = Ok(());
    loop {
        let frame = match wire::read_frame(&mut reader) {
            Ok(Some(f)) => f,
            Ok(None) => break, // hub hung up: the lease is over
            Err(e) => {
                outcome = Err(e.into());
                break;
            }
        };
        *last_inbound.lock().unwrap() = Instant::now();
        let stop = match handle(frame, &writer, &blobs, &child) {
            Ok(stop) => stop,
            Err(e) => {
                outcome = Err(e);
                break;
            }
        };
        if stop {
            break;
        }
    }
    alive.store(false, Ordering::Relaxed);
    // Whatever we were running dies with us, always.
    if let Some(pid) = *child.lock().unwrap() {
        unsafe {
            libc::kill(pid as i32, libc::SIGKILL);
        }
    }
    let _ = std::fs::remove_dir_all(&blobs);
    outcome
}

/// Returns true when the agent should stop (Destroy / fatal child loss).
fn handle(
    frame: Frame,
    writer: &Arc<Mutex<TcpStream>>,
    blobs: &Path,
    child: &Arc<Mutex<Option<u32>>>,
) -> Result<bool> {
    match frame {
        Frame::Destroy {} => Ok(true),
        Frame::Ping {} => Ok(false),
        Frame::Put { req, digest, data } => {
            let bytes = wire::unhex(&data).map_err(io_err)?;
            // The agent verifies content-addressing on its side too: a blob
            // that does not hash to its name is refused, not staged.
            if crate::hash::hex(&bytes) != digest {
                reply(writer, req, Err("put: data does not hash to the claimed digest"))?;
                return Ok(false);
            }
            std::fs::write(safe_blob_path(blobs, &digest)?, &bytes)?;
            reply(writer, req, Ok(()))?;
            Ok(false)
        }
        Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) {
            Ok(bytes) => {
                wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?;
                Ok(false)
            }
            Err(_) => {
                reply(writer, req, Err("get: no such blob"))?;
                Ok(false)
            }
        },
        Frame::Run { req, argv, cwd, env } => {
            run_child(req, argv, cwd, env, writer, blobs, child)?;
            Ok(false)
        }
        other => Err(Error::invalid(format!("agent: unexpected frame {other:?}"))),
    }
}

fn run_child(
    req: u64,
    argv: Vec<String>,
    cwd: Option<String>,
    env: Vec<(String, String)>,
    writer: &Arc<Mutex<TcpStream>>,
    blobs: &Path,
    child: &Arc<Mutex<Option<u32>>>,
) -> Result<()> {
    let mut argv = argv;
    // Expand `blob:<digest>` argv elements, like the loopback backend does.
    for a in argv.iter_mut() {
        if let Some(digest) = a.strip_prefix("blob:") {
            *a = safe_blob_path(blobs, digest)?.display().to_string();
        }
    }
    let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?;
    let mut c = std::process::Command::new(program);
    c.args(&argv[1..])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if let Some(dir) = cwd {
        c.current_dir(dir);
    }
    for (k, v) in env {
        c.env(k, v);
    }
    let mut proc = c.spawn()?;
    *child.lock().unwrap() = Some(proc.id());

    // Stream both pipes as they fill: readers hand chunks to the frame writer
    // over a channel, so a chatty build never blocks on the socket and vice
    // versa.
    let (tx, rx) = unbounded::<(&'static str, Vec<u8>)>();
    let mut pipes = Vec::new();
    let pipes_spec: [(&'static str, Option<Box<dyn std::io::Read + Send>>); 2] = [
        ("stdout", proc.stdout.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)),
        ("stderr", proc.stderr.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)),
    ];
    for (name, pipe) in pipes_spec {
        if let Some(mut pipe) = pipe {
            let tx = tx.clone();
            pipes.push(std::thread::spawn(move || {
                use std::io::Read;
                let mut buf = [0u8; 8192];
                loop {
                    match pipe.read(&mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            if tx.send((name, buf[..n].to_vec())).is_err() {
                                break;
                            }
                        }
                    }
                }
            }));
        }
    }
    drop(tx);
    while let Ok((stream, bytes)) = rx.recv() {
        wire::write_frame(
            writer.lock().unwrap().deref_mut(),
            &Frame::Log { req, stream: stream.to_string(), data: wire::hex_bytes(&bytes) },
        )?;
    }
    for p in pipes {
        let _ = p.join();
    }
    let status = proc.wait()?;
    *child.lock().unwrap() = None;
    wire::write_frame(
        writer.lock().unwrap().deref_mut(),
        &Frame::Exit { req, code: status.code() },
    )?;
    Ok(())
}

fn reply(writer: &Arc<Mutex<TcpStream>>, req: u64, result: std::result::Result<(), &str>) -> Result<()> {
    let frame = match result {
        Ok(()) => Frame::Ok { req },
        Err(msg) => Frame::Err { req, msg: msg.to_string() },
    };
    wire::write_frame(writer.lock().unwrap().deref_mut(), &frame)?;
    Ok(())
}

fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result<TcpStream, Error> {
    let deadline = Instant::now() + for_long;
    loop {
        match TcpStream::connect(hub) {
            Ok(s) => return Ok(s),
            Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
            Err(e) => return Err(Error::other(format!("agent: cannot reach hub {hub}: {e}"))),
        }
    }
}

/// Blob scratch, removed when the lease ends.
fn blob_dir(agent_id: &str) -> PathBuf {
    std::env::temp_dir().join(format!("aur-{agent_id}-blobs"))
}

/// Digests are the only blob names, and they must stay path-safe — the same
/// rule the loopback backend enforces, so a hostile frame cannot escape the
/// blob directory.
fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> {
    if digest.is_empty()
        || digest.len() > 128
        || !digest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(Error::fail_closed(format!("blob digest {digest:?} is not usable")));
    }
    Ok(blobs.join(digest))
}

fn io_err(e: std::io::Error) -> Error {
    Error::other(e.to_string())
}

use std::ops::DerefMut;