// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Legatus, the Fabrica Domi agent (docs/01_legatus.md): enroll with a one-time code, then //! long-poll the Fabrica server over mTLS for jobs, and run them only when the release is signed //! by the team. pub mod client; pub mod http; pub mod pipeline; pub mod state; pub mod target; pub mod tls; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use legatus_protocol::msg::{Capabilities, Hello, HostFacts, V, Welcome}; use legatus_protocol::{EnrollmentCode, JobGuard}; use crate::client::{ClientError, Fabrica}; use crate::pipeline::{Context, Fetch, Target}; use crate::state::{AgentFile, Enrolled, State, StateError}; use crate::tls::PinnedRoot; /// This Legatus's version. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); /// Unix seconds now. pub fn now() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) .unwrap_or(0) } /// Why the agent stopped or refused. #[derive(Debug, thiserror::Error)] pub enum AgentError { /// The code. #[error("{0}")] Code(#[from] legatus_protocol::CodeError), /// The server. #[error("{0}")] Client(#[from] ClientError), /// The state dir. #[error("{0}")] State(#[from] StateError), /// TLS. #[error("{0}")] Tls(#[from] tls::TlsError), /// The CA. #[error("{0}")] Pki(#[from] domi_pki::PkiError), /// Already enrolled. #[error("this machine is already enrolled as {0}; use --force to enroll again")] AlreadyEnrolled(String), /// The server's answer does not hold up. #[error("the server's answer cannot be trusted: {0}")] Untrusted(String), } /// This machine. pub fn host_facts() -> HostFacts { let hostname = std::env::var("HOSTNAME") .ok() .or_else(|| std::fs::read_to_string("/etc/hostname").ok()) .or_else(|| std::env::var("COMPUTERNAME").ok()) .unwrap_or_else(|| "unknown".into()); HostFacts { hostname: hostname.trim().chars().take(64).collect(), os: std::env::consts::OS.into(), arch: std::env::consts::ARCH.into(), version: VERSION.into(), } } fn chain_der(pem: &str) -> Result>, AgentError> { domi_pki::chain_der(pem).map_err(|e| AgentError::Untrusted(e.to_string())) } /// Enroll this machine with a pasted code. The key is made here and never leaves; the server /// must chain to the pinned root; what it sends back is checked before anything is saved. pub fn enroll(state: &State, code_text: &str, force: bool) -> Result { let code = EnrollmentCode::parse(code_text)?; if state.is_enrolled() && !force { let who = state .load() .map(|e| format!("{}/{}", e.file.team, e.file.agent)) .unwrap_or_else(|_| "an agent".into()); return Err(AgentError::AlreadyEnrolled(who)); } let key = domi_pki::generate_key()?; let csr = domi_pki::agent_csr(&key, "legatus")?; let resp = client::enroll(&code, &csr, host_facts())?; // The root must be the one the code pins. let roots = chain_der(&resp.root)?; let [root_der] = roots.as_slice() else { return Err(AgentError::Untrusted( "the root is not one certificate".into(), )); }; if PinnedRoot::with_der(*code.root_sha256(), root_der.clone()).is_none() { return Err(AgentError::Untrusted( "the root is not the one in the code".into(), )); } // The certificate must be an agent certificate for our own key, under that root. let chain = chain_der(&resp.chain)?; let id = domi_pki::verify_agent(&chain, root_der, now()) .map_err(|e| AgentError::Untrusted(format!("the agent certificate: {e}")))?; if id.team != resp.team || id.agent != resp.agent { return Err(AgentError::Untrusted( "the certificate names another agent".into(), )); } if domi_pki::public_key_der(&resp.chain)? != key.public_key_der() { return Err(AgentError::Untrusted( "the certificate is not for this machine's key".into(), )); } if resp.release_keys.is_empty() || resp.release_keys.len() > 8 { return Err(AgentError::Untrusted( "1 to 8 release keys are needed".into(), )); } for k in &resp.release_keys { if minisign_key_ok(k).is_none() { return Err(AgentError::Untrusted("a release key cannot be read".into())); } } let file = AgentFile { v: V, server: code.server().to_owned(), team: resp.team.clone(), agent: resp.agent.clone(), roles: resp.roles, release_keys: resp.release_keys.clone(), root_sha256: legatus_protocol::hex(code.root_sha256()), poll_seconds: resp.poll_seconds.clamp(5, 55), }; state.save_enrollment(&file, &resp.root, &resp.chain, &key.serialize_pem())?; Ok(file) } fn minisign_key_ok(k: &str) -> Option<()> { // `Ed` + 8-byte id + 32-byte key, base64. let k = k.trim(); (k.len() == 56 && k.starts_with("RW")).then_some(()) } /// An enrolled agent's connection to Fabrica. pub struct Session { state: State, enrolled: Enrolled, fabrica: Fabrica, ctx: Context, guard: JobGuard, } fn pinned(e: &Enrolled) -> Result { let mut sha = [0u8; 32]; let raw = (0..32) .map(|i| u8::from_str_radix(e.file.root_sha256.get(2 * i..2 * i + 2).unwrap_or("zz"), 16)) .collect::, _>>() .map_err(|_| AgentError::Untrusted("the pinned root".into()))?; sha.copy_from_slice(&raw); PinnedRoot::with_der(sha, e.root_der.clone()) .ok_or_else(|| AgentError::Untrusted("the pinned root".into())) } impl Session { /// Load the state and set up mTLS. pub fn open(state: State) -> Result { let enrolled = state.load()?; let cfg = tls::agent_config(pinned(&enrolled)?, &enrolled.chain_pem, &enrolled.key_pem)?; let fabrica = Fabrica::new(&enrolled.file.server, cfg)?; let ctx = Context { team: enrolled.file.team.clone(), roles: enrolled.file.roles, release_keys: enrolled.file.release_keys.clone(), downloads: state.downloads(), }; let guard = state.load_guard()?; Ok(Session { state, enrolled, fabrica, ctx, guard, }) } /// Who this agent is: `team/agent`. pub fn who(&self) -> String { format!("{}/{}", self.enrolled.file.team, self.enrolled.file.agent) } /// The current roles. pub fn roles(&self) -> legatus_protocol::Roles { self.ctx.roles } /// `hello`: say what this machine is and runs; take the roles Fabrica holds. pub fn hello(&mut self, target: &dyn Target) -> Result { let h = host_facts(); let w = self.fabrica.hello(&Hello { v: V, version: VERSION.into(), os: h.os, arch: h.arch, hostname: h.hostname, capabilities: Capabilities { deploy: target.kinds(), build: Vec::new(), }, deployed: target.deployed(), })?; if w.team != self.enrolled.file.team || w.agent != self.enrolled.file.agent { return Err(AgentError::Untrusted( "the server greets another agent".into(), )); } self.set_roles(w.roles)?; Ok(w) } fn set_roles(&mut self, roles: legatus_protocol::Roles) -> Result<(), AgentError> { if self.enrolled.file.roles != roles { self.enrolled.file.roles = roles; self.ctx.roles = roles; self.state.save_file(&self.enrolled.file)?; } Ok(()) } /// Wait for one job (long poll) and handle it. `true` when there was one. pub fn poll_once(&mut self, target: &dyn Target) -> Result { let Some(bytes) = self.fabrica.next_job(self.enrolled.file.poll_seconds)? else { return Ok(false); }; let fabrica = self.fabrica.clone(); let mut send = |r: legatus_protocol::Report| { if let Err(e) = fabrica.report(&r) { eprintln!("legatus: a report for job {} was not delivered: {e}", r.job); } }; let done = pipeline::handle( &bytes, now(), &mut self.ctx, &mut self.guard, &self.fabrica, target, &mut send, ); if done.guard_changed { self.state.save_guard(&self.guard)?; } if done.roles_changed { let roles = self.ctx.roles; self.enrolled.file.roles = roles; self.state.save_file(&self.enrolled.file)?; } Ok(true) } /// Renew the certificate when it is due (or `force`): a new key, a CSR, the new chain checked /// and stored, mTLS set up again. `true` when renewed. pub fn renew_if_due(&mut self, force: bool) -> Result { let leaf = domi_pki::inspect(&self.enrolled.chain_pem)?; if !force && !domi_pki::agent_renewal_due(leaf.not_after, now()) { return Ok(false); } let key = domi_pki::generate_key()?; let csr = domi_pki::agent_csr(&key, "legatus")?; let r = self.fabrica.renew(&csr)?; let chain = chain_der(&r.chain)?; let id = domi_pki::verify_agent(&chain, &self.enrolled.root_der, now()) .map_err(|e| AgentError::Untrusted(format!("the renewed certificate: {e}")))?; if id.team != self.enrolled.file.team || id.agent != self.enrolled.file.agent { return Err(AgentError::Untrusted( "the renewed certificate names another agent".into(), )); } if domi_pki::public_key_der(&r.chain)? != key.public_key_der() { return Err(AgentError::Untrusted( "the renewed certificate is not for the new key".into(), )); } let key_pem = key.serialize_pem(); self.state.save_identity(&r.chain, &key_pem)?; let cfg = tls::agent_config(pinned(&self.enrolled)?, &r.chain, &key_pem)?; self.fabrica = Fabrica::new(&self.enrolled.file.server, cfg)?; self.enrolled.chain_pem = r.chain; self.enrolled.key_pem = key_pem; Ok(true) } } impl Fetch for Fabrica { fn fetch( &self, job: &str, name: &str, max: u64, out: &mut dyn std::io::Write, ) -> Result { self.artifact(job, name, max, out) .map_err(|e| e.to_string()) } } /// Run until stopped: hello, then jobs; reconnect with back-off on errors. pub fn run(state: State, target: &dyn Target) -> Result<(), AgentError> { let mut backoff = Duration::from_secs(5); loop { let mut s = match Session::open(state.clone()) { Ok(s) => s, // Not enrolled or damaged state: stop; systemd shows why. Err(e @ (AgentError::State(_) | AgentError::Tls(_) | AgentError::Untrusted(_))) => { return Err(e); } Err(e) => { eprintln!("legatus: {e}"); std::thread::sleep(backoff); continue; } }; let result = (|| -> Result<(), AgentError> { let w = s.hello(target)?; eprintln!( "legatus: connected as {}; build {}, deploy {}", s.who(), if w.roles.build { "on" } else { "off" }, if w.roles.deploy { "on" } else { "off" } ); s.renew_if_due(w.renew)?; loop { s.poll_once(target)?; s.renew_if_due(false)?; } })(); if let Err(e) = result { eprintln!("legatus: {e}; trying again in {} s", backoff.as_secs()); std::thread::sleep(backoff); backoff = (backoff * 2).min(Duration::from_secs(60)); } else { backoff = Duration::from_secs(5); } } }