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
|
//! The sandbox seam: where build code actually runs (§8, remote-builder design).
//!
//! The pipeline executes untrusted recipe code, and the security boundary around
//! it has so far been "a chroot on this machine, with sudo rules" (§14). That
//! boundary is a *deployment* fact, not a pipeline fact: the step machine should
//! not know whether it is talking to a local process, a Kata container on a
//! cluster, or a loopback harness. So every subprocess the pipeline runs goes
//! through this interface instead of spawning one itself.
//!
//! Two implementations exist:
//!
//! * [`loopback::LoopbackBackend`] — today's behavior: commands run as local
//! subprocesses of the hub process, with the §16a shim protocol applied
//! through [`Config::child_env`]. This is what `cargo test` and a single
//! machine with devtools use.
//! * (planned) a Kata/agent-sandbox backend that leases disposable, TTL-bounded
//! sandboxes and speaks the wire protocol; the pipeline cannot tell the
//! difference, which is the entire point of the seam.
//!
//! The unit of isolation is a *sandbox lease*: [`SandboxBackend::acquire`]
//! hands out a handle, steps run commands on it, and the handle is destroyable
//! at any time. Nothing may assume a sandbox outlives its TTL, and nothing may
//! assume two tasks share one. Blob transfer is content-addressed by design:
//! there is no "path on the sandbox" concept in the interface at all, which
//! removes a class of hostile-write bugs that a path-based API would invite.
use std::collections::HashMap;
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use crossbeam_channel::{Receiver, Sender};
use crate::config::Config;
use crate::error::Result;
pub mod agent;
pub mod kata;
pub mod loopback;
pub mod remote;
pub mod wire;
/// A command to run inside a sandbox. Deliberately argv-shaped, not
/// `Command`-shaped: a remote sandbox must never be handed a shell string, and
/// the environment is the backend's business (see `Config::child_env`), not the
/// caller's.
///
/// An argv element of the form `blob:<digest>` names a content-addressed blob
/// staged with [`Sandbox::put`]: the backend expands it to wherever that blob
/// materializes inside the sandbox. Callers never name sandbox-local paths —
/// that is what keeps a loopback step byte-identical to a remote one.
#[derive(Debug, Clone)]
pub struct Cmd {
pub argv: Vec<String>,
pub cwd: Option<PathBuf>,
}
impl Cmd {
pub fn new<I, S>(argv: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self { argv: argv.into_iter().map(Into::into).collect(), cwd: None }
}
pub fn in_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.cwd = Some(dir.into());
self
}
/// The program name, for error messages.
pub fn name(&self) -> &str {
self.argv.first().map(String::as_str).unwrap_or("")
}
}
/// A finished command: exit status plus captured output. `code` is `None` when
/// the child died by signal — `success()` is false either way, matching what
/// `ExitStatus::success` would have said before the seam existed.
#[derive(Debug)]
pub struct Exit {
pub code: Option<i32>,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
impl Exit {
pub fn success(&self) -> bool {
self.code == Some(0)
}
}
/// What a caller asks the pool for. `profile` is the only affinity key warm
/// pools need today (one warm root per build profile, §8.3); `task` is for
/// attribution and rendezvous, `ttl` is the guarantee that the sandbox is dead
/// no matter what this process then does, and `disk_mb` is the admission hint
/// that replaces the hub's local disk-headroom check (§8.2) once builds leave
/// the hub's filesystem.
#[derive(Debug, Clone)]
pub struct SandboxSpec {
pub profile: String,
pub task: String,
pub ttl: Duration,
pub disk_mb: u64,
}
impl SandboxSpec {
pub fn new(profile: impl Into<String>, task: impl Into<String>, ttl: Duration) -> Self {
Self { profile: profile.into(), task: task.into(), ttl, disk_mb: 0 }
}
}
/// Pool state for the UI and notices: who is warm, who is busy, what profile.
#[derive(Debug, Clone)]
pub struct SandboxInfo {
pub id: String,
pub profile: String,
pub warm: bool,
}
/// A leased sandbox. `run` streams output through `on_log` as it arrives and
/// also returns it captured, so a step can parse stdout while the build log
/// stays complete. `put`/`get` move content-addressed blobs in and out — the
/// hub pulls artifacts by digest and never accepts a destination path from a
/// sandbox, which is the same I9 posture the local staging-containment checks
/// already enforce.
pub trait Sandbox: Send + Sync {
fn id(&self) -> &str;
fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>;
fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>;
fn get(&self, digest: &str) -> Result<Box<dyn Read>>;
/// Idempotent, and also happens by itself when the TTL bites. Destroying a
/// sandbox must never be the only thing standing between untrusted code and
/// the world.
fn destroy(&self) -> Result<()>;
}
/// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail
/// when at quota; callers treat a failed acquire like a blocked build, not a
/// broken one.
pub trait SandboxBackend: Send + Sync {
fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>;
fn status(&self) -> Result<Vec<SandboxInfo>>;
}
/// Turn a configuration into the backend it names — the only place that does,
/// so "which backend" has exactly one answer.
///
/// `Config::validate` runs here as well as at startup: a guard that only exists
/// in the CLI is a guard a test, a tool, or a future daemon can walk past.
/// And an unknown or unwired kind is an error, never a fallthrough — a build
/// configured for a Kata VM that quietly ran as the hub's own user is the
/// failure this function used to have.
pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> {
cfg.validate()?;
match &cfg.sandbox {
crate::config::Sandbox::Loopback => Ok(Arc::new(loopback::LoopbackBackend::new(cfg))),
crate::config::Sandbox::Remote { listen, token, .. } => {
Ok(Arc::new(remote::RemoteBackend::bind(cfg, listen, token)?))
}
crate::config::Sandbox::AgentSandbox { .. } => {
let backend: Arc<dyn SandboxBackend> = kata::KataBackend::shared_for(cfg)?;
Ok(backend)
}
}
}
/// A listener shared by every backend built from the same `(addr, token)`.
#[derive(Clone)]
pub(crate) struct Bound {
pub local: String,
pub rx: Receiver<TcpStream>,
}
/// One bound listener per `(address, token)` per process.
///
/// The listener is a property of the *process*, not of a build. Binding it per
/// build — which is what happened while `Ctx::new` constructed a backend for
/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed
/// `listen` and failed for a reason that had nothing to do with its package.
/// Sharing the queue is also exactly the semantics the agent protocol has: an
/// agent dials in when it is booted, and whichever build is waiting takes it.
///
/// The token is part of the key on purpose. Two different tokens cannot share a
/// listener, and reusing the first one's listener for a second, different token
/// would be a fail-open surprise; forcing a real bind makes the mistake loud.
pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new();
let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
let key = (addr.to_string(), token.to_string());
// A poisoned registry means a panic in some other thread's bind; the map
// itself is still sound, so recover rather than wedge every later build —
// the same posture as the publish lock.
let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner());
if let Some(b) = reg.get(&key) {
return Ok(b.clone());
}
let listener = TcpListener::bind(addr)?;
let local = listener.local_addr()?.to_string();
let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = crossbeam_channel::unbounded();
std::thread::spawn(move || {
for stream in listener.incoming() {
match stream {
Ok(s) => {
let _ = tx.send(s);
}
Err(_) => break,
}
}
});
let bound = Bound { local, rx };
reg.insert(key, bound.clone());
Ok(bound)
}
|