diff --git a/devenv.nix b/devenv.nix index b7bac77..a3ddcff 100644 --- a/devenv.nix +++ b/devenv.nix @@ -4,7 +4,8 @@ { languages.rust.enable = true; - packages = with pkgs; [ nixpkgs-fmt ]; + # `git` for the builder's tests + packages = with pkgs; [ git nixpkgs-fmt ]; scripts = { vm-test = { diff --git a/flake.nix b/flake.nix index 0b41317..0436ac4 100644 --- a/flake.nix +++ b/flake.nix @@ -29,8 +29,9 @@ nixosModules = { slop-broker = withPackage ./nix/modules/nixos/broker.nix [ "services" "slop-broker" ]; + slop-broker-builder = withPackage ./nix/modules/nixos/builder.nix [ "services" "slop-broker-builder" ]; default = { - imports = with self.nixosModules; [ slop-broker ]; + imports = with self.nixosModules; [ slop-broker slop-broker-builder ]; }; }; diff --git a/nix/modules/nixos/broker.nix b/nix/modules/nixos/broker.nix index 0b22134..3bf606b 100644 --- a/nix/modules/nixos/broker.nix +++ b/nix/modules/nixos/broker.nix @@ -2,7 +2,7 @@ # its own user, and sets up the `slop` user whose SSH keys reach it from other boxes. { lib, pkgs, config, ... }: let - inherit (builtins) any attrValues attrNames isAttrs isList length concatLists; + inherit (builtins) any head attrValues attrNames isAttrs isList length concatLists; inherit (lib) mkIf mkMerge mkOption mapAttrs mapAttrsToList filterAttrs optional optionals hasPrefix hasInfix unique concatStringsSep; mkOpt' = type: default: description: mkOption { inherit type default description; }; @@ -88,7 +88,13 @@ let ssh = "${pkgs.openssh}/bin/ssh"; key = "ssh-key"; known_hosts = "/var/lib/slop-broker/known_hosts"; - targets = mapAttrs (_: t: { inherit (t) hostname user; ssh_opts = t.sshOpts; }) cfg.ssh.targets; + targets = mapAttrs (_: t: { inherit (t) hostname user sudo; ssh_opts = t.sshOpts; }) cfg.ssh.targets; + } else null; + + deploy = if cfg.deploy.enable then { + builder = with cfg.deploy.builder; { inherit hostname user; ssh_opts = sshOpts; }; + nix = "${config.nix.package}/bin/nix"; + cache = "/var/lib/slop-broker/cache"; } else null; remote = if hasRemote then { @@ -131,10 +137,21 @@ in hostname = mkOpt' str null "Host to connect to."; user = mkOpt' str null "Remote user."; sshOpts = mkOpt' (listOf str) [ ] "Extra SSH arguments (trusted)."; + sudo = mkOpt' str "sudo -u" "How the user becomes root for deploys, followed by `root`."; }; })) { } "Named SSH targets (nodes), which `slop ssh`, the box queries and deploys address by name."; }; + deploy = { + enable = mkBoolOpt' false "Whether to build and deploy commits (`slop deploy`); needs `ssh`."; + builder = { + hostname = mkOpt' str "localhost" "Box running the builder (`services.slop-broker-builder`)."; + user = mkOpt' str "slop-broker-build" "The builder's user."; + sshOpts = mkOpt' (listOf str) [ "-p" (toString (head config.services.openssh.ports)) ] + "Extra SSH arguments for reaching the builder."; + }; + }; + homeAssistant = { enable = mkBoolOpt' false "Whether to send Companion approval notifications."; url = mkOpt' str "" "Home Assistant WebSocket endpoint, preferably wss://host/api/websocket."; @@ -151,6 +168,10 @@ in assertion = cfg.ssh.enable -> isRuntimePath cfg.ssh.keyFile; message = "slop-broker SSH needs a runtime key file."; } + { + assertion = cfg.deploy.enable -> cfg.ssh.enable; + message = "slop-broker deploys need `ssh`."; + } { assertion = missingPolicies == [ ]; message = "slop-broker requesters with an unknown policy: ${concatStringsSep ", " missingPolicies}."; diff --git a/nix/modules/nixos/builder.nix b/nix/modules/nixos/builder.nix new file mode 100644 index 0000000..1aeffe9 --- /dev/null +++ b/nix/modules/nixos/builder.nix @@ -0,0 +1,59 @@ +# The builder (`services.slop-broker-builder`): a user without keys that evaluates and builds +# commits for the broker, which reaches it over SSH with a forced command. +{ lib, pkgs, config, ... }: +let + inherit (lib) mkIf hasPrefix; + mkOpt' = type: default: description: lib.mkOption { inherit type default description; }; + mkBoolOpt' = default: description: mkOpt' lib.types.bool default description; + + cfg = config.services.slop-broker-builder; + + user = "slop-broker-build"; + home = "/var/lib/${user}"; + builderConfig = (pkgs.formats.toml { }).generate "slop-broker-builder.toml" { + inherit (cfg) repository branch; + key = cfg.keyFile; + directory = home; + path = map (p: "${p}/bin") [ pkgs.git config.nix.package pkgs.openssh pkgs.coreutils ]; + }; +in +{ + options.services.slop-broker-builder = with lib.types; { + enable = mkBoolOpt' false "Whether to build commits for `slop-broker` deploys, as `${user}`."; + package = lib.mkOption { + type = package; + default = pkgs.slop-broker; + defaultText = lib.literalExpression "pkgs.slop-broker"; + description = "slop-broker package; the flake's modules default to its own."; + }; + repository = mkOpt' str "" "Git repository to fetch commits from."; + branch = mkOpt' str "master" "Branch that approvals list commits relative to."; + keyFile = mkOpt' str "" "Runtime path to a read-only key for `repository`, readable by the builder."; + brokerKeys = mkOpt' (listOf str) [ ] "SSH public keys of brokers that may run builds."; + }; + + config = mkIf cfg.enable { + assertions = [ + { + assertion = cfg.repository != "" && hasPrefix "/" cfg.keyFile && !(hasPrefix "/nix/store/" cfg.keyFile); + message = "slop-broker builder needs a repository and a runtime key file."; + } + ]; + + # Evaluates and builds agent-written commits, so it holds nothing but a read-only Git key. + # Brokers' keys can only run one build per connection. + users = { + groups.${user} = { }; + users.${user} = { + isSystemUser = true; + group = user; + inherit home; + createHome = true; + shell = pkgs.bashInteractive; + openssh.authorizedKeys.keys = map + (k: ''restrict,command="${cfg.package}/bin/slop-broker builder --config ${builderConfig}" ${k}'') + cfg.brokerKeys; + }; + }; + }; +} diff --git a/slop-tools.md b/slop-tools.md index 08b9895..6021f2f 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -25,6 +25,7 @@ applies a policy, and asks a human to approve most requests. | `slop logs [-n 200] [--since 2h]` | A unit's journal; `--since` takes a duration or a date (`2026-01-31 12:00`) | usually none | | `slop failed ` | Failed units | usually none | | `slop ssh -- …` | Any command over SSH, as the node's configured user | asks | +| `slop deploy … [--commit ] [--boot]` | Build a pushed commit and deploy it to all the nodes at once | asks | | `slop requests` | Your pending requests and active leases | none | - Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a @@ -39,6 +40,18 @@ applies a policy, and asks a human to approve most requests. `-y`). - `slop ssh` forwards stdin once the request is approved. +### Deploying + +- Push the commit first: the broker fetches it from the Git server, not from you, and only finds commits + on a branch. `--commit` defaults to `HEAD` of your checkout (with `jj`, pass the commit). +- A target is a node (all its profiles, like `deploy .#node`) or `node.profile`, such as + `host.container-web`. Several targets deploy in parallel; for an order, deploy them one + at a time. +- The build and the copy to the nodes happen before approval, and their output streams to you, + so build errors show up without waiting for a human. Approval waits start after that. +- `--boot` makes it the boot default without switching; the box uses it after its next reboot. +- Check the result afterwards with `slop failed` and `slop status`. + ## Don't - Don't try to find, read or copy the broker's credentials, or use deploy tools or keys directly. diff --git a/src/audit.rs b/src/audit.rs index 615795e..26f878b 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -44,6 +44,11 @@ pub enum Event { /// Agent-supplied. label: Option, }, + /// What approvers are shown once preparing a request (such as building a deploy) finished. + Prepared { + id: String, + detail: String, + }, Approved { id: String, by: ApprovedBy, @@ -110,6 +115,13 @@ impl fmt::Display for Event { } Ok(()) } + Event::Prepared { id, detail } => { + write!(f, "{} ready for approval", short(id))?; + if let Some(line) = detail.lines().next() { + write!(f, "; {line}")?; + } + Ok(()) + } Event::Approved { id, by, approver } => { let by = match (by, approver) { (ApprovedBy::Policy, _) => "policy", @@ -138,7 +150,7 @@ impl Record { pub fn describe(&self) -> String { let time = self.time.replace('T', " ").trim_end_matches('Z').to_owned(); let mut text = format!("{time} {}\n", self.event); - if let Event::Request { detail, .. } = &self.event { + if let Event::Request { detail, .. } | Event::Prepared { detail, .. } = &self.event { for line in detail.lines().skip(1) { text += &format!("{:21}{line}\n", ""); } diff --git a/src/bin/slop-broker.rs b/src/bin/slop-broker.rs index 0788da9..213a467 100644 --- a/src/bin/slop-broker.rs +++ b/src/bin/slop-broker.rs @@ -26,6 +26,11 @@ enum Command { broker: Option, args: Vec, }, + /// Forced command for the builder's SSH key: builds one request read from stdin. + Builder { + #[arg(long)] + config: PathBuf, + }, /// Forced command for SSH keys: joins the session to the broker as the key's owner. Remote { #[arg(long, default_value = "/run/slop-broker/remote.sock")] @@ -57,6 +62,7 @@ async fn main() { } } Command::Remote { socket, role, name } => remote::bridge(&socket, role, name).await, + Command::Builder { config } => slop_broker::builder::worker(&config).await, } }; diff --git a/src/bin/slop.rs b/src/bin/slop.rs index cc792fb..1533134 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -13,7 +13,7 @@ use slop_broker::proto::{ Request, ServerMessage, decode, encode, transport, }; use slop_broker::remote::{self, Role, Stream}; -use slop_broker::types::{Arg, HostName, Lines, NodeName, Since, UnitName, UserName}; +use slop_broker::types::{Arg, CommitId, DeployTarget, HostName, Lines, NodeName, Since, UnitName, UserName}; /// Exit status when the broker didn't run the operation (denied, expired, invalid or failed). const NOT_RUN: i32 = 125; @@ -103,6 +103,18 @@ enum Command { #[command(flatten)] target: Target, }, + /// Build a pushed commit and deploy it to nodes, all at once, once approved. + Deploy { + /// Nodes (all their profiles, like `deploy .#node`) or node.profile. + #[arg(required = true)] + targets: Vec, + /// The commit, resolved in this checkout; it must already be pushed to the Git server the builder fetches from. + #[arg(long, default_value = "HEAD")] + commit: String, + /// Make it the boot default instead of switching to it now. + #[arg(long)] + boot: bool, + }, /// Show your pending requests and active leases. Requests, /// Print the guide for agents. @@ -119,11 +131,29 @@ fn operation(command: Command) -> Result { Operation::Query { destination: target.destination()?, query: Query::Logs { unit, lines, since } } } Command::Failed { target } => Operation::Query { destination: target.destination()?, query: Query::Failed }, + Command::Deploy { targets, commit, boot } => Operation::Deploy { targets, commit: resolve(&commit)?, boot }, Command::Requests => Operation::Requests, Command::Guide => unreachable!(), }) } +/// A full commit ID, from Git in the working directory unless it already is one. +fn resolve(revision: &str) -> Result { + if let Ok(commit) = revision.parse() { + return Ok(commit); + } + + let output = std::process::Command::new("git") + .args(["rev-parse", "--verify", "--quiet", "--end-of-options", &format!("{revision}^{{commit}}")]) + .output() + .context("running git to resolve the commit")?; + + if !output.status.success() { + bail!("{revision} isn't a commit in this checkout"); + } + parse(String::from_utf8_lossy(&output.stdout).trim()) +} + /// The working directory's name, so approvers can tell agents apart. fn default_label() -> Option { let directory = std::env::current_dir().ok()?; diff --git a/src/builder.rs b/src/builder.rs new file mode 100644 index 0000000..dd98bbb --- /dev/null +++ b/src/builder.rs @@ -0,0 +1,421 @@ +//! Builds commits for deploys. The broker runs `slop-broker builder` over SSH as a user without +//! keys (the key's forced command). It sends a [`BuildRequest`] on stdin and gets a +//! [`BuildResult`] back on stdout, each one frame like the rest of the protocol; build logs come +//! on stderr and go to the requester. +//! +//! The builder fetches the commit from the Git server itself, so the requester never supplies +//! the source, and evaluates it there: evaluation runs agent-written Nix, which is why it happens +//! here and not in the broker. +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use futures_util::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use tokio::io::AsyncReadExt; +use tokio::process::Command; +use tokio_util::codec::{FramedRead, FramedWrite}; +use tokio_util::sync::CancellationToken; + +use crate::exec::Output; +use crate::proto::{ServerMessage, codec, decode, encode}; +use crate::types::{CommitId, DeployTarget}; + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BuilderConfig { + /// Where commits are fetched from, such as `git@git.example.org:infra.git`. + pub repository: String, + /// Read-only key for the repository. + pub key: PathBuf, + /// Branch that commit lists are shown relative to. + #[serde(default = "default_branch")] + pub branch: String, + /// Writable state: the repository mirror, `known_hosts` and caches. + pub directory: PathBuf, + /// Directories with `git`, `nix` and `ssh`. + pub path: Vec, +} + +fn default_branch() -> String { + "master".into() +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BuildRequest { + pub commit: CommitId, + pub targets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BuildResult { + /// `git log` of the commits since the branch, one per line (agent-written messages). + pub log: String, + /// `git diff --stat` since the branch. + pub stat: String, + /// Every profile to activate, nodes in request order and profiles in deploy-rs's order. + pub profiles: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BuiltProfile { + pub node: String, + pub profile: String, + /// The built profile (deploy-rs's activation wrapper around the system). + pub path: String, + /// Where it's installed on the node. + pub profile_path: String, +} + +/// Store paths, checked so the broker can put them in remote commands. +pub fn is_store_path(path: &str) -> bool { + let Some(name) = path.strip_prefix("/nix/store/") else { return false }; + let b = name.as_bytes(); + b.len() > 33 + && b[..32].iter().all(|c| c.is_ascii_digit() || c.is_ascii_lowercase()) + && b[32] == b'-' + && b[33..].iter().all(|&c| c.is_ascii_alphanumeric() || b"+-._?=".contains(&c)) +} + +/// Profile paths, checked the same way; deploy-rs installs into `/nix/var/nix/profiles`. +pub fn is_profile_path(path: &str) -> bool { + let Some(rest) = path.strip_prefix("/nix/var/nix/profiles/") else { return false }; + !rest.is_empty() + && rest.split('/').all(|part| !part.is_empty() && part != "." && part != "..") + && rest.bytes().all(|c| c.is_ascii_alphanumeric() || b"/_-.".contains(&c)) +} + +impl BuildResult { + fn check(&self) -> Result<()> { + for profile in &self.profiles { + ensure!(is_store_path(&profile.path), "the builder returned an invalid path {:?}", profile.path); + ensure!(is_profile_path(&profile.profile_path), "invalid profile path {:?}", profile.profile_path); + } + Ok(()) + } +} + +// The broker's side + +/// Runs a build and returns what to deploy. Build output goes to `out` as it happens. +pub async fn build( + ssh: &crate::config::SshConfig, + deploy: &crate::config::DeployConfig, + request: &BuildRequest, + out: &Output, + cancel: &CancellationToken, +) -> Result { + let mut command = crate::ops::ssh::command_to(ssh, &deploy.builder, &["build"]); + command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true); + let mut child = command.spawn().context("starting the builder")?; + + // Stdin stays open afterwards: the builder stops when it closes. + let mut stdin = FramedWrite::new(child.stdin.take().unwrap(), codec()); + stdin.send(encode(request)?).await?; + + let mut stderr = child.stderr.take().unwrap(); + let out = out.clone(); + let logs = tokio::spawn(async move { + let mut buffer = vec![0; 64 * 1024]; + while let Ok(n @ 1..) = stderr.read(&mut buffer).await { + out.send(ServerMessage::Stderr(buffer[..n].to_vec())).await; + } + }); + + let mut stdout = FramedRead::new(child.stdout.take().unwrap(), codec()); + let (frame, status) = tokio::select! { + result = async { + let frame = stdout.next().await.transpose()?; + anyhow::Ok((frame, child.wait().await?)) + } => result?, + _ = cancel.cancelled() => bail!("requester disconnected"), + }; + drop(stdin); + let _ = tokio::time::timeout(Duration::from_secs(5), logs).await; + + ensure!(status.success(), "the build failed; its output is above"); + let result: BuildResult = decode(&frame.context("the builder sent no result")?)?; + result.check()?; + Ok(result) +} + +// The builder's side + +/// The forced command: one build per connection, one at a time. +pub async fn worker(config: &Path) -> Result<()> { + let text = std::fs::read_to_string(config).with_context(|| format!("reading {}", config.display()))?; + let config: BuilderConfig = toml::from_str(&text)?; + + let mut stdin = FramedRead::new(tokio::io::stdin(), codec()); + let request: BuildRequest = decode(&stdin.next().await.context("no request")??)?; + // Nothing else comes on stdin; it closing means the broker gave up. + let closed = async move { while let Some(Ok(_)) = stdin.next().await {} }; + + tokio::select! { + result = async { + let _lock = lock(&config.directory.join("build.lock")).await?; + run(&config, &request).await + } => { + let mut stdout = FramedWrite::new(tokio::io::stdout(), codec()); + stdout.send(encode(&result?)?).await?; + // Not a return: the runtime would wait for the blocked read of stdin, which the broker + // keeps open until this exits. + std::process::exit(0) + } + _ = closed => bail!("the broker went away"), + } +} + +/// Waits for the lock, saying so if it's held. +async fn lock(path: &Path) -> Result { + let file = std::fs::File::create(path)?; + let mut said = false; + while file.try_lock().is_err() { + if !said { + eprintln!("Waiting for another build to finish…"); + said = true; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + Ok(file) +} + +fn command(config: &BuilderConfig, program: &str) -> Command { + let path = std::env::join_paths(&config.path).unwrap_or_default(); + let mut command = Command::new(program); + command + .env_clear() + .env("PATH", path) + .env("HOME", &config.directory) + .env("XDG_CACHE_HOME", config.directory.join("cache")) + .stdin(Stdio::null()) + .kill_on_drop(true); + command +} + +/// Git in the mirror, with the repository key. Only Git gets the key: `nix` evaluates +/// agent-written code, whose fetches mustn't be able to use it. +fn git(config: &BuilderConfig, repository: &Path) -> Command { + let ssh = format!( + "ssh -F none -i {} -o IdentitiesOnly=yes -o IdentityAgent=none -o BatchMode=yes \ + -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile={}", + config.key.display(), + config.directory.join("known_hosts").display() + ); + + let mut command = command(config, "git"); + command.env("GIT_SSH_COMMAND", ssh).arg("-C").arg(repository); + command +} + +/// Runs a command for its output; its stderr goes along with the error if it fails. +async fn output(command: &mut Command) -> Result { + let output = command.stderr(Stdio::piped()).output().await?; + if !output.status.success() { + bail!("{}", String::from_utf8_lossy(&output.stderr).trim()); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) +} + +const NIX_OPTIONS: [&str; 6] = [ + "--extra-experimental-features", + "nix-command flakes", + "--option", + "accept-flake-config", + "false", + "--no-write-lock-file", +]; + +/// A deploy-rs node's profiles, as `nix eval --json` prints them. +#[derive(Deserialize)] +struct NodeProfiles { + order: Vec, + profiles: BTreeMap, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ProfileInfo { + profile_path: Option, + user: Option, +} + +/// What deploy-rs would deploy for `target`: the node's profiles in its order, or the one named. +fn select(target: &DeployTarget, node: &NodeProfiles) -> Result> { + let names: Vec<&String> = match target.profile() { + Some(profile) => { + vec![node.profiles.keys().find(|p| *p == profile).with_context(|| format!("{target}: no such profile"))?] + } + None => { + let mut names: Vec<&String> = node.order.iter().filter(|p| node.profiles.contains_key(*p)).collect(); + names.extend(node.profiles.keys().filter(|p| !node.order.contains(p))); + names + } + }; + + names + .into_iter() + .map(|name| { + let info = &node.profiles[name]; + ensure!( + info.user.as_deref().unwrap_or("root") == "root", + "{}.{name}: only profiles deployed as root are supported", + target.node() + ); + + let path = info.profile_path.clone().unwrap_or_else(|| format!("/nix/var/nix/profiles/{name}")); + ensure!(is_profile_path(&path), "{}.{name}: invalid profile path {path:?}", target.node()); + Ok((name.clone(), path)) + }) + .collect() +} + +async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result { + let commit = &request.commit; + let repository = config.directory.join("repository.git"); + if !repository.exists() { + output(command(config, "git").args(["init", "--quiet", "--bare"]).arg(&repository)).await?; + } + + eprintln!("Fetching {}…", config.repository); + output(git(config, &repository).args([ + "fetch", + "--quiet", + "--prune", + "--no-tags", + &config.repository, + "+refs/heads/*:refs/remotes/origin/*", + ])) + .await + .context("fetching")?; + if output(git(config, &repository).args(["cat-file", "-e", &format!("{commit}^{{commit}}")])).await.is_err() { + bail!("commit {commit} isn't on any branch of {}; push it first", config.repository); + } + + // What approvers see of the commits + let branch = format!("refs/remotes/origin/{}", config.branch); + let base = output(git(config, &repository).args(["merge-base", commit, &branch])).await.ok(); + let (log, stat) = match base.as_deref().map(str::trim) { + Some(base) if base != &**commit => { + let range = format!("{base}..{commit}"); + let log = + output(git(config, &repository).args(["log", "--format=%h %s", "--max-count=30", &range])).await?; + let stat = + output(git(config, &repository).args(["diff", "--stat=100", "--stat-count=40", base, commit])).await?; + (log, stat) + } + Some(_) => (format!("(on {})\n", config.branch), String::new()), + None => (format!("(not based on {})\n", config.branch), String::new()), + }; + + // Which profiles each target means + let flake = format!("git+file://{}?rev={commit}", repository.display()); + let apply = "n: { order = n.profilesOrder or [ ]; profiles = builtins.mapAttrs (_: p: \ + { profilePath = p.profilePath or null; user = p.user or n.user or null; }) n.profiles; }"; + let mut profiles = Vec::new(); + for target in &request.targets { + eprintln!("Evaluating {target}…"); + let node = output( + command(config, "nix") + .args(["eval", "--json"]) + .args(NIX_OPTIONS) + .arg(format!("{flake}#deploy.nodes.\"{}\"", target.node())) + .args(["--apply", apply]), + ) + .await + .with_context(|| format!("evaluating {}", target.node()))?; + let node: NodeProfiles = serde_json::from_str(&node)?; + + for (profile, profile_path) in select(target, &node)? { + if !profiles.iter().any(|p: &BuiltProfile| p.node == target.node() && p.profile == profile) { + profiles.push(BuiltProfile { node: target.node().into(), profile, path: String::new(), profile_path }); + } + } + } + + // Logs go to the broker as they happen; only the result is read. + eprintln!("Building…"); + let installables = + profiles.iter().map(|p| format!("{flake}#deploy.nodes.\"{}\".profiles.\"{}\".path", p.node, p.profile)); + // Not `output()`, which would capture stderr too, whatever it's set to. + let built = command(config, "nix") + .args(["build", "--no-link", "--json", "--print-build-logs"]) + .args(NIX_OPTIONS) + .args(installables) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn()? + .wait_with_output() + .await?; + ensure!(built.status.success(), "nix build failed"); + + #[derive(Deserialize)] + struct Built { + outputs: BTreeMap, + } + let built: Vec = serde_json::from_slice(&built.stdout).context("reading nix build's result")?; + ensure!( + built.len() == profiles.len(), + "nix build returned {} results for {} profiles", + built.len(), + profiles.len() + ); + for (profile, built) in profiles.iter_mut().zip(built) { + profile.path = built.outputs.get("out").context("no out output")?.clone(); + } + + let result = BuildResult { log, stat, profiles }; + result.check()?; + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checks_paths() { + assert!(is_store_path("/nix/store/0123456789abcdfghijklmnpqrsvwxyz-activatable-nixos-system-sfh")); + for bad in [ + "/nix/store/0123456789abcdfghijklmnpqrsvwxyz", + "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-a b", + "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-a;b", + "/tmp/x", + ] { + assert!(!is_store_path(bad), "{bad}"); + } + + assert!(is_profile_path("/nix/var/nix/profiles/per-container/hass/system")); + for bad in ["/nix/var/nix/profiles/../../etc", "/nix/var/nix/profiles/", "/etc/x", "/nix/var/nix/profiles/a b"] + { + assert!(!is_profile_path(bad), "{bad}"); + } + } + + #[test] + fn selects_profiles_like_deploy_rs() { + let node: NodeProfiles = serde_json::from_str( + r#"{ "order": ["system"], "profiles": { + "container-b": { "profilePath": "/nix/var/nix/profiles/per-container/b/system", "user": "root" }, + "container-a": { "profilePath": "/nix/var/nix/profiles/per-container/a/system", "user": "root" }, + "system": { "profilePath": null, "user": "root" } } }"#, + ) + .unwrap(); + + let all = select(&"shill".parse().unwrap(), &node).unwrap(); + assert_eq!(all.iter().map(|(p, _)| p.as_str()).collect::>(), ["system", "container-a", "container-b"]); + assert_eq!(all[0].1, "/nix/var/nix/profiles/system"); + assert_eq!(select(&"shill.container-b".parse().unwrap(), &node).unwrap().len(), 1); + assert!(select(&"shill.nope".parse().unwrap(), &node).is_err()); + + let user: NodeProfiles = + serde_json::from_str(r#"{ "order": [], "profiles": { "home": { "profilePath": null, "user": "dev" } } }"#) + .unwrap(); + assert!(select(&"castle".parse().unwrap(), &user).is_err()); + } +} diff --git a/src/config.rs b/src/config.rs index 5d53f8e..e93e810 100644 --- a/src/config.rs +++ b/src/config.rs @@ -39,6 +39,21 @@ pub struct Config { pub home_assistant: Option, #[serde(default)] pub remote: Option, + #[serde(default)] + pub deploy: Option, +} + +/// Deploys: a builder evaluates and builds commits, then the broker copies and activates them +/// over SSH like deploy-rs does. Needs `ssh`, whose key and options it uses. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DeployConfig { + /// Runs `slop-broker builder` as its forced command, as a user without keys. + pub builder: SshTarget, + /// `nix`, for copying closures to nodes. + pub nix: PathBuf, + /// Writable directory for `nix`'s cache. + pub cache: PathBuf, } /// Requesters and approvers on other boxes, connecting over SSH (see [`crate::remote`]). @@ -115,6 +130,13 @@ pub struct SshTarget { pub user: String, #[serde(default)] pub ssh_opts: Vec, + /// How `user` becomes root, followed by the user name (deploy-rs's `sudo`). + #[serde(default = "default_sudo")] + pub sudo: String, +} + +fn default_sudo() -> String { + "sudo -u".into() } #[derive(Debug, Clone, Deserialize)] diff --git a/src/exec.rs b/src/exec.rs index f12d3cb..4507f2e 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, bail}; use nix::errno::Errno; use nix::sys::signal::{Signal, killpg}; use nix::unistd::Pid; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt}; use tokio::process::Command; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; @@ -91,6 +91,45 @@ pub async fn run(mut command: Command, io: &mut Io, with_stdin: bool) -> Result< Ok(exit_code(status)) } +/// Runs `command` without stdin, sending each line of its output with `prefix`, so several can +/// share the requester's output. +pub async fn run_prefixed(mut command: Command, out: &Output, prefix: &str, cancel: &CancellationToken) -> Result { + command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true); + let mut child = spawn(&mut command).await?; + let pid = child.id().context("process exited immediately")? as i32; + + let lines = |reader, wrap: fn(Vec) -> ServerMessage| { + let (out, prefix) = (out.clone(), prefix.to_owned()); + tokio::spawn(async move { + let mut lines = tokio::io::BufReader::new(reader).lines(); + while let Ok(Some(line)) = lines.next_line().await { + out.send(wrap(format!("{prefix}{line}\n").into_bytes())).await; + } + }) + }; + + let stdout = + lines(Box::new(child.stdout.take().unwrap()) as Box, ServerMessage::Stdout); + let stderr = + lines(Box::new(child.stderr.take().unwrap()) as Box, ServerMessage::Stderr); + + let status = tokio::select! { + status = child.wait() => status?, + _ = cancel.cancelled() => { + terminate(pid, &mut child).await; + bail!("requester disconnected"); + } + }; + + // Lines still buffered belong before the exit status. + let _ = tokio::time::timeout(Duration::from_secs(5), async { + let _ = stdout.await; + let _ = stderr.await; + }) + .await; + Ok(exit_code(status)) +} + /// Runs `command` without the requester's stdio and returns its stdout. pub async fn capture(mut command: Command, cancel: &CancellationToken) -> Result<(i32, Vec, Vec)> { command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true); diff --git a/src/lib.rs b/src/lib.rs index 37cd1ea..86a402f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ //! approval. See `docs/design.md` and `docs/architecture.md`. pub mod approve; pub mod audit; +pub mod builder; pub mod config; pub mod exec; pub mod ha; diff --git a/src/ops/deploy.rs b/src/ops/deploy.rs new file mode 100644 index 0000000..e3acd0e --- /dev/null +++ b/src/ops/deploy.rs @@ -0,0 +1,498 @@ +//! `deploy`: build a pushed commit, show approvers what it changes on each node, then activate it +//! on all of them at once. +//! +//! Before approval nothing runs as root and no agent-written code runs on a node: the builder +//! evaluates and builds, the broker copies the closures to the nodes, and a fixed read-only +//! script compares them with what the nodes have. Activation (deploy-rs's `activate-rs`) runs +//! only once approved, in a transient unit, so it finishes even if the connection drops. +use std::collections::BTreeMap; + +use anyhow::{Context, Result, bail, ensure}; +use futures_util::future::join_all; +use serde_json::json; +use tokio::process::Command; + +use super::{Parsed, shell_quote, ssh}; +use crate::builder::{self, BuildRequest, BuildResult, BuiltProfile}; +use crate::config::{DeployConfig, SshConfig}; +use crate::exec::{self, Io, Output}; +use crate::policy::Limits; +use crate::proto::{Destination, Operation}; +use crate::server::Broker; +use crate::types::CommitId; + +const MAX_TARGETS: usize = 32; + +fn configs(broker: &Broker) -> Result<(&SshConfig, &DeployConfig)> { + let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?; + let deploy = broker.config.deploy.as_ref().context("deploys are not configured on this broker")?; + Ok((ssh, deploy)) +} + +fn mode(boot: bool) -> &'static str { + if boot { "boot" } else { "switch" } +} + +pub fn plan(broker: &Broker, operation: Operation) -> Result { + let Operation::Deploy { targets, commit, boot } = &operation else { unreachable!() }; + let (ssh, _) = configs(broker)?; + + ensure!(!targets.is_empty(), "nothing to deploy"); + ensure!(targets.len() <= MAX_TARGETS, "at most {MAX_TARGETS} targets at once"); + for (index, target) in targets.iter().enumerate() { + ensure!(ssh.targets.contains_key(target.node()), "unknown node {}", target.node()); + ensure!(!targets[..index].contains(target), "{target} is listed twice"); + } + + let mut sorted: Vec<&str> = targets.iter().map(|t| &**t).collect(); + sorted.sort(); + let names = sorted.join(", "); + + // Rules see one scope per target; the strictest answer applies. + let rule_scopes = targets + .iter() + .map(|t| { + let scope = json!({ + "node": t.node(), + "profile": t.profile().unwrap_or(""), + "mode": mode(*boot), + "commit": &**commit, + }); + scope.as_object().unwrap().clone() + }) + .collect(); + let scope = json!({ "targets": names, "mode": mode(*boot), "commit": &**commit }); + + Ok(Parsed { + op: "deploy", + scope: scope.as_object().unwrap().clone(), + rule_scopes, + summary: format!("deploy {names} ({}) at {}", mode(*boot), commit.short()), + detail: format!("Commit {commit}\n(building; the changes are shown once it's built)"), + limits: Limits::default(), + sensitive: false, + stdin: false, + builtin: false, + prepared: None, + operation, + }) +} + +/// Builds, copies and compares; fills in the approval detail. +pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { + let Operation::Deploy { targets, commit, boot } = &parsed.operation else { return Ok(()) }; + let (ssh, deploy) = configs(broker)?; + + let request = BuildRequest { commit: commit.clone(), targets: targets.clone() }; + io.out.info(format!("building {} for {}; output follows", commit.short(), parsed.summary)).await; + let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?; + + io.out.info("copying to the nodes and comparing with what they run").await; + let by_node = group(&built.profiles); + let reports = join_all(by_node.iter().map(|(node, profiles)| async move { + copy(ssh, deploy, node, profiles, &io.out, &io.cancel).await?; + + let mut sections = Vec::new(); + for profile in profiles { + let changes = inspect(ssh, node, profile, &io.cancel).await?; + sections.push(format!("{node}.{} ({}):\n{}", profile.profile, mode(*boot), changes.describe())); + } + anyhow::Ok(sections.join("\n")) + })) + .await; + + let mut detail = describe_commit(commit, &built); + for report in reports { + detail += &report?; + detail.push('\n'); + } + + parsed.detail = super::truncate(detail.trim_end(), 20_000); + parsed.prepared = Some(built); + Ok(()) +} + +pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result { + let Operation::Deploy { boot, .. } = &parsed.operation else { unreachable!() }; + let (ssh, _) = configs(broker)?; + let built = parsed.prepared.as_ref().context("nothing was built")?; + + let run = &crate::queue::new_id(); + let (out, cancel) = (&io.out, &io.cancel); + let results = join_all(group(&built.profiles).into_iter().map(|(node, profiles)| async move { + for profile in profiles { + let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, run))]; + let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote); + let prefix = format!("[{node}.{}] ", profile.profile); + + let exit = exec::run_prefixed(command, out, &prefix, cancel).await?; + if exit != 0 { + return anyhow::Ok((node, format!("{} failed (exit status {exit})", profile.profile), exit)); + } + } + anyhow::Ok((node, "done".to_owned(), 0)) + })) + .await; + + let mut status = 0; + for result in results { + let (node, outcome, exit) = result?; + io.out.info(format!("{node}: {outcome}")).await; + if status == 0 { + status = exit; + } + } + Ok(status) +} + +/// Profiles by node, nodes in request order. +fn group(profiles: &[BuiltProfile]) -> Vec<(String, Vec<&BuiltProfile>)> { + let mut groups: Vec<(String, Vec<&BuiltProfile>)> = Vec::new(); + for profile in profiles { + match groups.iter_mut().find(|(node, _)| *node == profile.node) { + Some((_, list)) => list.push(profile), + None => groups.push((profile.node.clone(), vec![profile])), + } + } + groups +} + +fn describe_commit(commit: &CommitId, built: &BuildResult) -> String { + let mut text = format!("Commit {commit}\nCommits:\n"); + for line in built.log.lines().chain(built.stat.lines()) { + text += &format!(" {line}\n"); + } + text +} + +/// Copies closures to a node like deploy-rs does, letting it substitute what caches have. Its +/// progress (one line per path) goes to the requester. +async fn copy( + ssh: &SshConfig, + deploy: &DeployConfig, + node: &str, + profiles: &[&BuiltProfile], + out: &Output, + cancel: &tokio_util::sync::CancellationToken, +) -> Result<()> { + let target = &ssh.targets[node]; + let options = copy_options(ssh, node); + ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy"); + + let ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default(); + let mut command = Command::new(&deploy.nix); + command + .env_clear() + .env("PATH", format!("{ssh_directory}:/run/current-system/sw/bin")) + .env("HOME", &deploy.cache) + .env("XDG_CACHE_HOME", &deploy.cache) + .env("NIX_SSHOPTS", options.join(" ")) + .args([ + "--extra-experimental-features", + "nix-command", + "copy", + "--no-check-sigs", + "--substitute-on-destination", + ]) + .arg("--to") + .arg(format!("ssh://{}@{}", target.user, target.hostname)) + .args(profiles.iter().map(|p| &p.path)); + + let exit = exec::run_prefixed(command, out, &format!("[{node}] "), cancel).await?; + ensure!(exit == 0, "copying to {node} failed; its output is above"); + Ok(()) +} + +/// `NIX_SSHOPTS` for `nix copy`. It adds `-oPermitLocalCommand=yes -oLocalCommand=echo started` +/// and waits for that line, but ssh keeps the first value of an option, so the broker's +/// `PermitLocalCommand=no` would leave it waiting forever. With `-F none`, nothing else can set a +/// local command anyway. +fn copy_options(ssh: &SshConfig, node: &str) -> Vec { + let mut options = ssh::options(ssh); + if let Some(index) = options.windows(2).position(|w| w == ["-o", "PermitLocalCommand=no"]) { + options.drain(index..index + 2); + } + options.extend(ssh.targets[node].ssh_opts.iter().cloned()); + options +} + +/// Compares a profile's current and new closures on the node; reads only. +const INSPECT: &str = r#"old=$1 new=$2 +if [ -e "$old" ]; then + echo @@packages + nix --extra-experimental-features nix-command store diff-closures "$old" "$new" 2>&1 | head -n 500 + echo @@boot + for f in kernel initrd; do + [ -e "$old/$f" ] && [ -e "$new/$f" ] && [ "$(readlink -f "$old/$f")" != "$(readlink -f "$new/$f")" ] && echo "$f" + done +fi +# /etc entries are links into the store, so a link's target changes with its contents. Units are +# one link to a directory of them, so that one is followed. +list() { + [ -d "$1/etc" ] && cd "$1/etc" || return 0 + find . -path ./systemd/system -prune -o -type l -printf "%p\t%l\n" -o -type f -printf "%p\t%s\n" + [ -d systemd/system ] || return 0 + units=$(find -L systemd/system/ -mindepth 1 -maxdepth 2 -type f | LC_ALL=C sort) + [ -n "$units" ] || return 0 + paste <(printf "%s\n" "$units" | sed "s|^|./|") <(printf "%s\n" "$units" | xargs -d "\n" realpath --) +} +echo @@old +[ -e "$old" ] && (list "$old") +echo @@new +(list "$new") +"#; + +async fn inspect( + ssh: &SshConfig, + node: &str, + profile: &BuiltProfile, + cancel: &tokio_util::sync::CancellationToken, +) -> Result { + let words = ["bash", "-c", INSPECT, "bash", &profile.profile_path, &profile.path]; + let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &[shell_quote(&words)]); + + let (exit, stdout, stderr) = exec::capture(command, cancel).await?; + if exit != 0 { + bail!("comparing on {node} failed: {}", String::from_utf8_lossy(&stderr).trim()); + } + Ok(Changes::parse(&String::from_utf8_lossy(&stdout))) +} + +fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, run: &str) -> Vec { + let mut words: Vec = ssh.targets[node].sudo.split_whitespace().map(Into::into).collect(); + words.push("root".into()); + + // A transient unit, so activation finishes even if this connection drops + words.extend( + [ + "/run/current-system/sw/bin/systemd-run", + "--quiet", + "--wait", + "--pipe", + "--collect", + "--service-type=exec", + "--setenv=PATH=/run/current-system/sw/bin", + ] + .map(Into::into), + ); + words.push(format!("--unit=slop-deploy-{}-{}", &run[..8], profile.profile)); + + // What deploy-rs runs, without magic rollback + words.push(format!("{}/activate-rs", profile.path)); + words.extend(["activate".into(), profile.path.clone(), "--profile-path".into(), profile.profile_path.clone()]); + words.extend(["--temp-path", "/tmp", "--confirm-timeout", "30"].map(Into::into)); + if boot { + words.push("--boot".into()); + } + words +} + +/// Drops terminal escape sequences, which `nix` can print even into a pipe. +fn strip_escapes(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c == '\x1b' { + if chars.next() == Some('[') { + for c in chars.by_ref() { + if c.is_ascii_alphabetic() { + break; + } + } + } + } else { + result.push(c); + } + } + result +} + +/// What a deploy changes on one profile. +#[derive(Debug, Default, PartialEq)] +struct Changes { + /// No current profile: everything is new. + new: bool, + packages: Vec, + /// `kernel` or `initrd`, if they changed. + boot: Vec, + units: Diff, + files: Diff, +} + +#[derive(Debug, Default, PartialEq)] +struct Diff { + changed: Vec, + added: Vec, + removed: Vec, +} + +impl Changes { + fn parse(output: &str) -> Changes { + let output = strip_escapes(output); + let mut changes = Changes { new: !output.contains("@@packages"), ..Changes::default() }; + + // Sections start with `@@name` lines; the /etc listings are `pathtarget`. + let (mut old, mut new) = (BTreeMap::new(), BTreeMap::new()); + let mut section = ""; + for line in output.lines() { + if let Some(name) = line.strip_prefix("@@") { + section = match name { + "packages" => "packages", + "boot" => "boot", + "old" => "old", + "new" => "new", + _ => "", + }; + continue; + } + match section { + "packages" if !line.trim().is_empty() => changes.packages.push(line.trim().to_owned()), + "boot" if !line.is_empty() => changes.boot.push(line.to_owned()), + "old" | "new" => { + if let Some((name, target)) = line.split_once('\t') { + let map = if section == "old" { &mut old } else { &mut new }; + map.insert(format!("/{}", name.trim_start_matches("./")), target.to_owned()); + } + } + _ => {} + } + } + + for (name, target) in &new { + match old.get(name) { + Some(previous) if previous == target => {} + Some(_) => changes.record(name, |d| &mut d.changed), + None => changes.record(name, |d| &mut d.added), + } + } + for name in old.keys().filter(|n| !new.contains_key(*n)) { + changes.record(name, |d| &mut d.removed); + } + changes + } + + /// Files under `systemd/system` count as their unit; links in `.wants` and the like only + /// repeat the unit they point to. + fn record(&mut self, name: &str, list: fn(&mut Diff) -> &mut Vec) { + match name.strip_prefix("/systemd/system/") { + Some(rest) => { + let first = rest.split('/').next().unwrap_or(rest); + if rest.contains('/') && [".wants", ".requires", ".upholds"].iter().any(|s| first.ends_with(s)) { + return; + } + + let unit = first.strip_suffix(".d").unwrap_or(first); + let units = list(&mut self.units); + if !units.iter().any(|u| u == unit) { + units.push(unit.to_owned()); + } + } + None => list(&mut self.files).push(format!("/etc{name}")), + } + } + + fn describe(&self) -> String { + fn listing(label: &str, items: &[String], limit: usize) -> String { + if items.is_empty() { + return String::new(); + } + + let mut shown = items.iter().take(limit).cloned().collect::>().join(", "); + if items.len() > limit { + shown += &format!(", … {} more", items.len() - limit); + } + format!(" {label}: {shown}\n") + } + + let mut text = String::new(); + if self.new { + text += " new profile: nothing to compare with\n"; + } else if self.packages.is_empty() { + text += " packages: no version changes\n"; + } else { + text += " packages:\n"; + for line in self.packages.iter().take(40) { + text += &format!(" {line}\n"); + } + if self.packages.len() > 40 { + text += &format!(" … {} more\n", self.packages.len() - 40); + } + } + if !self.boot.is_empty() { + text += &format!(" {} changed: takes effect after a reboot\n", self.boot.join(" and ")); + } + + text += &listing("changed units", &self.units.changed, 40); + text += &listing("added units", &self.units.added, 40); + text += &listing("removed units", &self.units.removed, 40); + text += &listing("changed files", &self.files.changed, 30); + text += &listing("added files", &self.files.added, 30); + text += &listing("removed files", &self.files.removed, 30); + if !self.new && self.units == Diff::default() && self.files == Diff::default() { + text += " no unit or /etc changes\n"; + } + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_etc_trees() { + let output = "@@packages\nhome-assistant: 2026.11.1 → 2026.11.2, +3.4 MiB\n@@boot\nkernel\n@@old\n\ + ./systemd/system/a.service\t/nix/store/x-a\n\ + ./systemd/system/b.service\t/nix/store/x-b\n\ + ./systemd/system/multi-user.target.wants/a.service\t/nix/store/x-a\n\ + ./hosts\t/nix/store/x-hosts\n\ + ./gone\t/nix/store/x-gone\n\ + @@new\n\ + ./systemd/system/a.service\t/nix/store/y-a\n\ + ./systemd/system/multi-user.target.wants/a.service\t/nix/store/y-a\n\ + ./systemd/system/c.service.d/overrides.conf\t/nix/store/y-c\n\ + ./hosts\t/nix/store/x-hosts\n\ + ./new.conf\t/nix/store/y-new\n"; + + let changes = Changes::parse(output); + assert_eq!(changes.packages, ["home-assistant: 2026.11.1 → 2026.11.2, +3.4 MiB"]); + assert_eq!(strip_escapes("source: \x1b[31;1m3.6 GiB\x1b[0m"), "source: 3.6 GiB"); + assert_eq!(changes.boot, ["kernel"]); + assert_eq!(changes.units.changed, ["a.service"]); + assert_eq!(changes.units.added, ["c.service"]); + assert_eq!(changes.units.removed, ["b.service"]); + assert_eq!(changes.files.added, ["/etc/new.conf"]); + assert_eq!(changes.files.removed, ["/etc/gone"]); + assert!(changes.files.changed.is_empty()); + + let text = changes.describe(); + assert!(text.contains("changed units: a.service\n") && text.contains("kernel changed"), "{text}"); + + let fresh = Changes::parse("@@old\n@@new\n./hosts\t/nix/store/x\n"); + assert!(fresh.new && fresh.describe().contains("new profile")); + } + + #[test] + fn copies_can_run_their_local_command() { + let options = copy_options(&ssh::tests::config(), "river"); + assert!(!options.iter().any(|o| o.starts_with("PermitLocalCommand")), "{options:?}"); + assert!(options.contains(&"IdentitiesOnly=yes".to_owned())); + assert_eq!(&options[options.len() - 2..], ["-p", "2222"]); + } + + #[test] + fn activation_runs_in_a_transient_unit() { + let mut config = ssh::tests::config(); + config.targets.get_mut("river").unwrap().sudo = "doas -u".into(); + let profile = BuiltProfile { + node: "river".into(), + profile: "system".into(), + path: "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-system".into(), + profile_path: "/nix/var/nix/profiles/system".into(), + }; + let words = activate_command(&config, "river", &profile, true, "0123456789abcdef"); + assert_eq!(&words[..3], ["doas", "-u", "root"]); + assert!(words.contains(&"--unit=slop-deploy-01234567-system".to_owned())); + assert_eq!(words.last().unwrap(), "--boot"); + } +} diff --git a/src/ops/mod.rs b/src/ops/mod.rs index a45d4bb..9a0fc45 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -8,6 +8,7 @@ use crate::policy::Limits; use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary}; use crate::server::Broker; +pub mod deploy; pub mod query; pub mod ssh; @@ -15,6 +16,9 @@ pub struct Parsed { pub op: &'static str, /// What an approval covers; also what policy rules match against. pub scope: Map, + /// If set, policy rules are checked against each of these instead, and the strictest + /// answer applies (such as one per node of a deploy). + pub rule_scopes: Vec>, pub summary: String, pub detail: String, pub limits: Limits, @@ -24,6 +28,8 @@ pub struct Parsed { pub stdin: bool, /// Needs no policy or approval. pub builtin: bool, + /// What [`prepare`] made before approval. + pub prepared: Option, pub operation: Operation, } @@ -62,6 +68,8 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { sensitive: false, stdin: true, builtin: false, + rule_scopes: Vec::new(), + prepared: None, operation, }) } @@ -80,9 +88,12 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { sensitive: false, stdin: false, builtin: false, + rule_scopes: Vec::new(), + prepared: None, operation, }) } + Operation::Deploy { .. } => deploy::plan(broker, operation), Operation::Requests => Ok(Parsed { op: "requests", scope: Map::new(), @@ -92,12 +103,27 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { sensitive: false, stdin: false, builtin: true, + rule_scopes: Vec::new(), + prepared: None, operation, }), } } +/// Work done before approval so approvers can see what a request does, such as building a +/// deploy. Runs nothing privileged. +pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { + match parsed.operation { + Operation::Deploy { .. } => deploy::prepare(broker, parsed, io).await, + _ => Ok(()), + } +} + pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut Io) -> Result { + if let Operation::Deploy { .. } = parsed.operation { + return deploy::execute(broker, &parsed, io).await.map(Into::into); + } + match parsed.operation { Operation::Ssh { destination, command } => { ssh::execute(broker, &destination, &command, io).await.map(Into::into) @@ -121,6 +147,7 @@ pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut .collect(); Ok(Outcome { exit: 0, result: Some(OpResult::Requests { pending, leases }) }) } + Operation::Deploy { .. } => unreachable!(), } } diff --git a/src/ops/ssh.rs b/src/ops/ssh.rs index 9f613ed..87101a8 100644 --- a/src/ops/ssh.rs +++ b/src/ops/ssh.rs @@ -3,7 +3,7 @@ use anyhow::{Result, bail}; use serde_json::{Map, Value, json}; use tokio::process::Command; -use crate::config::{SshConfig, credential}; +use crate::config::{SshConfig, SshTarget, credential}; use crate::exec::{self, Io}; use crate::proto::Destination; use crate::server::Broker; @@ -34,11 +34,10 @@ pub fn describe(destination: &Destination) -> String { } } -/// The `ssh` invocation; every option comes from here or trusted target config. -pub fn command>(config: &SshConfig, destination: &Destination, remote: &[S]) -> Command { - let mut command = Command::new(&config.ssh); - command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty"); - command.args(["-F", "none", "-T", "-i"]).arg(credential(&config.key)); +/// Options for every connection; they come before any from target config, so they win. +pub fn options(config: &SshConfig) -> Vec { + let mut options: Vec = vec!["-F".into(), "none".into(), "-i".into()]; + options.push(credential(&config.key).to_string_lossy().into_owned()); for option in [ "IdentitiesOnly=yes", "IdentityAgent=none", @@ -53,9 +52,18 @@ pub fn command>(config: &SshConfig, destination: &Destination, rem // Keeps notices like "Permanently added … to the list of known hosts" out of the output "LogLevel=ERROR", ] { - command.args(["-o", option]); + options.extend(["-o".into(), option.into()]); } - command.arg("-o").arg(format!("UserKnownHostsFile={}", config.known_hosts.display())); + options.extend(["-o".into(), format!("UserKnownHostsFile={}", config.known_hosts.display())]); + options +} + +/// The `ssh` invocation; every option comes from here or trusted target config. +pub fn command>(config: &SshConfig, destination: &Destination, remote: &[S]) -> Command { + let mut command = Command::new(&config.ssh); + command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty"); + command.arg("-T").args(options(config)); + match destination { Destination::Node(node) => { let target = &config.targets[&**node]; @@ -70,6 +78,16 @@ pub fn command>(config: &SshConfig, destination: &Destination, rem command } +/// The same, to a target that isn't a node (such as the builder). +pub fn command_to>(config: &SshConfig, target: &SshTarget, remote: &[S]) -> Command { + let mut command = Command::new(&config.ssh); + command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty"); + command.arg("-T").args(options(config)); + command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]); + command.args(remote.iter().map(AsRef::as_ref)); + command +} + pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result { let config = broker.config.ssh.as_ref().unwrap(); exec::run(command(config, destination, remote), io, true).await @@ -78,7 +96,6 @@ pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::config::SshTarget; use std::collections::BTreeMap; pub fn config() -> SshConfig { @@ -89,6 +106,7 @@ pub(crate) mod tests { hostname: "river.example.org".into(), user: "deploy".into(), ssh_opts: vec!["-p".into(), "2222".into()], + sudo: "doas -u".into(), }, ); SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets } diff --git a/src/policy.rs b/src/policy.rs index 673996a..a1a33ba 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -73,6 +73,17 @@ pub fn evaluate(policy: Option<&OpPolicy>, scope: &Map, limits: L Verdict { action, leases } } +/// The strictest of several verdicts: the highest action, and only leases all of them allow. +pub fn combine(verdicts: impl IntoIterator) -> Verdict { + let mut verdicts = verdicts.into_iter(); + let Some(mut combined) = verdicts.next() else { return Verdict { action: Action::Deny, leases: vec![] } }; + for verdict in verdicts { + combined.action = combined.action.max(verdict.action); + combined.leases.retain(|l| verdict.leases.contains(l)); + } + combined +} + fn matches(patterns: &BTreeMap, scope: &Map) -> bool { patterns.iter().all(|(field, pattern)| { let value = match scope.get(field) { @@ -116,6 +127,15 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn combining_takes_the_strictest() { + let verdict = |action, leases: &[u64]| Verdict { action, leases: leases.to_vec() }; + let combined = combine([verdict(Action::Auto, &[300, 3600]), verdict(Action::Ask, &[300])]); + assert_eq!(combined, verdict(Action::Ask, &[300])); + assert_eq!(combine([verdict(Action::Ask, &[]), verdict(Action::Deny, &[])]).action, Action::Deny); + assert_eq!(combine([]).action, Action::Deny); + } + fn scope(value: Value) -> Map { value.as_object().unwrap().clone() } diff --git a/src/proto.rs b/src/proto.rs index 37b856e..0660acc 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -15,7 +15,7 @@ use tokio_util::codec::{Framed, LengthDelimitedCodec}; use crate::audit::Record; use crate::queue::{Decision, PendingInfo}; -use crate::types::{Arg, HostName, Lines, NodeName, Since, UnitName, UserName}; +use crate::types::{Arg, CommitId, DeployTarget, HostName, Lines, NodeName, Since, UnitName, UserName}; /// Bumped on any incompatible change; the broker refuses other versions. pub const PROTOCOL_VERSION: u32 = 1; @@ -50,6 +50,13 @@ pub enum Operation { Query { destination: Destination, query: Query }, /// This requester's pending requests and leases. Requests, + /// Builds a pushed commit and, once approved, activates it on deploy nodes, all at once. + Deploy { + targets: Vec, + commit: CommitId, + /// Make it the boot default without switching to it. + boot: bool, + }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -171,8 +178,12 @@ pub enum ApproveResponse { pub type Transport = Framed; +pub fn codec() -> LengthDelimitedCodec { + LengthDelimitedCodec::builder().max_frame_length(MAX_MESSAGE).new_codec() +} + pub fn transport(stream: S) -> Transport { - Framed::new(stream, LengthDelimitedCodec::builder().max_frame_length(MAX_MESSAGE).new_codec()) + Framed::new(stream, codec()) } pub fn encode(message: &T) -> Result { diff --git a/src/server.rs b/src/server.rs index 0d4bffe..3b3e8ea 100644 --- a/src/server.rs +++ b/src/server.rs @@ -169,7 +169,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io let id = new_id(); let label = request.label.as_deref().map(|l| ops::truncate(l.trim(), 200)).filter(|l| !l.is_empty()); - let parsed = match ops::plan(broker, request.operation) { + let mut parsed = match ops::plan(broker, request.operation) { Ok(parsed) => parsed, Err(error) => { let error = format!("{error:#}"); @@ -179,8 +179,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io }; // Built-in operations only read the broker's own state, so they aren't logged. + let builtin = parsed.builtin; let log = |event| { - if !parsed.builtin { + if !builtin { broker.audit.log(event) } }; @@ -194,6 +195,37 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io label: label.clone(), }); + // Some operations do work first, so approvers can see what they'll change; not if policy + // would refuse anyway. + if parsed.op == "deploy" { + let refused = match verdict(broker, requester, &parsed) { + Ok(verdict) if verdict.action == Action::Deny => Some(denied("denied by policy")), + Ok(_) => None, + Err(message) => Some(message), + }; + + if let Some(message) = refused { + let reason = match &message { + ServerMessage::Denied(reason) => reason.clone(), + other => format!("{other:?}"), + }; + log(Event::Denied { id, reason }); + return Some(message); + } + + if let Err(error) = ops::prepare(broker, &mut parsed, io).await { + if io.cancel.is_cancelled() { + log(Event::Disconnected { id }); + return None; + } + let error = format!("{error:#}"); + log(Event::Failed { id, error: error.clone() }); + return Some(ServerMessage::Error(error)); + } + + log(Event::Prepared { id: id.clone(), detail: parsed.detail.clone() }); + } + let (approved_by, approver) = match authorize(broker, &id, requester, &parsed, label, io).await { Ok(Some(approval)) => approval, Ok(None) => { @@ -242,6 +274,16 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io } } +/// What policy says about a request. +fn verdict(broker: &Broker, requester: &str, parsed: &ops::Parsed) -> Result { + let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?; + let op = settings.ops.get(parsed.op); + if parsed.rule_scopes.is_empty() { + return Ok(policy::evaluate(op, &parsed.scope, parsed.limits)); + } + Ok(policy::combine(parsed.rule_scopes.iter().map(|scope| policy::evaluate(op, scope, parsed.limits)))) +} + /// Applies policy and waits for an approver if needed, returning who approved it (and the /// approver's name). `Ok(None)` means the requester left. async fn authorize( @@ -257,7 +299,7 @@ async fn authorize( } let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?; - let verdict = policy::evaluate(settings.ops.get(parsed.op), &parsed.scope, parsed.limits); + let verdict = verdict(broker, requester, parsed)?; match verdict.action { Action::Deny => Err(denied("denied by policy")), Action::Auto => { diff --git a/src/types.rs b/src/types.rs index fecf471..1ef59ee 100644 --- a/src/types.rs +++ b/src/types.rs @@ -108,6 +108,48 @@ validated_string!( } ); +validated_string!( + /// A full Git commit ID, SHA-1 or SHA-256, in lowercase hex. + CommitId, + "commit ID (use the full hash)", + |s| matches!(s.len(), 40 | 64) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +); + +impl CommitId { + pub fn short(&self) -> &str { + &self.0[..12] + } +} + +validated_string!( + /// What to deploy: a node (all its profiles, as `deploy .#node` does) or `node.profile`. + DeployTarget, + "deploy target (use node or node.profile)", + |s| { + let name = |p: &str| { + let b = p.as_bytes(); + !b.is_empty() + && b.len() <= 128 + && b[0].is_ascii_alphanumeric() + && b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_-".contains(&c)) + }; + match s.split_once('.') { + Some((node, profile)) => name(node) && name(profile), + None => name(s), + } + } +); + +impl DeployTarget { + pub fn node(&self) -> &str { + self.0.split_once('.').map_or(&self.0, |(node, _)| node) + } + + pub fn profile(&self) -> Option<&str> { + self.0.split_once('.').map(|(_, profile)| profile) + } +} + validated_string!( /// One word of a command; anything but NUL. Arg, @@ -177,6 +219,21 @@ impl From for u32 { mod tests { use super::*; + #[test] + fn commits_and_deploy_targets() { + assert!("0123456789abcdef0123456789abcdef01234567".parse::().is_ok()); + for bad in ["HEAD", "0123456", "0123456789ABCDEF0123456789abcdef01234567"] { + assert!(bad.parse::().is_err(), "{bad}"); + } + let target: DeployTarget = "shill.container-middleman".parse().unwrap(); + assert_eq!((target.node(), target.profile()), ("shill", Some("container-middleman"))); + let target: DeployTarget = "sfh".parse().unwrap(); + assert_eq!((target.node(), target.profile()), ("sfh", None)); + for bad in ["a.b.c", ".a", "a.", "-a", "a b", "a.\"$x\""] { + assert!(bad.parse::().is_err(), "{bad}"); + } + } + #[test] fn names() { assert!("river".parse::().is_ok());