summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/lib.rs1
-rw-r--r--src/pipeline/mod.rs23
-rw-r--r--src/pipeline/steps.rs56
-rw-r--r--src/sandbox/loopback.rs133
-rw-r--r--src/sandbox/mod.rs131
5 files changed, 320 insertions, 24 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 9048ff8..d4e69de 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -18,6 +18,7 @@ pub mod pkginfo;
pub mod pkgver;
pub mod recipe;
pub mod review;
+pub mod sandbox;
/// The §16a fake toolchain: stand-ins for `makepkg`, `mkarchroot`, `gpg`,
/// `repo-add` and `pacman` so the whole step machine runs without root, network
/// or an Arch chroot.
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index bd37258..5e0a823 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -10,12 +10,15 @@ pub mod dispatch;
mod steps;
use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
use crate::config::Config;
use crate::db::{self, builds, Db, Pkgbase};
use crate::db::model::*;
use crate::db::SnapshotRow;
use crate::error::{Error, Result};
+use crate::sandbox::{Sandbox, SandboxBackend};
/// The approved source identity a build must reproduce.
///
@@ -120,6 +123,9 @@ pub struct Ctx {
pub log: PathBuf,
pub profile: String,
pub attempt: i64,
+ /// Where build code runs. Defaults to the loopback backend (§8, sandbox
+ /// seam); the pipeline itself never spawns a build subprocess directly.
+ pub backend: Arc<dyn SandboxBackend>,
}
impl Ctx {
@@ -165,9 +171,26 @@ impl Ctx {
log: cfg.build_log_path(build_id),
profile,
attempt,
+ backend: Arc::new(crate::sandbox::loopback::LoopbackBackend::new(cfg)),
})
}
+ /// Lease a sandbox for this build's profile. Today every step acquires and
+ /// releases around itself; a remote backend will hold one sandbox across
+ /// the sandbox-bearing steps of a build, and steps stay idempotent either
+ /// way (I5). The TTL is the lease window: a sandbox that outlives it is
+ /// assumed dead, which is exactly what the reaper already concludes about
+ /// an expired build lease.
+ pub fn sandbox(&self) -> Result<Arc<dyn Sandbox>> {
+ let spec = crate::sandbox::SandboxSpec {
+ profile: self.profile.clone(),
+ task: self.build.id.clone(),
+ ttl: Duration::from_secs(self.cfg.lease_secs.max(1) as u64),
+ disk_mb: self.cfg.min_free_disk_mb,
+ };
+ self.backend.acquire(&spec)
+ }
+
/// Append to the build log; the SSE tail reads this file (§12).
pub fn log_line(&self, line: &str) {
use std::io::Write;
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index 7187e13..98089ca 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -4,12 +4,12 @@
//! the long-running child process happens outside any transaction (§11a).
use std::path::Path;
-use std::process::Command;
use crate::db::{self, builds, model::*};
use crate::error::{Error, Result};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
+use crate::sandbox::Cmd;
use crate::watch::digests::cached_path;
pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> {
@@ -119,12 +119,12 @@ fn chroot(ctx: &Ctx) -> Result<StepResult> {
let seed = ctx.cfg.chroot_seed(&ctx.profile);
if !seed.exists() {
std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?;
- let mut cmd = Command::new(&ctx.cfg.mkarchroot_bin);
// Real devtools usage: `mkarchroot [options] <working-dir> <packages...>`.
- cmd.arg(&seed).args(&ctx.cfg.mkarchroot_args);
- ctx.cfg.child_env(&mut cmd);
- let out = cmd.output()?;
- if !out.status.success() {
+ let mut argv = vec![ctx.cfg.mkarchroot_bin.clone(), seed.display().to_string()];
+ argv.extend(ctx.cfg.mkarchroot_args.iter().cloned());
+ let sbx = ctx.sandbox()?;
+ let out = sbx.run(&Cmd::new(argv), &mut |_| {})?;
+ if !out.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.mkarchroot_bin.clone(),
detail: String::from_utf8_lossy(&out.stderr).into_owned(),
@@ -187,11 +187,10 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> {
}
return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into()));
}
- let mut cmd = Command::new(&ctx.cfg.makepkg_bin);
- cmd.current_dir(&ctx.srcdir).arg("--vercheck");
- ctx.cfg.child_env(&mut cmd);
- let out = cmd.output()?;
- if !out.status.success() {
+ let cmd = vec![ctx.cfg.makepkg_bin.clone(), "--vercheck".to_string()];
+ let sbx = ctx.sandbox()?;
+ let out = sbx.run(&Cmd::new(cmd).in_dir(&ctx.srcdir), &mut |_| {})?;
+ if !out.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.makepkg_bin.clone(),
detail: String::from_utf8_lossy(&out.stderr).into_owned(),
@@ -216,25 +215,34 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> {
/// the file the SSE tail reads.
fn build(ctx: &Ctx) -> Result<StepResult> {
let seed = ctx.cfg.chroot_seed(&ctx.profile);
- let mut cmd = Command::new(&ctx.cfg.makechrootpkg_bin);
- cmd.current_dir(&ctx.srcdir);
- cmd.args(["-c", "-r", &seed.display().to_string(), "--"]);
+ let mut argv = vec![
+ ctx.cfg.makechrootpkg_bin.clone(),
+ "-c".into(),
+ "-r".into(),
+ seed.display().to_string(),
+ "--".into(),
+ ];
if !ctx.cfg.signing_key_id.is_empty() {
- cmd.arg(format!("-si{}", ctx.cfg.signing_key_id));
+ argv.push(format!("-si{}", ctx.cfg.signing_key_id));
}
- cmd.arg("-f");
- ctx.cfg.child_env(&mut cmd);
- let out = cmd.output()?;
- // Capture the child's output into the build log regardless of outcome.
+ argv.push("-f".into());
+ // Capture the child's output into the build log regardless of outcome —
+ // the sandbox streams it here as it arrives, and the SSE tail reads the
+ // same file.
if let Some(parent) = ctx.log.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
- if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log) {
- let _ = f.write_all(&out.stdout);
- let _ = f.write_all(&out.stderr);
- }
- if !out.status.success() {
+ let mut log_file = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log).ok();
+ let mut on_log = move |bytes: &[u8]| {
+ if let Some(f) = log_file.as_mut() {
+ let _ = f.write_all(bytes);
+ }
+ };
+ let sbx = ctx.sandbox()?;
+ let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?;
+ drop(on_log); // closes the log file before the outcome is recorded
+ if !out.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.makechrootpkg_bin.clone(),
detail: tail(&out.stderr),
diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs
new file mode 100644
index 0000000..1b31b1a
--- /dev/null
+++ b/src/sandbox/loopback.rs
@@ -0,0 +1,133 @@
+//! The loopback backend: run sandbox commands as local subprocesses.
+//!
+//! This is today's behavior wearing the new interface — same `Config::child_env`
+//! shim protocol (§16a), same captured output, same process as the hub. It is
+//! what `cargo test` exercises and what a single machine with devtools runs;
+//! the shim suite passing unchanged through this file is what makes the seam a
+//! pure refactor rather than a re-architecture.
+//!
+//! Isolation here is *none*: the "sandbox" is the hub's own user. That is
+//! honest — the loopback backend is for development, tests, and the local
+//! chroot deployment where §14's sudo rules are the boundary — and the Kata
+//! backend is where the machine boundary lives.
+
+use std::fs;
+use std::io::Read;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use crate::config::Config;
+use crate::error::{Error, Result};
+use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};
+
+pub struct LoopbackBackend {
+ cfg: Config,
+}
+
+impl LoopbackBackend {
+ pub fn new(cfg: &Config) -> Self {
+ Self { cfg: cfg.clone() }
+ }
+}
+
+impl SandboxBackend for LoopbackBackend {
+ fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
+ // The "pool" is this machine: acquire always succeeds, instantly, and
+ // the TTL is a promise the loopback sandbox does not have to keep
+ // because there is nothing to leak — the process dies with the hub.
+ let blobs = blob_root(&self.cfg).join(safe_name(&spec.task));
+ fs::create_dir_all(&blobs)?;
+ Ok(Arc::new(LoopbackSandbox {
+ id: format!("loopback:{}", spec.task),
+ blobs,
+ cfg: self.cfg.clone(),
+ }))
+ }
+
+ fn status(&self) -> Result<Vec<SandboxInfo>> {
+ Ok(vec![SandboxInfo {
+ id: "loopback".into(),
+ profile: self.cfg.build_profile.clone(),
+ warm: true,
+ }])
+ }
+}
+
+pub struct LoopbackSandbox {
+ id: String,
+ blobs: PathBuf,
+ cfg: Config,
+}
+
+impl Sandbox for LoopbackSandbox {
+ fn id(&self) -> &str {
+ &self.id
+ }
+
+ fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> {
+ let argv0 = cmd
+ .argv
+ .first()
+ .ok_or_else(|| Error::invalid("sandbox command has no argv[0]"))?;
+ let mut c = std::process::Command::new(argv0);
+ c.args(&cmd.argv[1..]);
+ if let Some(dir) = &cmd.cwd {
+ c.current_dir(dir);
+ }
+ // The shim protocol lives here, not in the steps: a step that cannot
+ // tell loopback from a remote sandbox is the property under test.
+ self.cfg.child_env(&mut c);
+ let out = c.output()?;
+ on_log(&out.stdout);
+ on_log(&out.stderr);
+ Ok(Exit { code: out.status.code(), stdout: out.stdout, stderr: out.stderr })
+ }
+
+ fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()> {
+ let path = self.blob_path(digest)?;
+ let mut f = fs::File::create(&path)?;
+ std::io::copy(r, &mut f)?;
+ Ok(())
+ }
+
+ fn get(&self, digest: &str) -> Result<Box<dyn Read>> {
+ let path = self.blob_path(digest)?;
+ Ok(Box::new(fs::File::open(&path)?))
+ }
+
+ fn destroy(&self) -> Result<()> {
+ // Nothing to reclaim: the sandbox is this process. Blob scratch is
+ // disposable staging and falls to `gc` like the rest of `staging/`.
+ Ok(())
+ }
+}
+
+impl LoopbackSandbox {
+ /// Digests double as blob filenames, so they must be path-safe. The digests
+ /// this codebase produces are hex or `hex-sig`; anything else is a caller
+ /// bug (or, later, a hostile sandbox) and fails closed.
+ fn blob_path(&self, digest: &str) -> Result<PathBuf> {
+ if digest.is_empty() || digest.len() > 128 {
+ return Err(Error::invalid(format!("blob digest {digest:?} is not usable")));
+ }
+ if !digest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
+ return Err(Error::invalid(format!("blob digest {digest:?} is not path-safe")));
+ }
+ Ok(self.blobs.join(digest))
+ }
+}
+
+fn blob_root(cfg: &Config) -> PathBuf {
+ cfg.staging_dir().join("blobs")
+}
+
+/// Filesystem-safe name for a task id, same spirit as `config::slug`.
+fn safe_name(s: &str) -> String {
+ s.chars()
+ .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
+ .collect::<String>()
+ .trim_matches('-')
+ .chars()
+ .take(64)
+ .collect()
+}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
new file mode 100644
index 0000000..18c98ad
--- /dev/null
+++ b/src/sandbox/mod.rs
@@ -0,0 +1,131 @@
+//! 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::io::Read;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::error::Result;
+
+pub mod loopback;
+
+/// 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.
+#[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>>;
+}