summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/bin/sandbox-agent.rs3
-rw-r--r--src/config.rs4
-rw-r--r--src/sandbox/agent.rs9
-rw-r--r--src/sandbox/kata.rs389
-rw-r--r--src/sandbox/mod.rs1
-rw-r--r--src/sandbox/remote.rs28
-rw-r--r--tests/kata.rs89
7 files changed, 514 insertions, 9 deletions
diff --git a/src/bin/sandbox-agent.rs b/src/bin/sandbox-agent.rs
index 1c2a8d8..4e959a9 100644
--- a/src/bin/sandbox-agent.rs
+++ b/src/bin/sandbox-agent.rs
@@ -11,6 +11,7 @@ fn main() {
let mut token = None;
let mut profile = Some("extra-x86_64".to_string());
let mut ttl = 90u64;
+ let mut agent_id = None;
let args: Vec<String> = std::env::args().skip(1).collect();
let mut i = 0;
while i < args.len() {
@@ -22,6 +23,7 @@ fn main() {
"--hub" => take(&mut i).map(|v| hub = Some(v)),
"--token" => take(&mut i).map(|v| token = Some(v)),
"--profile" => take(&mut i).map(|v| profile = Some(v)),
+ "--agent-id" => take(&mut i).map(|v| agent_id = Some(v)),
"--ttl" => take(&mut i).and_then(|v| v.parse::<u64>().map(|t| ttl = t).map_err(|_| "bad ttl".to_string())),
other => Err(format!("unknown argument {other}")),
};
@@ -44,6 +46,7 @@ fn main() {
token,
profile: profile.unwrap(),
ttl: Duration::from_secs(ttl),
+ agent_id,
};
if let Err(e) = aur_build::sandbox::agent::serve(&opts) {
eprintln!("sandbox-agent: {e}");
diff --git a/src/config.rs b/src/config.rs
index 864540c..bda99e9 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -54,6 +54,9 @@ pub struct Config {
/// untrusted the moment it boots; this token is the only thing telling
/// the hub "you belong to me" — deploy it like one.
pub agent_token: String,
+ /// Image a provisioned sandbox boots (the `sandbox-agent` entrypoint).
+ /// Only consulted by provisioning backends (kata).
+ pub sandbox_image: String,
/// Test-only hooks (§16a). Not part of the production configuration at all
/// unless the crate is built with `test-support` — see [`TestHooks`].
#[cfg(feature = "test-support")]
@@ -145,6 +148,7 @@ impl Default for Config {
sandbox_backend: "loopback".into(),
agent_listen: String::new(),
agent_token: String::new(),
+ sandbox_image: "aur-build-sandbox:latest".into(),
#[cfg(feature = "test-support")]
hooks: TestHooks::default(),
max_concurrent_builds: 1,
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs
index 3964d2c..09a6f93 100644
--- a/src/sandbox/agent.rs
+++ b/src/sandbox/agent.rs
@@ -33,11 +33,18 @@ pub struct AgentOptions {
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 = format!("sandbox-{}", std::process::id());
+ let agent_id = opts
+ .agent_id
+ .clone()
+ .unwrap_or_else(|| format!("sandbox-{}", std::process::id()));
wire::write_frame(
&mut stream.try_clone()?,
&Frame::Hello {
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
new file mode 100644
index 0000000..7a83f89
--- /dev/null
+++ b/src/sandbox/kata.rs
@@ -0,0 +1,389 @@
+//! The kata backend: ad-hoc, TTL-bounded sandboxes provisioned by an
+//! orchestrator, leased over the same agent protocol as everything else.
+//!
+//! This is composition, not a new protocol: a kata sandbox is a small VM that
+//! boots the `sandbox-agent` image pointed at this hub, and `acquire` is
+//! "ask the provisioner for a box, then wait for *that specific box* to dial
+//! in". The nonce each lease generates is handed to the provisioner and comes
+//! back as the agent's `agent_id`, so a stray sandbox can never be leased to
+//! 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 `LocalAgentProvisioner` is the shape this tier is tested with: a real
+//! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the
+//! loopback backend is to a clean machine — the honest stand-in that keeps
+//! the interface itself under test.
+
+use std::collections::HashMap;
+use std::io::BufReader;
+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::time::Duration;
+
+use crossbeam_channel::{bounded, Receiver, Sender};
+
+use crate::config::Config;
+use crate::error::{Error, Result};
+use crate::sandbox::remote::RemoteSandbox;
+use crate::sandbox::wire::{self, Frame};
+use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};
+
+/// What any provisioner needs to know to start one sandbox pointed at this
+/// hub. `sandbox_id` is the rendezvous nonce: the hub will only lease the
+/// connection whose hello carries it back.
+#[derive(Debug, Clone)]
+pub struct ProvisionRequest {
+ pub sandbox_id: String,
+ pub profile: String,
+ pub hub_addr: String,
+ pub token: String,
+ pub ttl: Duration,
+ pub image: String,
+}
+
+pub trait Provisioner: Send + Sync {
+ /// Start a sandbox for `req`. Must return quickly; the sandbox dials in
+ /// asynchronously and `acquire` waits on the dial.
+ fn provision(&self, req: &ProvisionRequest) -> Result<()>;
+ /// Reclaim a sandbox out of band (TTL would also do it eventually).
+ fn reclaim(&self, sandbox_id: &str) -> Result<()>;
+ fn name(&self) -> &str;
+}
+
+/// The agent-sandbox-style CR: one disposable Sandbox per build, Kata for the
+/// VM boundary, `activeDeadlineSeconds` so the *orchestrator* enforces the
+/// TTL even if the hub dies. The token rides in args for v1; a production
+/// deployment should mount it from a Secret, and this comment is the honest
+/// place that says so.
+pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
+ serde_json::json!({
+ "apiVersion": "agents.x-k8s.io/v1alpha1",
+ "kind": "Sandbox",
+ "metadata": {
+ "name": req.sandbox_id,
+ "labels": {
+ "aur-build.io/managed-by": "aur-build",
+ "aur-build.io/profile": req.profile,
+ },
+ },
+ "spec": {
+ "runtimeClass": "kata",
+ "shutdownPolicy": "Delete",
+ "activeDeadlineSeconds": req.ttl.as_secs(),
+ "template": {
+ "spec": {
+ "containers": [{
+ "name": "build-agent",
+ "image": req.image,
+ "args": [
+ "--hub", req.hub_addr,
+ "--token", req.token,
+ "--agent-id", req.sandbox_id,
+ "--profile", req.profile,
+ "--ttl", req.ttl.as_secs().to_string(),
+ ],
+ }],
+ },
+ },
+ },
+ })
+}
+
+/// 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(),
+ ]
+}
+
+/// Talks to a Kubernetes API serving an agent-sandbox-style CRD. Real code,
+/// exercised only by the gated live tier — this repository's philosophy is
+/// that a gated tier is recorded as skipped, never silently absent.
+pub struct K8sSandboxProvisioner {
+ pub api: String,
+ pub bearer: String,
+ pub namespace: String,
+}
+
+impl Provisioner for K8sSandboxProvisioner {
+ fn provision(&self, req: &ProvisionRequest) -> Result<()> {
+ let url = format!(
+ "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes",
+ self.api.trim_end_matches('/'),
+ self.namespace
+ );
+ ureq::post(&url)
+ .set("Authorization", &format!("Bearer {}", self.bearer))
+ .send_json(sandbox_cr(req))
+ .map_err(|e| Error::other(format!("kata provision failed: {e}")))?;
+ Ok(())
+ }
+
+ fn reclaim(&self, sandbox_id: &str) -> Result<()> {
+ let url = format!(
+ "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes/{sandbox_id}",
+ self.api.trim_end_matches('/'),
+ self.namespace
+ );
+ ureq::delete(&url)
+ .set("Authorization", &format!("Bearer {}", self.bearer))
+ .call()
+ .map_err(|e| Error::other(format!("kata reclaim failed: {e}")))?;
+ Ok(())
+ }
+
+ fn name(&self) -> &str {
+ "k8s-sandbox-crd"
+ }
+}
+
+/// The test/dev provisioner: a real `sandbox-agent` process, no VM. This is
+/// what keeps the kata rendezvous and TTL logic under honest test on a
+/// machine with neither root nor `/dev/kvm`.
+pub struct LocalAgentProvisioner {
+ pub bin: PathBuf,
+ children: Mutex<HashMap<String, Child>>,
+}
+
+impl LocalAgentProvisioner {
+ pub fn new(bin: impl Into<PathBuf>) -> Self {
+ Self { bin: bin.into(), children: Mutex::new(HashMap::new()) }
+ }
+}
+
+impl Provisioner for LocalAgentProvisioner {
+ fn provision(&self, req: &ProvisionRequest) -> Result<()> {
+ let child = Command::new(&self.bin)
+ .arg("--hub")
+ .arg(&req.hub_addr)
+ .arg("--token")
+ .arg(&req.token)
+ .arg("--agent-id")
+ .arg(&req.sandbox_id)
+ .arg("--profile")
+ .arg(&req.profile)
+ .arg("--ttl")
+ .arg(req.ttl.as_secs().to_string())
+ .spawn()
+ .map_err(|e| Error::other(format!("local agent spawn failed: {e}")))?;
+ self.children.lock().unwrap().insert(req.sandbox_id.clone(), child);
+ Ok(())
+ }
+
+ fn reclaim(&self, sandbox_id: &str) -> Result<()> {
+ if let Some(mut child) = self.children.lock().unwrap().remove(sandbox_id) {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ Ok(())
+ }
+
+ fn name(&self) -> &str {
+ "local-agent"
+ }
+}
+
+pub struct KataBackend {
+ cfg: Config,
+ token: String,
+ addr: String,
+ provisioner: Arc<dyn Provisioner>,
+ /// Nonce → the waiting `acquire`. The accept thread routes dial-ins by
+ /// the `agent_id` the hello frame carries; anything unknown is dropped,
+ /// because a sandbox the hub did not ask for is a sandbox to not lease.
+ pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>,
+ counter: AtomicU64,
+}
+
+impl KataBackend {
+ pub fn bind(
+ cfg: &Config,
+ listen: &str,
+ token: &str,
+ provisioner: Arc<dyn Provisioner>,
+ ) -> Result<Self> {
+ let listener = TcpListener::bind(listen)?;
+ let addr = listener.local_addr()?.to_string();
+ let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new()));
+ {
+ let (token, pending) = (token.to_string(), pending.clone());
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ let Ok(stream) = stream else { break };
+ route_dial_in(stream, &token, &pending);
+ }
+ });
+ }
+ Ok(Self {
+ cfg: cfg.clone(),
+ token: token.to_string(),
+ addr,
+ provisioner,
+ pending,
+ counter: AtomicU64::new(1),
+ })
+ }
+
+ /// Reclaim a sandbox out of band. The TTL would also do this eventually;
+ /// this is just not making someone else pay for the wait.
+ pub fn reclaim(&self, sandbox_id: &str) -> Result<()> {
+ self.provisioner.reclaim(sandbox_id)
+ }
+
+ pub fn local_addr(&self) -> &str {
+ &self.addr
+ }
+
+ fn nonce(&self) -> String {
+ let n = self.counter.fetch_add(1, Ordering::SeqCst);
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0);
+ crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string()
+ }
+}
+
+/// Read one hello and route it. A connection that greets with a nonce nobody
+/// asked for is dropped unread — the TTL on the provisioner cleans that box
+/// up, and the hub never leases a sandbox it did not order.
+fn route_dial_in(
+ stream: TcpStream,
+ token: &str,
+ pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>,
+) {
+ // Bounded so a box that connects and says nothing cannot park the loop.
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
+ let mut reader = match stream.try_clone() {
+ Ok(s) => BufReader::new(s),
+ Err(_) => return,
+ };
+ let hello = match wire::read_frame(&mut reader) {
+ Ok(Some(Frame::Hello { token: t, agent_id, .. })) if t == token => agent_id,
+ _ => return,
+ };
+ let slot = pending.lock().unwrap().remove(&hello).map(|tx| (tx, stream));
+ if let Some((tx, stream)) = slot {
+ let _ = tx.send(stream);
+ }
+}
+
+impl SandboxBackend for KataBackend {
+ fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
+ 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.clone(),
+ };
+ if let Err(e) = self.provisioner.provision(&req) {
+ self.pending.lock().unwrap().remove(&id);
+ return Err(e);
+ }
+ // The TTL is the wait bound *and* the sandbox's own deadline: nobody
+ // dials in by then, and nobody ever will — the box is dying or dead.
+ let stream = match rx.recv_timeout(spec.ttl) {
+ Ok(s) => s,
+ Err(_) => {
+ self.pending.lock().unwrap().remove(&id);
+ let _ = self.provisioner.reclaim(&id);
+ return Err(Error::other(format!(
+ "sandbox {id} for profile {} never dialed in within its TTL",
+ spec.profile
+ )));
+ }
+ };
+ let ttl = spec.ttl.max(Duration::from_secs(1));
+ wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?;
+ Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl)))
+ }
+
+ fn status(&self) -> Result<Vec<SandboxInfo>> {
+ Ok(vec![SandboxInfo {
+ id: format!("kata@{} via {}", self.addr, self.provisioner.name()),
+ profile: self.cfg.build_profile.clone(),
+ warm: !self.pending.lock().unwrap().is_empty(),
+ }])
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn req() -> ProvisionRequest {
+ ProvisionRequest {
+ sandbox_id: "sbx-abc123".into(),
+ profile: "extra-x86_64".into(),
+ hub_addr: "10.0.0.5:9443".into(),
+ token: "t0ken".into(),
+ ttl: Duration::from_secs(120),
+ image: "aur-build-sandbox:latest".into(),
+ }
+ }
+
+ #[test]
+ fn the_cr_asks_kata_for_a_vm_that_dies_on_its_own_by_ttl() {
+ let cr = sandbox_cr(&req());
+ assert_eq!(cr["spec"]["runtimeClass"], "kata");
+ assert_eq!(cr["spec"]["activeDeadlineSeconds"], 120,
+ "the orchestrator must enforce the TTL even if the hub dies");
+ assert_eq!(cr["spec"]["shutdownPolicy"], "Delete");
+ let args = cr["spec"]["template"]["spec"]["containers"][0]["args"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_str().unwrap().to_string())
+ .collect::<Vec<_>>();
+ // The rendezvous nonce and the hub coordinates must reach the agent.
+ assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123"));
+ assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443"));
+ 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 89bef23..b20788d 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -32,6 +32,7 @@ use std::time::Duration;
use crate::error::Result;
pub mod agent;
+pub mod kata;
pub mod loopback;
pub mod remote;
pub mod wire;
diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs
index c1ad998..e68ea0f 100644
--- a/src/sandbox/remote.rs
+++ b/src/sandbox/remote.rs
@@ -98,14 +98,9 @@ impl SandboxBackend for RemoteBackend {
};
wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?;
let _ = stream.set_read_timeout(None);
- Ok(Arc::new(RemoteSandbox {
- cfg: self.cfg.clone(),
- id: agent_id,
- ttl: spec.ttl,
- reader: Mutex::new(reader),
- writer: Mutex::new(stream),
- req: AtomicU64::new(1),
- }))
+ Ok(Arc::new(RemoteSandbox::after_hello(
+ &self.cfg, stream, agent_id, spec.ttl,
+ )))
}
fn status(&self) -> Result<Vec<SandboxInfo>> {
@@ -127,6 +122,23 @@ pub struct RemoteSandbox {
}
impl RemoteSandbox {
+ /// Wrap a stream whose `Hello` has been verified and answered. Split out
+ /// so the kata backend can lease a rendezvoused connection with its own
+ /// accept loop without duplicating the sandbox half.
+ pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self {
+ let reader = BufReader::new(
+ stream.try_clone().expect("cloning a connected tcp stream cannot fail"),
+ );
+ Self {
+ cfg: cfg.clone(),
+ id: agent_id,
+ ttl,
+ reader: Mutex::new(reader),
+ writer: Mutex::new(stream),
+ req: AtomicU64::new(1),
+ }
+ }
+
fn send(&self, frame: &Frame) -> Result<()> {
wire::write_frame(&mut *self.writer.lock().unwrap(), frame).map_err(Into::into)
}
diff --git a/tests/kata.rs b/tests/kata.rs
new file mode 100644
index 0000000..eb7c333
--- /dev/null
+++ b/tests/kata.rs
@@ -0,0 +1,89 @@
+//! The kata backend, tested the way every gated tier here is tested: the
+//! logic runs for real on a machine with neither root nor `/dev/kvm`, and
+//! only the live-orchestrator tier skips — with a printed note, never
+//! silently absent (the convention `versions::vercmp_matches_the_system_oracle`
+//! set).
+
+mod common;
+
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use aur_build::config::Config;
+use aur_build::error::Result;
+use aur_build::sandbox::kata::{KataBackend, LocalAgentProvisioner, ProvisionRequest, Provisioner};
+use aur_build::sandbox::{Cmd, SandboxBackend, SandboxSpec};
+use common::shim_dir;
+
+#[test]
+fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
+ // Real sandbox-agent process, real frames, real nonce-matched dial-in —
+ // everything about the kata lease path except the VM.
+ let cfg = Config::default();
+ let prov = Arc::new(LocalAgentProvisioner::new(shim_dir().join("sandbox-agent")));
+ let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "kata-token", prov.clone()).unwrap();
+ let sbx = backend
+ .acquire(&SandboxSpec::new("extra-x86_64", "build-1", Duration::from_secs(15)))
+ .expect("the provisioned agent should dial in and rendezvous");
+ let out = sbx
+ .run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {})
+ .unwrap();
+ assert!(out.success());
+ assert_eq!(String::from_utf8_lossy(&out.stdout), "hi from the sandbox\n");
+ sbx.destroy().unwrap();
+}
+
+#[test]
+fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() {
+ struct NullProvisioner;
+ impl Provisioner for NullProvisioner {
+ fn provision(&self, _req: &ProvisionRequest) -> Result<()> {
+ Ok(())
+ }
+ fn reclaim(&self, _id: &str) -> Result<()> {
+ Ok(())
+ }
+ fn name(&self) -> &str {
+ "null"
+ }
+ }
+ let cfg = Config::default();
+ let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
+ let started = Instant::now();
+ let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) {
+ Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"),
+ Err(e) => e,
+ };
+ assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL");
+ assert!(err.to_string().contains("never dialed in"), "{err}");
+}
+
+#[test]
+fn the_live_kata_tier_is_recorded_not_silently_absent() {
+ // The §16a convention: a tier that needs hardware or infrastructure
+ // announces its own skip rather than pretending to have run.
+ if !Path::new("/dev/kvm").exists() {
+ println!("note: no /dev/kvm on this host; the live kata tier is skipped, not passed");
+ return;
+ }
+ let Ok(api) = std::env::var("AUR_KATA_API") else {
+ println!("note: /dev/kvm present but AUR_KATA_API unset; live kata tier still skipped");
+ return;
+ };
+ // Recorded as reached: a real cluster lease. Kept minimal on purpose —
+ // acquire, one command, reclaim.
+ let cfg = Config::default();
+ let prov = Arc::new(aur_build::sandbox::kata::K8sSandboxProvisioner {
+ api,
+ bearer: std::env::var("AUR_KATA_TOKEN").unwrap_or_default(),
+ namespace: std::env::var("AUR_KATA_NS").unwrap_or_else(|_| "default".into()),
+ });
+ let backend = KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap();
+ let sbx = backend
+ .acquire(&SandboxSpec::new("extra-x86_64", "live", Duration::from_secs(300)))
+ .expect("live kata sandbox should lease");
+ let out = sbx.run(&Cmd::new(["/bin/echo", "kata"]), &mut |_| {}).unwrap();
+ assert!(out.success() && String::from_utf8_lossy(&out.stdout).contains("kata"));
+ sbx.destroy().unwrap();
+}