use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; pub const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest"; #[derive(Clone, Default, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] pub enum Sandbox { #[default] Loopback, Remote { listen: String, /// Rendezvous secret. Deploy it like a credential. token: String, #[serde(default)] shared_workspace: bool, }, AgentSandbox { api: String, namespace: String, /// Never logged. bearer: String, image: String, listen: String, token: String, #[serde(default)] shared_workspace: bool, }, } impl std::fmt::Debug for Sandbox { // Hand-written so the rendezvous token and cluster bearer cannot ride into // a log line, a panic message, or an audit payload. 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 { pub fn kind(&self) -> &'static str { match self { Sandbox::Loopback => "loopback", Sandbox::Remote { .. } => "remote", Sandbox::AgentSandbox { .. } => "agent-sandbox", } } pub fn listen(&self) -> Option<&str> { match self { Sandbox::Remote { listen, .. } => Some(listen), Sandbox::AgentSandbox { listen, .. } => Some(listen), Sandbox::Loopback => None, } } /// Never log this. pub fn token(&self) -> Option<&str> { match self { Sandbox::Remote { token, .. } => Some(token), Sandbox::AgentSandbox { token, .. } => Some(token), Sandbox::Loopback => None, } } pub fn image(&self) -> Option<&str> { match self { Sandbox::AgentSandbox { image, .. } => Some(image), _ => None, } } pub fn shared_workspace(&self) -> bool { match self { Sandbox::Loopback => true, Sandbox::Remote { shared_workspace, .. } => *shared_workspace, Sandbox::AgentSandbox { shared_workspace, .. } => *shared_workspace, } } pub const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"]; } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Config { pub root: PathBuf, pub repo_name: String, pub arch: String, pub signing_key_id: String, pub bind: String, pub password: String, pub base_url: String, pub build_profile: String, pub git_bin: String, pub makepkg_bin: String, pub pacman_bin: String, pub repo_add_bin: String, pub gpg_bin: String, pub build_user: String, pub sandbox: Sandbox, #[cfg(feature = "test-support")] #[serde(default, skip_serializing_if = "TestHooks::is_empty")] pub hooks: TestHooks, pub max_concurrent_builds: usize, pub lease_secs: i64, pub min_free_disk_mb: u64, pub max_transient_attempts: i64, pub dispatch_tick_secs: u64, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct TestHooks { pub path_prepend: Option, pub shim_manifest: Option, pub shim_dir: Option, pub publish_fault: Option, pub shim_fail: Option, pub shim_kill_parent: Option, pub shim_plant_link: Option, } impl TestHooks { pub fn is_empty(&self) -> bool { self.path_prepend.is_none() && self.shim_manifest.is_none() && self.shim_dir.is_none() && self.publish_fault.is_none() && self.shim_fail.is_none() && self.shim_kill_parent.is_none() && self.shim_plant_link.is_none() } } impl Default for Config { fn default() -> Self { Self { root: PathBuf::from("/var/lib/aur-build"), repo_name: "aur-build".into(), arch: "x86_64".into(), signing_key_id: String::new(), bind: "127.0.0.1:8484".into(), password: String::new(), base_url: "http://127.0.0.1:8484".into(), build_profile: "extra-x86_64".into(), git_bin: "git".into(), makepkg_bin: "makepkg".into(), pacman_bin: "pacman".into(), repo_add_bin: "repo-add".into(), gpg_bin: "gpg".into(), build_user: String::new(), sandbox: Sandbox::default(), #[cfg(feature = "test-support")] hooks: TestHooks::default(), max_concurrent_builds: 1, lease_secs: 90, min_free_disk_mb: 1024, max_transient_attempts: 3, dispatch_tick_secs: 2, } } } impl Config { pub fn sandbox_image(&self) -> String { self.sandbox .image() .unwrap_or(DEFAULT_SANDBOX_IMAGE) .to_string() } pub fn validate(&self) -> crate::error::Result<()> { let require = |field: &str, value: &str| -> crate::error::Result<()> { if value.trim().is_empty() { return Err(crate::error::Error::invalid(format!( "sandbox kind \"{}\" needs a non-empty \"{field}\"", self.sandbox.kind() ))); } Ok(()) }; match &self.sandbox { Sandbox::Loopback => {} Sandbox::Remote { listen, token, .. } => { require("listen", listen)?; require("token", token)?; } Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } => { for (field, value) in [ ("api", api), ("namespace", namespace), ("bearer", bearer), ("image", image), ("listen", listen), ("token", token), ] { require(field, value)?; } } } if self.sandbox.shared_workspace() { return Ok(()); } Err(crate::error::Error::invalid(format!( concat!( "sandbox kind \"{}\" was not told that hub and sandbox share a filesystem: ", "set \"shared_workspace\": true in the sandbox object. The build workspace is ", "not shipped to a remote sandbox — `Run` frames carry a hub-side working ", "directory — so a remote build only works where the staging directory is ", "visible at the same path on both sides. Asserting it here is what keeps a ", "remote configuration from silently building on the hub it was meant to leave." ), self.sandbox.kind() ))) } pub fn load(root: &Path) -> crate::error::Result { let dir = absolute(root)?; let p = dir.join("config.json"); if !p.exists() { return Err(crate::error::Error::not_found(format!( "no config at {}; run `aur-build init`", p.display() ))); } let s = std::fs::read_to_string(&p)?; 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) } pub fn save(&self) -> crate::error::Result<()> { std::fs::create_dir_all(&self.root)?; let mut out = self.clone(); out.root = absolute(&self.root)?; std::fs::write( self.root.join("config.json"), serde_json::to_string_pretty(&out)? + "\n", )?; Ok(()) } #[cfg_attr(not(feature = "test-support"), allow(unused_variables))] pub fn child_env_pairs(&self) -> Vec<(String, String)> { #[cfg_attr(not(feature = "test-support"), allow(unused_mut))] let mut pairs = Vec::new(); #[cfg(feature = "test-support")] { let h = &self.hooks; if let Some(dir) = &h.path_prepend { let path = std::env::var("PATH").unwrap_or_default(); pairs.push(("PATH".to_string(), format!("{}:{path}", dir.display()))); } if let Some(m) = &h.shim_manifest { pairs.push(("AUR_SHIM_MANIFEST".to_string(), m.display().to_string())); } if let Some(d) = &h.shim_dir { pairs.push(("AUR_SHIM_DIR".to_string(), d.display().to_string())); } if let Some(f) = &h.shim_fail { pairs.push(("AUR_SHIM_FAIL".to_string(), f.clone())); } if let Some(k) = &h.shim_kill_parent { pairs.push(("AUR_SHIM_KILL_PARENT".to_string(), k.clone())); } if let Some(l) = &h.shim_plant_link { pairs.push(("AUR_SHIM_PLANT_LINK".to_string(), l.clone())); } } pairs } pub fn child_env(&self, cmd: &mut std::process::Command) { for (k, v) in self.child_env_pairs() { cmd.env(k, v); } } pub fn ensure_dirs(&self) -> crate::error::Result<()> { for d in [ self.root.clone(), self.mirrors_dir(), self.vcs_cache_dir(), self.source_cache_dir(), self.staging_dir(), self.store_dir(), self.log_dir(), self.repo_dir(), ] { std::fs::create_dir_all(d)?; } std::fs::create_dir_all(self.repo_arch_dir())?; Ok(()) } pub fn db_path(&self) -> PathBuf { self.root.join("aur-build.db") } fn mirrors_dir(&self) -> PathBuf { self.root.join("mirrors") } pub fn mirror_path(&self, pkgbase: &str) -> PathBuf { self.mirrors_dir().join(format!("{pkgbase}.git")) } pub fn vcs_cache_dir(&self) -> PathBuf { self.root.join("vcs_cache") } pub fn vcs_cache_path(&self, url: &str) -> PathBuf { let h = crate::hash::short(url.as_bytes(), 16); self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h)) } pub fn source_cache_dir(&self) -> PathBuf { self.root.join("source_cache") } pub fn source_cache_path(&self, digest: &str) -> PathBuf { self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest) } pub fn staging_dir(&self) -> PathBuf { self.root.join("staging") } pub fn staging_build_dir(&self, build_id: &str) -> PathBuf { self.staging_dir().join(build_id) } pub fn store_dir(&self) -> PathBuf { self.root.join("store") } pub fn store_path(&self, digest: &str) -> PathBuf { self.store_dir().join(&digest[..2.min(digest.len())]).join(digest) } fn log_dir(&self) -> PathBuf { self.root.join("logs") } pub fn build_log_path(&self, build_id: &str) -> PathBuf { self.log_dir().join(format!("{build_id}.log")) } fn repo_dir(&self) -> PathBuf { self.root.join("repo") } pub fn repo_arch_dir(&self) -> PathBuf { self.repo_dir() .join(&self.repo_name) .join("os") .join(&self.arch) } pub fn repo_db_name(&self) -> String { format!("{}.db", self.repo_name) } } 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(), } } 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 = 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(", ") ))) } fn absolute(p: &Path) -> crate::error::Result { Ok(std::path::absolute(p)?) } fn slug(url: &str) -> String { url.chars() .map(|c| { if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' } }) .collect::() .trim_matches('-') .chars() .take(32) .collect() }