From eeaf22a7b5ff8a371c9c4f08304ed396ffc8bf07 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 22 Nov 2026 21:55:37 +0000 Subject: [PATCH] ops: Add builds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `slop build …` builds flake attributes of a pushed commit on the builder and, once approved, copies them to a binary cache's store and roots them there. `services.slop-broker-cache` gives the cache store owner's key a forced command that only allows the store protocol and GC roots, and expires the roots. Co-Authored-By: Claude Opus 5.5 --- flake.nix | 3 +- nix/modules/nixos/broker.nix | 19 +++ nix/modules/nixos/cache.nix | 90 ++++++++++++++ slop-tools.md | 11 ++ src/bin/slop.rs | 14 ++- src/builder.rs | 45 +++++-- src/config.rs | 16 +++ src/ops/build.rs | 227 +++++++++++++++++++++++++++++++++++ src/ops/deploy.rs | 12 +- src/ops/mod.rs | 11 +- src/ops/ssh.rs | 7 +- src/proto.rs | 5 +- src/server.rs | 2 +- src/types.rs | 24 ++++ tests/broker.rs | 13 ++ 15 files changed, 477 insertions(+), 22 deletions(-) create mode 100644 nix/modules/nixos/cache.nix create mode 100644 src/ops/build.rs diff --git a/flake.nix b/flake.nix index 0436ac4..28241e2 100644 --- a/flake.nix +++ b/flake.nix @@ -30,8 +30,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" ]; + slop-broker-cache = ./nix/modules/nixos/cache.nix; default = { - imports = with self.nixosModules; [ slop-broker slop-broker-builder ]; + imports = with self.nixosModules; [ slop-broker slop-broker-builder slop-broker-cache ]; }; }; diff --git a/nix/modules/nixos/broker.nix b/nix/modules/nixos/broker.nix index 3bf606b..c2bff49 100644 --- a/nix/modules/nixos/broker.nix +++ b/nix/modules/nixos/broker.nix @@ -97,6 +97,12 @@ let cache = "/var/lib/slop-broker/cache"; } else null; + cache = if cfg.cache.enable then { + inherit (cfg.cache) hostname user; + ssh_opts = cfg.cache.sshOpts; + key = "cache-key"; + } else null; + remote = if hasRemote then { socket = "/run/slop-broker/remote.sock"; user = remoteUser; @@ -152,6 +158,14 @@ in }; }; + cache = { + enable = mkBoolOpt' false "Whether to build attributes and push them to the binary cache (`slop build`); needs `deploy`."; + hostname = mkOpt' str null "Box holding the cache's store (`services.slop-broker-cache`)."; + user = mkOpt' str null "The store's owner, whose key runs the cache's forced command."; + sshOpts = mkOpt' (listOf str) [ ] "Extra SSH arguments for reaching the cache."; + keyFile = mkOpt' str "" "Runtime path to the cache's SSH private key; never a Nix store path."; + }; + homeAssistant = { enable = mkBoolOpt' false "Whether to send Companion approval notifications."; url = mkOpt' str "" "Home Assistant WebSocket endpoint, preferably wss://host/api/websocket."; @@ -172,6 +186,10 @@ in assertion = cfg.deploy.enable -> cfg.ssh.enable; message = "slop-broker deploys need `ssh`."; } + { + assertion = cfg.cache.enable -> (cfg.deploy.enable && isRuntimePath cfg.cache.keyFile); + message = "slop-broker builds need `deploy` and a runtime cache key file."; + } { assertion = missingPolicies == [ ]; message = "slop-broker requesters with an unknown policy: ${concatStringsSep ", " missingPolicies}."; @@ -221,6 +239,7 @@ in ExecStart = "${cfg.package}/bin/slop-broker serve --config ${brokerConfig}"; LoadCredential = optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++ + optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++ optional ha.enable "ha-token:${ha.tokenFile}"; User = "slop-broker"; diff --git a/nix/modules/nixos/cache.nix b/nix/modules/nixos/cache.nix new file mode 100644 index 0000000..2de8d31 --- /dev/null +++ b/nix/modules/nixos/cache.nix @@ -0,0 +1,90 @@ +# The binary cache side (`services.slop-broker-cache`): a forced command on the cache store owner's +# key that allows only the store protocol and GC roots, and a timer expiring those roots. +{ 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-cache; + roots = "${cfg.store}/nix/var/nix/gcroots/slop-broker"; + + # Allows the store protocol (what `nix copy --to ssh-ng://` runs) and adding GC roots, nothing else + forcedCommand = pkgs.writeShellScript "slop-broker-cache" '' + set -euo pipefail + export HOME=${cfg.home} + store=${cfg.store} + roots=${roots} + + read -ra words <<< "''${SSH_ORIGINAL_COMMAND-}" + case "''${words[0]-}" in + nix-daemon) + if [ "$SSH_ORIGINAL_COMMAND" != "nix-daemon --stdio" ]; then + echo "only nix-daemon --stdio is allowed" >&2 + exit 1 + fi + exec ${config.nix.package}/bin/nix-daemon --stdio --store "$store" + ;; + root) + mkdir -p "$roots" + for path in "''${words[@]:1}"; do + if ! [[ $path =~ ^/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._?=-]+$ ]]; then + echo "invalid store path: $path" >&2 + exit 1 + fi + # Replacing a root renews it + ln -sfn "$path" "$roots/''${path#/nix/store/}" + done + ;; + *) + echo "allowed commands: nix-daemon --stdio, root ..." >&2 + exit 1 + ;; + esac + ''; +in +{ + options.services.slop-broker-cache = with lib.types; { + enable = mkBoolOpt' false "Whether to let `slop-broker` push builds into a binary cache's store."; + user = mkOpt' str null "Owner of the store; brokers log in as this user."; + store = mkOpt' str null "Root of the store the cache serves."; + home = mkOpt' str null "`HOME` for the store's commands; a directory `user` can write to."; + keepDays = mkOpt' ints.positive 14 "Days a pushed path stays rooted after its last push."; + brokerKeys = mkOpt' (listOf str) [ ] "SSH public keys of brokers that may push."; + }; + + config = mkIf cfg.enable { + assertions = [ + { + assertion = hasPrefix "/" cfg.store && hasPrefix "/" cfg.home; + message = "slop-broker cache needs absolute store and home paths."; + } + ]; + + users.users.${cfg.user}.openssh.authorizedKeys.keys = + map (k: ''restrict,command="${forcedCommand}" ${k}'') cfg.brokerKeys; + + # Expired roots go daily; the store's own garbage collection then takes their paths + systemd = { + services.slop-broker-cache-expire = { + description = "Expire slop-broker's GC roots in the binary cache"; + serviceConfig = { + Type = "oneshot"; + User = cfg.user; + }; + script = '' + if [ -d ${roots} ]; then + find ${roots} -type l -mtime +${toString cfg.keepDays} -delete + fi + ''; + }; + timers.slop-broker-cache-expire = { + wantedBy = [ "timers.target" ]; + timerConfig = { + OnCalendar = "daily"; + Persistent = true; + }; + }; + }; + }; +} diff --git a/slop-tools.md b/slop-tools.md index 6021f2f..5293a2d 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -26,6 +26,7 @@ applies a policy, and asks a human to approve most requests. | `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 build … [--commit ]` | Build flake attributes of a pushed commit and push them to the binary cache | 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 @@ -52,6 +53,16 @@ applies a policy, and asks a human to approve most requests. - `--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`. +### Building into the binary cache + +- `slop build` builds on the broker's box from a pushed commit, like `slop deploy`, and pushes the + outputs to the binary cache every box uses. Use it when boxes or other agents should be able to + substitute something instead of building it, not just to check that something builds: for that, + build locally. +- Attributes are dotted flake output paths, such as `packages.x86_64-linux.hello` or + `nixosConfigurations.host.config.system.build.toplevel`; names containing dots can't be built. +- Once pushed, it prints the output paths, one per line. + ## 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/bin/slop.rs b/src/bin/slop.rs index 1533134..837860c 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -13,7 +13,9 @@ use slop_broker::proto::{ Request, ServerMessage, decode, encode, transport, }; use slop_broker::remote::{self, Role, Stream}; -use slop_broker::types::{Arg, CommitId, DeployTarget, HostName, Lines, NodeName, Since, UnitName, UserName}; +use slop_broker::types::{ + Arg, CommitId, DeployTarget, FlakeAttr, 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; @@ -115,6 +117,15 @@ enum Command { #[arg(long)] boot: bool, }, + /// Build flake attributes of a pushed commit and, once approved, push them to the binary cache. + Build { + /// Attribute paths, such as packages.x86_64-linux.hello. + #[arg(required = true)] + attrs: 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, + }, /// Show your pending requests and active leases. Requests, /// Print the guide for agents. @@ -132,6 +143,7 @@ fn operation(command: Command) -> Result { } Command::Failed { target } => Operation::Query { destination: target.destination()?, query: Query::Failed }, Command::Deploy { targets, commit, boot } => Operation::Deploy { targets, commit: resolve(&commit)?, boot }, + Command::Build { attrs, commit } => Operation::Build { attrs, commit: resolve(&commit)? }, Command::Requests => Operation::Requests, Command::Guide => unreachable!(), }) diff --git a/src/builder.rs b/src/builder.rs index dd98bbb..434b4bb 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1,4 +1,4 @@ -//! Builds commits for deploys. The broker runs `slop-broker builder` over SSH as a user without +//! Builds commits for deploys and `slop build`. 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. @@ -21,7 +21,7 @@ use tokio_util::sync::CancellationToken; use crate::exec::Output; use crate::proto::{ServerMessage, codec, decode, encode}; -use crate::types::{CommitId, DeployTarget}; +use crate::types::{CommitId, DeployTarget, FlakeAttr}; #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] @@ -47,7 +47,10 @@ fn default_branch() -> String { #[serde(deny_unknown_fields)] pub struct BuildRequest { pub commit: CommitId, + /// Deploy targets whose profiles to build. pub targets: Vec, + /// Flake attributes to build. + pub attrs: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -59,6 +62,15 @@ pub struct BuildResult { pub stat: String, /// Every profile to activate, nodes in request order and profiles in deploy-rs's order. pub profiles: Vec, + /// The output paths of each attribute, in request order. + pub outputs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BuiltAttr { + pub attr: FlakeAttr, + pub paths: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -96,6 +108,9 @@ impl BuildResult { 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); } + for path in self.outputs.iter().flat_map(|o| &o.paths) { + ensure!(is_store_path(path), "the builder returned an invalid path {path:?}"); + } Ok(()) } } @@ -340,13 +355,16 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result = profiles + .iter() + .map(|p| format!("{flake}#deploy.nodes.\"{}\".profiles.\"{}\".path", p.node, p.profile)) + .chain(request.attrs.iter().map(|attr| format!("{flake}#{attr}"))) + .collect(); // 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) + .args(&installables) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .spawn()? @@ -360,16 +378,23 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result = 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() == installables.len(), + "nix build returned {} results for {} installables", built.len(), - profiles.len() + installables.len() ); - for (profile, built) in profiles.iter_mut().zip(built) { + let (built_profiles, built_attrs) = built.split_at(profiles.len()); + for (profile, built) in profiles.iter_mut().zip(built_profiles) { profile.path = built.outputs.get("out").context("no out output")?.clone(); } + let outputs = request + .attrs + .iter() + .zip(built_attrs) + .map(|(attr, built)| BuiltAttr { attr: attr.clone(), paths: built.outputs.values().cloned().collect() }) + .collect(); - let result = BuildResult { log, stat, profiles }; + let result = BuildResult { log, stat, profiles, outputs }; result.check()?; Ok(result) } diff --git a/src/config.rs b/src/config.rs index e93e810..ea9fe48 100644 --- a/src/config.rs +++ b/src/config.rs @@ -41,6 +41,8 @@ pub struct Config { pub remote: Option, #[serde(default)] pub deploy: Option, + #[serde(default)] + pub cache: Option, } /// Deploys: a builder evaluates and builds commits, then the broker copies and activates them @@ -56,6 +58,20 @@ pub struct DeployConfig { pub cache: PathBuf, } +/// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose +/// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose +/// builder it uses. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CacheConfig { + pub hostname: String, + pub user: String, + #[serde(default)] + pub ssh_opts: Vec, + /// Private key; relative paths are resolved in `$CREDENTIALS_DIRECTORY`. + pub key: PathBuf, +} + /// Requesters and approvers on other boxes, connecting over SSH (see [`crate::remote`]). #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/src/ops/build.rs b/src/ops/build.rs new file mode 100644 index 0000000..9a9b222 --- /dev/null +++ b/src/ops/build.rs @@ -0,0 +1,227 @@ +//! `build`: build flake attributes of a pushed commit and, once approved, push them to the binary +//! cache. +//! +//! The builder evaluates and builds, as it does for deploys, so paths only reach the cache from +//! this box's own store. Everything in the cache is signed and trusted by every box, which is why +//! agents can't upload paths they built themselves. +use std::path::Path; + +use anyhow::{Context, Result, bail, ensure}; +use serde_json::json; +use tokio::process::Command; +use tokio_util::sync::CancellationToken; + +use super::deploy::{describe_commit, nix_ssh_options}; +use super::{Parsed, shell_quote, ssh}; +use crate::builder::{self, BuildRequest}; +use crate::config::{CacheConfig, DeployConfig, SshConfig}; +use crate::exec::{self, Io}; +use crate::policy::Limits; +use crate::proto::{Operation, ServerMessage}; +use crate::server::Broker; + +const MAX_ATTRS: usize = 32; + +fn configs(broker: &Broker) -> Result<(&SshConfig, &DeployConfig, &CacheConfig)> { + let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?; + let deploy = broker.config.deploy.as_ref().context("the builder is not configured on this broker")?; + let cache = broker.config.cache.as_ref().context("the binary cache is not configured on this broker")?; + Ok((ssh, deploy, cache)) +} + +pub fn plan(broker: &Broker, operation: Operation) -> Result { + let Operation::Build { attrs, commit } = &operation else { unreachable!() }; + configs(broker)?; + + ensure!(!attrs.is_empty(), "nothing to build"); + ensure!(attrs.len() <= MAX_ATTRS, "at most {MAX_ATTRS} attributes at once"); + for (index, attr) in attrs.iter().enumerate() { + ensure!(!attrs[..index].contains(attr), "{attr} is listed twice"); + } + + let mut sorted: Vec<&str> = attrs.iter().map(|a| &**a).collect(); + sorted.sort(); + let names = sorted.join(", "); + + // Rules see one scope per attribute; the strictest answer applies. + let rule_scopes = + attrs.iter().map(|a| json!({ "attr": &**a, "commit": &**commit }).as_object().unwrap().clone()).collect(); + let scope = json!({ "attrs": names, "commit": &**commit }); + + Ok(Parsed { + op: "build", + scope: scope.as_object().unwrap().clone(), + rule_scopes, + summary: format!("build {names} at {}", commit.short()), + detail: format!("Commit {commit}\n(building; the outputs are shown once it's built)"), + limits: Limits::default(), + sensitive: false, + stdin: false, + builtin: false, + prepared: None, + operation, + }) +} + +/// Builds; fills in the approval detail with the outputs and their closure sizes. +pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { + let Operation::Build { attrs, commit } = &parsed.operation else { return Ok(()) }; + let (ssh, deploy, _) = configs(broker)?; + + let request = BuildRequest { commit: commit.clone(), targets: Vec::new(), attrs: attrs.clone() }; + io.out.info(format!("{}; output follows", parsed.summary)).await; + let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?; + + let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect(); + let sizes = closure_sizes(deploy, &paths, &io.cancel).await?; + + let mut detail = describe_commit(commit, &built); + detail += "Outputs (closure sizes):\n"; + for output in &built.outputs { + detail += &format!(" {}:\n", output.attr); + for path in &output.paths { + let size = sizes.iter().find(|(p, _)| p == path).map_or("?", |(_, s)| s.as_str()); + detail += &format!(" {path} ({size})\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 (ssh, deploy, cache) = configs(broker)?; + let built = parsed.prepared.as_ref().context("nothing was built")?; + let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect(); + + // Roots first, so the cache's garbage collection can't take the paths as they arrive. + io.out.info("adding GC roots in the binary cache").await; + let remote = [shell_quote(&[&["root"], &paths[..]].concat())]; + let exit = exec::run_prefixed(cache_command(ssh, cache, &remote), &io.out, "[cache] ", &io.cancel).await?; + if exit != 0 { + io.out.info(format!("adding GC roots failed (exit status {exit}); nothing was pushed")).await; + return Ok(exit); + } + + io.out.info("pushing to the binary cache").await; + let exit = exec::run_prefixed(copy_command(ssh, deploy, cache, &paths)?, &io.out, "[cache] ", &io.cancel).await?; + if exit != 0 { + io.out.info(format!("pushing failed (exit status {exit})")).await; + return Ok(exit); + } + + // The paths, for scripts + let listing: String = paths.iter().map(|p| format!("{p}\n")).collect(); + io.out.send(ServerMessage::Stdout(listing.into_bytes())).await; + Ok(0) +} + +/// `ssh` to the cache with its own key; the forced command there reads the remote command. +fn cache_command>(ssh: &SshConfig, cache: &CacheConfig, remote: &[S]) -> Command { + let mut command = Command::new(&ssh.ssh); + command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty"); + command.arg("-T").args(ssh::options_with_key(ssh, &cache.key)); + command.args(&cache.ssh_opts).args(["-l", &cache.user, "--", &cache.hostname]); + command.args(remote.iter().map(AsRef::as_ref)); + command +} + +/// `nix copy` to the cache's store over `ssh-ng`, which runs `nix-daemon --stdio` there. +fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, paths: &[&str]) -> Result { + let options = nix_ssh_options(ssh::options_with_key(ssh, &cache.key), &cache.ssh_opts); + ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy"); + + let mut command = nix(deploy, ssh.ssh.parent()); + command + .env("NIX_SSHOPTS", options.join(" ")) + .args(["--extra-experimental-features", "nix-command", "copy", "--no-check-sigs"]) + .arg("--to") + .arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname)) + .args(paths); + Ok(command) +} + +fn nix(deploy: &DeployConfig, ssh_directory: Option<&Path>) -> Command { + let ssh_directory = ssh_directory.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); + command +} + +/// Each path's closure size, human-readable, from the local store. +async fn closure_sizes( + deploy: &DeployConfig, + paths: &[&str], + cancel: &CancellationToken, +) -> Result> { + let mut command = nix(deploy, None); + command.args(["--extra-experimental-features", "nix-command", "path-info", "--closure-size", "--human-readable"]); + command.args(paths); + + let (exit, stdout, stderr) = exec::capture(command, cancel).await?; + if exit != 0 { + bail!("measuring the outputs failed: {}", String::from_utf8_lossy(&stderr).trim()); + } + Ok(parse_sizes(&String::from_utf8_lossy(&stdout))) +} + +/// `nix path-info --closure-size --human-readable` prints a path, then its size. +fn parse_sizes(output: &str) -> Vec<(String, String)> { + output + .lines() + .filter_map(|line| { + let (path, size) = line.split_once(char::is_whitespace)?; + Some((path.to_owned(), size.trim().to_owned())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cache() -> CacheConfig { + CacheConfig { + hostname: "object.example".into(), + user: "harmonia".into(), + ssh_opts: vec!["-p".into(), "2222".into()], + key: "/cache-key".into(), + } + } + + fn args(command: &Command) -> Vec { + command.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect() + } + + #[test] + fn uses_the_cache_key() { + let ssh = ssh::tests::config(); + let deploy = + DeployConfig { builder: ssh.targets["river"].clone(), nix: "/bin/nix".into(), cache: "/var/cache".into() }; + let paths = ["/nix/store/0123456789abcdfghijklmnpqrsvwxyz-hello"]; + + let root = args(&cache_command(&ssh, &cache(), &[shell_quote(&[&["root"], &paths[..]].concat())])); + assert!(root.contains(&"/cache-key".to_owned()) && !root.contains(&"/key".to_owned()), "{root:?}"); + let expected = ["-p", "2222", "-l", "harmonia", "--", "object.example", &format!("root {}", paths[0])]; + assert_eq!(&root[root.len() - 7..], expected); + + let copy = copy_command(&ssh, &deploy, &cache(), &paths).unwrap(); + let options = copy.as_std().get_envs().find(|(k, _)| *k == "NIX_SSHOPTS").unwrap().1.unwrap(); + let options = options.to_string_lossy(); + assert!(options.contains("-i /cache-key") && options.ends_with("-p 2222"), "{options}"); + assert!(!options.contains("PermitLocalCommand=no"), "{options}"); + assert!(args(©).contains(&"ssh-ng://harmonia@object.example".to_owned())); + } + + #[test] + fn reads_closure_sizes() { + let sizes = parse_sizes("/nix/store/aaa-hello\t 12.3 MiB\n/nix/store/bbb-x 1.0 KiB\n"); + assert_eq!(sizes[0], ("/nix/store/aaa-hello".into(), "12.3 MiB".into())); + assert_eq!(sizes[1].1, "1.0 KiB"); + } +} diff --git a/src/ops/deploy.rs b/src/ops/deploy.rs index e3acd0e..90815af 100644 --- a/src/ops/deploy.rs +++ b/src/ops/deploy.rs @@ -83,7 +83,7 @@ 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() }; + let request = BuildRequest { commit: commit.clone(), targets: targets.clone(), attrs: Vec::new() }; 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?; @@ -157,7 +157,7 @@ fn group(profiles: &[BuiltProfile]) -> Vec<(String, Vec<&BuiltProfile>)> { groups } -fn describe_commit(commit: &CommitId, built: &BuildResult) -> String { +pub(super) 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"); @@ -208,11 +208,15 @@ async fn copy( /// `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); + nix_ssh_options(ssh::options(ssh), &ssh.targets[node].ssh_opts) +} + +/// The broker's SSH options, made usable by `nix copy` as described above, then `extra`. +pub(super) fn nix_ssh_options(mut options: Vec, extra: &[String]) -> Vec { 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.extend(extra.iter().cloned()); options } diff --git a/src/ops/mod.rs b/src/ops/mod.rs index 9a0fc45..cd3db9c 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 build; pub mod deploy; pub mod query; pub mod ssh; @@ -94,6 +95,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { }) } Operation::Deploy { .. } => deploy::plan(broker, operation), + Operation::Build { .. } => build::plan(broker, operation), Operation::Requests => Ok(Parsed { op: "requests", scope: Map::new(), @@ -115,13 +117,16 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { match parsed.operation { Operation::Deploy { .. } => deploy::prepare(broker, parsed, io).await, + Operation::Build { .. } => build::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::Deploy { .. } => return deploy::execute(broker, &parsed, io).await.map(Into::into), + Operation::Build { .. } => return build::execute(broker, &parsed, io).await.map(Into::into), + _ => {} } match parsed.operation { @@ -147,7 +152,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!(), + Operation::Deploy { .. } | Operation::Build { .. } => unreachable!(), } } diff --git a/src/ops/ssh.rs b/src/ops/ssh.rs index 87101a8..a6d5fc5 100644 --- a/src/ops/ssh.rs +++ b/src/ops/ssh.rs @@ -36,8 +36,13 @@ pub fn describe(destination: &Destination) -> String { /// Options for every connection; they come before any from target config, so they win. pub fn options(config: &SshConfig) -> Vec { + options_with_key(config, &config.key) +} + +/// The same, with another of the broker's keys (such as the cache's). +pub fn options_with_key(config: &SshConfig, key: &std::path::Path) -> Vec { let mut options: Vec = vec!["-F".into(), "none".into(), "-i".into()]; - options.push(credential(&config.key).to_string_lossy().into_owned()); + options.push(credential(key).to_string_lossy().into_owned()); for option in [ "IdentitiesOnly=yes", "IdentityAgent=none", diff --git a/src/proto.rs b/src/proto.rs index 0660acc..ea4b57a 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, CommitId, DeployTarget, HostName, Lines, NodeName, Since, UnitName, UserName}; +use crate::types::{Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Since, UnitName, UserName}; /// Bumped on any incompatible change; the broker refuses other versions. pub const PROTOCOL_VERSION: u32 = 1; @@ -57,6 +57,9 @@ pub enum Operation { /// Make it the boot default without switching to it. boot: bool, }, + /// Builds flake attributes of a pushed commit and, once approved, pushes them to the binary + /// cache. + Build { attrs: Vec, commit: CommitId }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/src/server.rs b/src/server.rs index 3b3e8ea..c592fb6 100644 --- a/src/server.rs +++ b/src/server.rs @@ -197,7 +197,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io // Some operations do work first, so approvers can see what they'll change; not if policy // would refuse anyway. - if parsed.op == "deploy" { + if matches!(parsed.op, "deploy" | "build") { let refused = match verdict(broker, requester, &parsed) { Ok(verdict) if verdict.action == Action::Deny => Some(denied("denied by policy")), Ok(_) => None, diff --git a/src/types.rs b/src/types.rs index 1ef59ee..1343250 100644 --- a/src/types.rs +++ b/src/types.rs @@ -150,6 +150,23 @@ impl DeployTarget { } } +validated_string!( + /// A flake output attribute path, such as `packages.x86_64-linux.slop-broker`; unquoted, so + /// names can't contain dots. + FlakeAttr, + "flake attribute (use a dotted path like packages.x86_64-linux.name)", + |s| { + s.len() <= 512 + && s.split('.').count() <= 16 + && s.split('.').all(|p| { + let b = p.as_bytes(); + !b.is_empty() + && (b[0].is_ascii_alphabetic() || b[0] == b'_') + && b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_-'".contains(&c)) + }) + } +); + validated_string!( /// One word of a command; anything but NUL. Arg, @@ -232,6 +249,13 @@ mod tests { for bad in ["a.b.c", ".a", "a.", "-a", "a b", "a.\"$x\""] { assert!(bad.parse::().is_err(), "{bad}"); } + + for good in ["packages.x86_64-linux.slop-broker", "ci.x86_64-linux.palace", "hello"] { + assert!(good.parse::().is_ok(), "{good}"); + } + for bad in ["", "a..b", ".a", "a.", "-a", "1a", "a.\"b.c\"", "a b", "a#b", "a/b", "a.${x}"] { + assert!(bad.parse::().is_err(), "{bad}"); + } } #[test] diff --git a/tests/broker.rs b/tests/broker.rs index 21d15f2..c9e076a 100644 --- a/tests/broker.rs +++ b/tests/broker.rs @@ -151,6 +151,19 @@ async fn unknown_nodes_and_versions_are_rejected() { assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("protocol version"))); } +#[tokio::test] +async fn builds_need_a_builder_and_a_cache() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "build": { "action": "auto" } })); + + let operation = Operation::Build { + attrs: vec!["packages.x86_64-linux.hello".parse().unwrap()], + commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(), + }; + let mut client = Client::start(&broker, operation).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("not configured"))); +} + #[tokio::test] async fn invalid_messages_are_rejected() { let directory = tempfile::tempdir().unwrap();