summaryrefslogtreecommitdiffstats
path: root/src/sandbox
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-19 15:45:38 +0000
committeraur-build <aur-build@localhost>2026-11-19 15:45:38 +0000
commit8dcdce879b51b19603d8163d8a9bfb5f61ff1558 (patch)
tree57ba7dee86414eaf24de114a1df8209149e7b5bd /src/sandbox
parentec80c312b80ba51271fff0548c6d1e293d373455 (diff)
downloadaur-build-8dcdce879b51b19603d8163d8a9bfb5f61ff1558.tar.gz
aur-build-8dcdce879b51b19603d8163d8a9bfb5f61ff1558.zip
sandbox: agent-sandbox is a backend now, and nerdctl is gone
`sandbox_backend` was a string and `backend_for` matched it with `_ => loopback`, so the documented Kata backend was unreachable from configuration: a hub told to use agent-sandbox would have quietly built untrusted PKGBUILDs as its own user. The kind now parses, validates, and produces a real `KataBackend` over `K8sSandboxProvisioner`, with the CR's `runtimeClass`, `activeDeadlineSeconds`, nonce, image and cluster coordinates all traced back to the config that produced them. Kata shares a *backend* per configuration rather than only a listener: it routes each dial-in by the nonce in its `Hello` into a map that belongs to it, so two backends on one address would each see half the dial-ins and neither could complete a rendezvous. The cache key is a digest of the distinguishing fields so the token and bearer are not copied into a second place. The containerd/`nerdctl` payload builder is deleted rather than left unused. It was a second deployment shape with no provisioner, no config path and no live tier — a builder that advertises a route the configuration refuses is worse than no builder, because someone will eventually assume the route exists. DESIGN.md now names one provisioning shape, which is the one that exists.
Diffstat (limited to 'src/sandbox')
-rw-r--r--src/sandbox/kata.rs125
-rw-r--r--src/sandbox/mod.rs66
-rw-r--r--src/sandbox/remote.rs64
3 files changed, 139 insertions, 116 deletions
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
index 5c92557..c7d717f 100644
--- a/src/sandbox/kata.rs
+++ b/src/sandbox/kata.rs
@@ -9,13 +9,11 @@
//! the wrong build, and a sandbox that never dials in is a TTL expiry — the
//! same vocabulary every other failure in this system speaks (I5).
//!
-//! Two payload shapes are constructed here because both are real deployment
-//! targets: an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`,
-//! `activeDeadlineSeconds` as the TTL the orchestrator enforces) and a
-//! direct containerd/`nerdctl` argv for hosts without a cluster. Both are
-//! pure functions, unit-tested; the network calls that would send them are
-//! exercised only by the gated live tier, which skips — with a printed note,
-//! never a silent pass — wherever `/dev/kvm` or a cluster is absent.
+//! The payload is an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`,
+//! `activeDeadlineSeconds` as the TTL the orchestrator enforces). It is a pure
+//! function, unit-tested; the network call that sends it is exercised only by
+//! the gated live tier, which skips — with a printed note, never a silent
+//! pass — wherever a cluster is absent.
//!
//! The `LocalAgentProvisioner` is the shape this tier is tested with: a real
//! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the
@@ -28,7 +26,7 @@ use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command};
use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use crossbeam_channel::{bounded, Receiver, Sender};
@@ -100,32 +98,20 @@ pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
})
}
-/// The no-cluster shape: `nerdctl run` against containerd's kata runtime.
-/// `--rm` is the TTL's poor cousin; the agent's own watchdog is the floor.
-pub fn nerdctl_argv(req: &ProvisionRequest) -> Vec<String> {
- vec![
- "nerdctl".into(),
- "run".into(),
- "-d".into(),
- "--rm".into(),
- "--name".into(),
- req.sandbox_id.clone(),
- "--runtime".into(),
- "io.containerd.kata.v2".into(),
- "--label".into(),
- format!("aur-build.io/profile={}", req.profile),
- req.image.clone(),
- "--hub".into(),
- req.hub_addr.clone(),
- "--token".into(),
- req.token.clone(),
- "--agent-id".into(),
- req.sandbox_id.clone(),
- "--profile".into(),
- req.profile.clone(),
- "--ttl".into(),
- req.ttl.as_secs().to_string(),
- ]
+impl K8sSandboxProvisioner {
+ /// The provisioner an `agent-sandbox` configuration names. Split out so a
+ /// test can assert the cluster coordinates reach it from a parsed config,
+ /// and so `shared_for` and any later caller build it the same way.
+ pub fn for_config(cfg: &Config) -> Option<Self> {
+ match &cfg.sandbox {
+ crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self {
+ api: api.clone(),
+ namespace: namespace.clone(),
+ bearer: bearer.clone(),
+ }),
+ _ => None,
+ }
+ }
}
/// Talks to a Kubernetes API serving an agent-sandbox-style CRD. Real code,
@@ -228,6 +214,59 @@ pub struct KataBackend {
}
impl KataBackend {
+ /// The one Kata backend this process should use for this configuration.
+ ///
+ /// A Kata backend cannot share only its listener the way the plain remote
+ /// backend does: it routes every dial-in by the nonce in its `Hello` into a
+ /// map that belongs to it, so two backends on one address would each see
+ /// half the dial-ins and neither could complete a rendezvous. So the whole
+ /// backend is shared, not just the socket — which is also what makes
+ /// "one listener per process" true here, since binding happens exactly once
+ /// per distinct configuration.
+ ///
+ /// The key is a digest of everything that distinguishes one backend from
+ /// another, so the rendezvous token and the cluster bearer are not sitting
+ /// around in a second place, and two configurations that differ only in
+ /// unrelated hub settings still get their own backend.
+ pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> {
+ let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } =
+ &cfg.sandbox
+ else {
+ return Err(Error::invalid(
+ "KataBackend::shared_for needs an agent-sandbox configuration",
+ ));
+ };
+ let key = crate::hash::hex(
+ format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(),
+ );
+ static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new();
+ let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
+ let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner());
+ if let Some(existing) = guard.get(&key) {
+ return Ok(existing.clone());
+ }
+ let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| {
+ Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration")
+ })?);
+ let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?);
+ guard.insert(key, backend.clone());
+ Ok(backend)
+ }
+
+ /// The request a lease turns into, for one nonce. Split out of `acquire` so
+ /// a test can assert what a *configuration* becomes without a cluster in
+ /// the loop.
+ pub fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest {
+ ProvisionRequest {
+ sandbox_id: id.to_string(),
+ profile: spec.profile.clone(),
+ hub_addr: self.addr.clone(),
+ token: self.token.clone(),
+ ttl: spec.ttl,
+ image: self.cfg.sandbox_image(),
+ }
+ }
+
pub fn bind(
cfg: &Config,
listen: &str,
@@ -305,14 +344,7 @@ impl SandboxBackend for KataBackend {
let id = self.nonce();
let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = bounded(1);
self.pending.lock().unwrap().insert(id.clone(), tx);
- let req = ProvisionRequest {
- sandbox_id: id.clone(),
- profile: spec.profile.clone(),
- hub_addr: self.addr.clone(),
- token: self.token.clone(),
- ttl: spec.ttl,
- image: self.cfg.sandbox_image(),
- };
+ let req = self.provision_request(spec, &id);
if let Err(e) = self.provisioner.provision(&req) {
self.pending.lock().unwrap().remove(&id);
return Err(e);
@@ -378,12 +410,5 @@ mod tests {
assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken"));
}
- #[test]
- fn the_containerd_shape_names_the_kata_runtime() {
- let argv = nerdctl_argv(&req());
- let rt = argv.windows(2).find(|w| w[0] == "--runtime").expect("--runtime present");
- assert_eq!(rt[1], "io.containerd.kata.v2");
- assert!(argv.contains(&"--rm".to_string()), "no-cluster TTL floor: --rm");
- assert!(argv.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123"));
- }
+
}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index cdbfa02..13cf282 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -24,11 +24,15 @@
//! 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;
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
+use crossbeam_channel::{Receiver, Sender};
+
use crate::config::Config;
use crate::error::Result;
@@ -151,15 +155,61 @@ pub trait SandboxBackend: Send + Sync {
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::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 { .. } => Err(crate::error::Error::invalid(concat!(
- "sandbox kind \"agent-sandbox\" is not wired up yet; refusing to run this build ",
- "on a backend it was not configured for",
- ))),
+ 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)
+}
diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs
index 96b1ee6..d02335c 100644
--- a/src/sandbox/remote.rs
+++ b/src/sandbox/remote.rs
@@ -19,11 +19,9 @@
//! manifest/tar sync from the design sketch; that is deliberately not here
//! yet, and nothing should pretend otherwise.
-use std::collections::HashMap;
use std::io::BufReader;
-use std::net::TcpListener;
use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex, OnceLock};
+use std::sync::{Arc, Mutex};
use crossbeam_channel::Receiver;
@@ -41,64 +39,14 @@ pub struct RemoteBackend {
queue: Receiver<std::net::TcpStream>,
}
-/// A listener shared by every backend built from the same `(addr, token)`.
-struct Bound {
- local: String,
- rx: Receiver<std::net::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 `remote` already has: an
-/// agent dials in when the operator boots one, 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.
-fn registry() -> &'static Mutex<HashMap<(String, String), Bound>> {
- static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new();
- REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
-}
-
-fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
- 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(Bound { local: b.local.clone(), rx: b.rx.clone() });
- }
- let listener = TcpListener::bind(addr)?;
- let local = listener.local_addr()?.to_string();
- let (tx, rx) = 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 { local: bound.local.clone(), rx: bound.rx.clone() });
- Ok(bound)
-}
-
impl RemoteBackend {
/// Bind the agent listener — or share the one this process already bound for
- /// the same `(addr, token)`. `addr` may name port 0; [`Self::local_addr`]
- /// reports what actually got bound, which is how a test (or a supervisor)
- /// hands the address to the agent without a port negotiation dance.
+ /// the same `(addr, token)`; see [`crate::sandbox::bound_listener`]. `addr`
+ /// may name port 0; [`Self::local_addr`] reports what actually got bound,
+ /// which is how a test (or a supervisor) hands the address to the agent
+ /// without a port negotiation dance.
pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> {
- let bound = bound_listener(addr, token)?;
+ let bound = super::bound_listener(addr, token)?;
Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx })
}