diff options
| -rw-r--r-- | src/config.rs | 241 | ||||
| -rw-r--r-- | src/pipeline/mod.rs | 21 | ||||
| -rw-r--r-- | src/sandbox/kata.rs | 2 | ||||
| -rw-r--r-- | tests/config.rs | 190 |
4 files changed, 427 insertions, 27 deletions
diff --git a/src/config.rs b/src/config.rs index 00ac3e4..b86aada 100644 --- a/src/config.rs +++ b/src/config.rs @@ -9,6 +9,157 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +/// The tag a provisioned sandbox image gets when the configuration names a +/// provisioning kind but the caller has no image of its own (tests, mostly). +pub const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest"; + +/// Where build code runs (§8, the sandbox seam). +/// +/// Three kinds, and only three. This is an enum with required fields rather +/// than a string plus a `validate()` that has to be remembered, because the +/// failure mode of the string was silent: `sandbox_backend = "kata"` fell +/// through to loopback and a build that was supposed to run inside a VM ran +/// as the hub's own user. Here an unknown kind is a parse error naming the +/// valid set, and a kind is missing a field it needs is a parse error naming +/// the field. +/// +/// Secrets are redacted in `Debug` on purpose: a config that ends up in a log +/// line or a panic message must not carry the rendezvous token. +#[derive(Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum Sandbox { + /// Subprocesses of this process — tests, and the single-machine deployment + /// where §14's sudo rules are the boundary. The default, and the only kind + /// that needs no configuration, which is what keeps an existing + /// `config.json` valid without edits. + /// + /// Isolation is *none*: the sandbox is the hub's own user. + Loopback, + /// Sandboxes that dial in over the agent protocol (§8a). The hub never + /// provisions them; it waits for an agent carrying the token to connect. + Remote { + /// Address the hub listens on for agent dial-ins. Port 0 is allowed + /// and resolves at bind. + listen: String, + /// Shared secret an agent presents at rendezvous. A sandbox is + /// untrusted the moment it boots; this is the only thing saying "you + /// belong to me". Deploy it like a credential. + token: String, + /// Asserts that hub and sandbox see the same filesystem. The workspace + /// is not yet shipped to a remote sandbox (§8a), so a remote build only + /// works where the srcdir is shared; saying so explicitly is what + /// turns a silent misconfiguration into a refusal. See `Config`'s + /// startup guard. + #[serde(default)] + shared_workspace: bool, + }, + /// agent-sandbox: disposable Kata VMs provisioned by a Kubernetes CRD, so + /// the orchestrator enforces the TTL even if the hub dies (§8a). + AgentSandbox { + /// Kubernetes API server serving the agent-sandbox CRD. + api: String, + /// Namespace the sandboxes are created in. + namespace: String, + /// Bearer token for the API. A credential; never logged. + bearer: String, + /// Image a provisioned sandbox boots — the `sandbox-agent` entrypoint. + image: String, + /// Address the hub listens on for agent dial-ins. + listen: String, + /// Shared secret an agent presents at rendezvous. + token: String, + /// As [`Sandbox::Remote`]. + #[serde(default)] + shared_workspace: bool, + }, +} + +impl Default for Sandbox { + /// The fully local option, so a config that says nothing still builds. + fn default() -> Self { + Sandbox::Loopback + } +} + +impl std::fmt::Debug for Sandbox { + /// Hand-written so the secrets cannot ride along: a config that ends up in + /// a log line, a panic message, or an audit payload must not carry the + /// rendezvous token or the cluster bearer. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Sandbox::Loopback => f.write_str("Sandbox::Loopback"), + Sandbox::Remote { listen, shared_workspace, .. } => f + .debug_struct("Sandbox::Remote") + .field("listen", listen) + .field("shared_workspace", shared_workspace) + .field("token", &"[redacted]") + .finish(), + Sandbox::AgentSandbox { api, namespace, image, listen, shared_workspace, .. } => f + .debug_struct("Sandbox::AgentSandbox") + .field("api", api) + .field("namespace", namespace) + .field("image", image) + .field("listen", listen) + .field("shared_workspace", shared_workspace) + .field("token", &"[redacted]") + .field("bearer", &"[redacted]") + .finish(), + } + } +} + +impl Sandbox { + /// The kind name, for error messages and the UI. + pub fn kind(&self) -> &'static str { + match self { + Sandbox::Loopback => "loopback", + Sandbox::Remote { .. } => "remote", + Sandbox::AgentSandbox { .. } => "agent-sandbox", + } + } + + /// The rendezvous listener address, for the kinds that have one. + pub fn listen(&self) -> Option<&str> { + match self { + Sandbox::Remote { listen, .. } => Some(listen), + Sandbox::AgentSandbox { listen, .. } => Some(listen), + Sandbox::Loopback => None, + } + } + + /// The rendezvous token, for the kinds that have one. Never log this. + pub fn token(&self) -> Option<&str> { + match self { + Sandbox::Remote { token, .. } => Some(token), + Sandbox::AgentSandbox { token, .. } => Some(token), + Sandbox::Loopback => None, + } + } + + /// The image a provisioning backend boots. `None` for kinds that + /// provision nothing — there is no honest default for loopback, and a + /// field that is never consulted is a field that lies. + pub fn image(&self) -> Option<&str> { + match self { + Sandbox::AgentSandbox { image, .. } => Some(image), + _ => None, + } + } + + /// Whether the operator has asserted that hub and sandbox share a + /// filesystem. Loopback shares it by construction. + pub fn shared_workspace(&self) -> bool { + match self { + Sandbox::Loopback => true, + Sandbox::Remote { shared_workspace, .. } => *shared_workspace, + Sandbox::AgentSandbox { shared_workspace, .. } => *shared_workspace, + } + } + + /// The valid kind names, for the error that names them. + pub const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"]; +} + /// Runtime configuration. Persisted as `<root>/config.json`. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] @@ -43,20 +194,11 @@ pub struct Config { pub gpg_bin: String, /// Unprivileged user that runs PKGBUILD code (§14). Empty = current user. pub build_user: String, - /// Where build code runs: `loopback` (subprocesses of this process — - /// tests and the single-machine deployment) or `remote` (sandboxes that - /// dial in via the agent protocol). See `crate::sandbox`. - pub sandbox_backend: String, - /// Address the hub listens on for sandbox agents when - /// `sandbox_backend = "remote"`. Port 0 is allowed and resolves at bind. - pub agent_listen: String, - /// Shared secret an agent must present at rendezvous. A sandbox is - /// 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, + /// Where build code runs (§8). A tagged enum rather than a free-form string + /// plus a validation pass: the configurations that cannot work are not + /// representable, so there is no input that silently becomes "loopback". + /// See [`Sandbox`]. + pub sandbox: Sandbox, /// 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,10 +287,7 @@ impl Default for Config { repo_add_bin: "repo-add".into(), gpg_bin: "gpg".into(), build_user: String::new(), - sandbox_backend: "loopback".into(), - agent_listen: String::new(), - agent_token: String::new(), - sandbox_image: "aur-build-sandbox:latest".into(), + sandbox: Sandbox::default(), #[cfg(feature = "test-support")] hooks: TestHooks::default(), max_concurrent_builds: 1, @@ -161,6 +300,17 @@ impl Default for Config { } impl Config { + /// The image a provisioning sandbox boots, when this configuration + /// provisions anything. Falls back to the conventional tag so a test that + /// builds a `KataBackend` over a default config still gets a name to hand + /// an agent. + pub fn sandbox_image(&self) -> String { + self.sandbox + .image() + .unwrap_or(DEFAULT_SANDBOX_IMAGE) + .to_string() + } + /// Read `<root>/config.json`. /// /// The crate's own error type, like everything else that can fail (m-15): @@ -187,7 +337,9 @@ impl Config { ))); } let s = std::fs::read_to_string(&p)?; - let mut cfg: Config = serde_json::from_str(&s)?; + let v: serde_json::Value = serde_json::from_str(&s)?; + check_retired_sandbox_keys(&v)?; + let mut cfg: Config = serde_json::from_value(v)?; cfg.root = dir; Ok(cfg) } @@ -331,6 +483,57 @@ impl Config { } } +/// Whether a retired key holds exactly the value `init` used to write for a +/// local deployment. Such a value states nothing the default does not already +/// state, so it is noise from an old file rather than an intent that could be +/// lost — which is what lets a working local config keep loading across the +/// change. Anything else is refused. +fn retired_key_is_inert(key: &str, value: &str) -> bool { + match key { + "sandbox_backend" => value == "loopback", + "sandbox_image" => value.is_empty() || value == DEFAULT_SANDBOX_IMAGE, + _ => value.is_empty(), + } +} + +/// The sandbox configuration moved from four flat keys to one tagged object +/// ([`Sandbox`]). A retired key is refused rather than quietly ignored — but +/// only when it would have changed behaviour. +/// +/// `init` used to write `sandbox_backend: "loopback"` alongside three empty +/// strings, and a config carrying exactly that says nothing the default does +/// not already say, so it keeps loading untouched. Anything else is an error: +/// silently turning a retired `sandbox_backend: "remote"` into loopback is +/// precisely the failure the enum exists to make impossible. +fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> { + const RETIRED: [&str; 4] = ["sandbox_backend", "agent_listen", "agent_token", "sandbox_image"]; + let named: Vec<String> = RETIRED + .iter() + .filter(|k| { + let key: &str = k; + match v.get(key) { + None => false, + Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s), + Some(_) => true, + } + }) + .map(|k| format!("\"{k}\"")) + .collect(); + if named.is_empty() { + return Ok(()); + } + let example = concat!( + "replace them with a single \"sandbox\" object: ", + "{\"kind\":\"loopback\"}, ", + "{\"kind\":\"remote\",\"listen\":…,\"token\":…}, or ", + "{\"kind\":\"agent-sandbox\",\"api\":…,\"namespace\":…,\"bearer\":…,\"image\":…,\"listen\":…,\"token\":…}" + ); + Err(crate::error::Error::invalid(format!( + "{} are retired sandbox keys; {example}", + named.join(", ") + ))) +} + /// Absolutize a path without resolving symlinks and without requiring it to /// exist, both of which `canonicalize` insists on — and `init` saves its config /// before the tree under it is complete. diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 1f57bed..9a53d80 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -180,13 +180,20 @@ impl Ctx { /// point. `remote` binds the agent listener for the lifetime of this /// run's context. fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { - match cfg.sandbox_backend.as_str() { - "remote" => Ok(Arc::new(crate::sandbox::remote::RemoteBackend::bind( - cfg, - &cfg.agent_listen, - &cfg.agent_token, - )?)), - _ => Ok(Arc::new(crate::sandbox::loopback::LoopbackBackend::new(cfg))), + match &cfg.sandbox { + crate::config::Sandbox::Loopback => { + Ok(Arc::new(crate::sandbox::loopback::LoopbackBackend::new(cfg))) + } + crate::config::Sandbox::Remote { listen, token, .. } => Ok(Arc::new( + crate::sandbox::remote::RemoteBackend::bind(cfg, listen, token)?, + )), + // A valid kind that is not wired up yet is an error, never a + // fallthrough: a build configured for a Kata VM that silently ran + // as the hub's own user is the failure this enum was added to stop. + crate::config::Sandbox::AgentSandbox { .. } => Err(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", + ))), } } diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 9592dca..5c92557 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -311,7 +311,7 @@ impl SandboxBackend for KataBackend { hub_addr: self.addr.clone(), token: self.token.clone(), ttl: spec.ttl, - image: self.cfg.sandbox_image.clone(), + image: self.cfg.sandbox_image(), }; if let Err(e) = self.provisioner.provision(&req) { self.pending.lock().unwrap().remove(&id); diff --git a/tests/config.rs b/tests/config.rs index c62c4c9..30b687b 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -132,3 +132,193 @@ fn an_absolute_root_is_used_verbatim() { .unwrap(); assert_eq!(Config::load(dir).unwrap().root, dir); } + +// --------------------------------------------------------------------------- +// The sandbox configuration: three kinds, and only three. +// +// This used to be `sandbox_backend: String` matched with a `_ =>` arm that +// produced loopback, so `"kata"` — a real, intended backend — silently meant +// "run the untrusted PKGBUILD as the hub's own user". The kinds are an enum +// now, so the invalid configurations do not parse, and the error says which +// field or which value was wrong. +// --------------------------------------------------------------------------- + +/// Write a config carrying exactly this `sandbox` value and load it. +fn load_sandbox(sandbox: &str) -> Result<Config, String> { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join("config.json"), + format!("{{\n \"sandbox\": {sandbox}\n}}\n"), + ) + .unwrap(); + Config::load(tmp.path()).map_err(|e| e.to_string()) +} + +/// Load a config written as an older `aur-build init` would have written it. +fn load_raw(body: &str) -> Result<Config, String> { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("config.json"), body).unwrap(); + Config::load(tmp.path()).map_err(|e| e.to_string()) +} + +#[test] +fn each_sandbox_kind_parses_with_its_required_fields() { + match load_sandbox(r#"{"kind":"loopback"}"#).unwrap().sandbox { + aur_build::config::Sandbox::Loopback => {} + other => panic!("expected loopback, got {other:?}"), + } + + let remote = load_sandbox( + r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#, + ) + .unwrap(); + match &remote.sandbox { + aur_build::config::Sandbox::Remote { listen, token, shared_workspace } => { + assert_eq!(listen, "127.0.0.1:8787"); + assert_eq!(token, "s3cr3t"); + assert!(!*shared_workspace, "sharing the filesystem is asserted, never assumed"); + } + other => panic!("expected remote, got {other:?}"), + } + + let abs = load_sandbox( + r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"builds", + "bearer":"kube-token","image":"aur-build-sandbox:latest", + "listen":"0.0.0.0:8787","token":"s3cr3t","shared_workspace":true}"#, + ) + .unwrap(); + match &abs.sandbox { + aur_build::config::Sandbox::AgentSandbox { api, namespace, bearer, image, .. } => { + assert_eq!(api, "https://k8s:6443"); + assert_eq!(namespace, "builds"); + assert_eq!(bearer, "kube-token"); + assert_eq!(image, "aur-build-sandbox:latest"); + } + other => panic!("expected agent-sandbox, got {other:?}"), + } + assert_eq!(abs.sandbox_image(), "aur-build-sandbox:latest"); +} + +#[test] +fn a_missing_required_field_names_the_field() { + let err = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:8787"}"#).unwrap_err(); + assert!(err.contains("token"), "the error must name the missing field: {err}"); + + let err = load_sandbox(r#"{"kind":"remote","token":"t"}"#).unwrap_err(); + assert!(err.contains("listen"), "the error must name the missing field: {err}"); + + for missing in ["api", "namespace", "bearer", "image", "listen", "token"] { + let mut fields = vec![ + r#""api":"https://k8s:6443""#.to_string(), + r#""namespace":"builds""#.to_string(), + r#""bearer":"kube""#.to_string(), + r#""image":"img""#.to_string(), + r#""listen":"0.0.0.0:1""#.to_string(), + r#""token":"t""#.to_string(), + ]; + fields.retain(|f| !f.starts_with(&format!("\"{missing}\""))); + let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(","))) + .unwrap_err(); + assert!(err.contains(missing), "dropping {missing} must name it: {err}"); + } +} + +#[test] +fn a_misspelled_field_is_refused_not_ignored() { + // deny_unknown_fields: `listn` must not parse as "no listen address given". + let err = load_sandbox(r#"{"kind":"remote","listn":"127.0.0.1:1","token":"t"}"#).unwrap_err(); + assert!(err.contains("listn"), "a typo'd field name must be named: {err}"); +} + +#[test] +fn an_unknown_kind_names_the_value_and_the_valid_set() { + // The exact mistake this enum exists to catch: `kata` was a real intent, + // and the old match sent it quietly to loopback. + let err = load_sandbox(r#"{"kind":"kata"}"#).unwrap_err(); + assert!(err.contains("kata"), "must name the bad value: {err}"); + for kind in aur_build::config::Sandbox::KINDS { + assert!(err.contains(kind), "must name the valid set ({kind} missing): {err}"); + } +} + +#[test] +fn a_config_with_no_sandbox_object_is_the_local_backend() { + // The contract with every config.json already on disk: saying nothing means + // loopback, exactly as before. + let cfg = load_raw("{\n \"repo_name\": \"aur\"\n}\n").unwrap(); + assert!(matches!(cfg.sandbox, aur_build::config::Sandbox::Loopback)); + assert_eq!(cfg.repo_name, "aur", "the rest of the config is untouched"); + assert_eq!(cfg.sandbox_image(), aur_build::config::DEFAULT_SANDBOX_IMAGE); + assert!(cfg.sandbox.shared_workspace(), "loopback shares the filesystem by construction"); +} + +/// The file an older `aur-build init` wrote, verbatim. It carries the retired +/// keys, but they say `loopback` and three empty strings — which is what the +/// default already means — so it must still load rather than strand a working +/// local deployment on a syntax change. +#[test] +fn a_config_init_wrote_before_the_enum_still_loads() { + let cfg = load_raw( + r#"{ + "root": "/var/lib/aur-build", + "repo_name": "aur", + "arch": "x86_64", + "signing_key_id": "", + "bind": "127.0.0.1:8484", + "password": "", + "base_url": "http://127.0.0.1:8484", + "build_profile": "extra-x86_64", + "git_bin": "git", + "makepkg_bin": "makepkg", + "pacman_bin": "pacman", + "repo_add_bin": "repo-add", + "gpg_bin": "gpg", + "build_user": "", + "sandbox_backend": "loopback", + "agent_listen": "", + "agent_token": "", + "sandbox_image": "aur-build-sandbox:latest", + "max_concurrent_builds": 1, + "lease_secs": 90, + "min_free_disk_mb": 1024, + "max_transient_attempts": 3, + "dispatch_tick_secs": 2 +}"#, + ) + .unwrap(); + assert!(matches!(cfg.sandbox, aur_build::config::Sandbox::Loopback)); + assert_eq!(cfg.lease_secs, 90); +} + +/// …but retired keys that *would* have changed behaviour are refused, not +/// quietly reinterpreted. A retired `"remote"` becoming loopback is the exact +/// silent substitution the enum was introduced to make impossible. +#[test] +fn retired_sandbox_keys_that_mean_something_are_refused() { + let err = load_raw(r#"{ "sandbox_backend": "remote", "agent_listen": "0.0.0.0:1", "agent_token": "t" }"#) + .unwrap_err(); + assert!(err.contains("sandbox_backend"), "must name the retired key: {err}"); + assert!(err.contains("sandbox"), "must point at the replacement: {err}"); + + // Even one retired key with content is enough to refuse. + let err = load_raw(r#"{ "sandbox_backend": "kata" }"#).unwrap_err(); + assert!(err.contains("sandbox_backend"), "{err}"); + + // An empty retired key is noise, not intent, and stays tolerated. + assert!(load_raw(r#"{ "sandbox_backend": "loopback", "agent_token": "" }"#).is_ok()); +} + +#[test] +fn the_rendezvous_secrets_never_reach_debug() { + // A config that ends up in a log line, a panic, or an audit payload must + // not carry the token or the cluster bearer. + let cfg = load_sandbox( + r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"builds", + "bearer":"kube-token","image":"img","listen":"0.0.0.0:1","token":"s3cr3t"}"#, + ) + .unwrap(); + let shown = format!("{cfg:?}"); + assert!(!shown.contains("s3cr3t"), "the rendezvous token leaked into Debug"); + assert!(!shown.contains("kube-token"), "the cluster bearer leaked into Debug"); + assert!(shown.contains("builds"), "the non-secret fields are still visible: {shown}"); +} |
