Files
slop-broker/src/builder.rs
T
jackos1998andClaude Opus 5.5 4b2c32636e
CI / Check (pull_request) Successful in 5m17s
CI / Check (push) Canceled after 0s
broker: Containers as targets
`slop status`, `logs`, `failed` and `ssh` take `node.container-<name>`,
the name `slop deploy` already takes, so agents can check a container
without asking for `slop ssh` on its host.

- The builder evaluates each node's profile names; its
  `container-<name>` profiles are the containers requests can name.
- Commands run on the node as root through its `sudo`:
  `systemctl --machine`, `journalctl --machine` and, for `ssh`,
  `systemd-run --machine --pipe --wait` with `/bin/sh -l`.
- A container's scope is its node as `target` plus `container`, so
  node rules apply to it while leases stay per target. Rules can
  match `container`.
- Remote commands are now quoted so `fish` reads them as POSIX shells
  do: it treats `\\` and `\'` as escapes inside single quotes.

`PROTOCOL_VERSION` 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:28:57 +00:00

769 lines
29 KiB
Rust

//! 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 one [`BuilderRequest`] on stdin and
//! gets the result back on stdout, each one frame like the rest of the protocol; 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. [`BuilderRequest::Describe`] runs only Git, so approvers can see the commits before
//! anything agent-written runs; [`BuilderRequest::Build`] evaluates and builds, which runs
//! agent-written Nix and is why it happens here and not in the broker.
//! [`BuilderRequest::Secret`] and [`BuilderRequest::Nodes`] read the main branch, evaluating only
//! that branch's Nix.
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::de::DeserializeOwned;
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, FlakeAttr, ObjectId, RulesPath, SecretPath};
#[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<PathBuf>,
}
fn default_branch() -> String {
"master".into()
}
/// What the broker asks of the builder, one per connection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum BuilderRequest {
/// Fetch a commit and describe it; runs only Git.
Describe(CommitId),
Build(BuildRequest),
/// What the main branch says about a secret.
Secret(SecretRequest),
/// The main branch's deploy-rs nodes, as SSH targets.
Nodes,
}
/// The main branch's deploy-rs nodes. Nothing in it is agent-written, as long as only people can
/// push to the branch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Nodes {
/// The branch's commit they were read at.
pub commit: CommitId,
pub nodes: BTreeMap<String, Node>,
}
/// How deploy-rs reaches a node: the node's settings, else the flake's `deploy` defaults.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Node {
pub hostname: String,
pub ssh_user: Option<String>,
/// Only the node's own: the flake-wide ones usually name the operator's key.
pub ssh_opts: Vec<String>,
pub sudo: Option<String>,
/// Its profiles' names, such as `system` and `container-<name>`.
#[serde(default)]
pub profiles: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretRequest {
/// The blob ID of the requester's ciphertext, if it sent one.
pub blob: Option<ObjectId>,
/// Relative to the rules file's directory, as the rules file names it.
pub path: SecretPath,
pub rules: RulesPath,
}
/// The main branch's view of a secret. Nothing in it is agent-written, as long as only people
/// can push to the branch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretContext {
pub branch: String,
/// The branch's commit it was read at.
pub commit: CommitId,
/// Every path on the branch, from the repository's root, whose content is the blob.
pub paths: Vec<String>,
/// The path's recipients in the branch's rules file, or `None` if it has no entry.
pub recipients: Option<Vec<String>>,
/// Keys by name, from SSH keys' comments anywhere in the rules file.
#[serde(default)]
pub names: BTreeMap<String, String>,
}
/// A commit as approvers see it before anything is built. Everything but `on_branch` is
/// agent-written.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Description {
/// `git log` of the commits since the branch, one per line.
pub log: String,
/// `git diff --stat` since the branch.
pub stat: String,
/// The diff since the branch, cut at [`MAX_DIFF`] bytes.
pub diff: String,
/// Whether the commit is already on the branch (so already reviewed).
pub on_branch: bool,
}
pub const MAX_DIFF: usize = 48 * 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildRequest {
pub commit: CommitId,
/// Deploy targets whose profiles to build.
pub targets: Vec<DeployTarget>,
/// Flake attributes to build.
pub attrs: Vec<FlakeAttr>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildResult {
/// Every profile to activate, nodes in request order and profiles in deploy-rs's order.
pub profiles: Vec<BuiltProfile>,
/// The output paths of each attribute, in request order.
pub outputs: Vec<BuiltAttr>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuiltAttr {
pub attr: FlakeAttr,
pub paths: Vec<String>,
}
#[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);
}
for path in self.outputs.iter().flat_map(|o| &o.paths) {
ensure!(is_store_path(path), "the builder returned an invalid path {path:?}");
}
Ok(())
}
}
// The broker's side
/// Fetches and describes a commit, running only Git. Its progress goes to `out`.
pub async fn describe(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
commit: &CommitId,
out: &Output,
cancel: &CancellationToken,
) -> Result<Description> {
call(ssh, deploy, &BuilderRequest::Describe(commit.clone()), out, cancel).await
}
/// Runs a build and returns what it built. 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<BuildResult> {
let result: BuildResult = call(ssh, deploy, &BuilderRequest::Build(request.clone()), out, cancel).await?;
result.check()?;
Ok(result)
}
/// The main branch's deploy-rs nodes. Its progress goes to `out`.
pub async fn nodes(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
out: &Output,
cancel: &CancellationToken,
) -> Result<Nodes> {
call(ssh, deploy, &BuilderRequest::Nodes, out, cancel).await
}
/// What the main branch says about a secret. Its progress goes to `out`.
pub async fn secret(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
request: &SecretRequest,
out: &Output,
cancel: &CancellationToken,
) -> Result<SecretContext> {
call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, cancel).await
}
async fn call<R: DeserializeOwned>(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
request: &BuilderRequest,
out: &Output,
cancel: &CancellationToken,
) -> Result<R> {
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 builder failed; its output is above");
decode(&frame.context("the builder sent no 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: BuilderRequest = 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 {
match &request {
BuilderRequest::Describe(commit) => encode(&describe_commit(&config, commit).await?),
BuilderRequest::Secret(request) => encode(&secret_context(&config, request).await?),
BuilderRequest::Nodes => encode(&branch_nodes(&config).await?),
BuilderRequest::Build(request) => {
let _lock = lock(&config.directory.join("build.lock")).await?;
encode(&run(&config, request).await?)
}
}
} => {
let mut stdout = FramedWrite::new(tokio::io::stdout(), codec());
stdout.send(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<std::fs::File> {
lock_saying(path, "Waiting for another build to finish…").await
}
async fn lock_saying(path: &Path, waiting: &str) -> Result<std::fs::File> {
let file = std::fs::File::create(path)?;
let mut said = false;
while file.try_lock().is_err() {
if !said {
eprintln!("{waiting}");
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<String> {
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<String>,
profiles: BTreeMap<String, ProfileInfo>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProfileInfo {
profile_path: Option<String>,
user: Option<String>,
}
/// 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<Vec<(String, String)>> {
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()
}
fn mirror(config: &BuilderConfig) -> PathBuf {
config.directory.join("repository.git")
}
async fn has_commit(config: &BuilderConfig, commit: &CommitId) -> bool {
output(git(config, &mirror(config)).args(["cat-file", "-e", &format!("{commit}^{{commit}}")])).await.is_ok()
}
/// Fetches every branch into the mirror and checks it has `commit`.
async fn fetch(config: &BuilderConfig, commit: &CommitId) -> Result<()> {
fetch_all(config).await?;
if !has_commit(config, commit).await {
bail!("commit {commit} isn't on any branch of {}; push it first", config.repository);
}
Ok(())
}
/// Fetches every branch into the mirror; one fetch at a time, separately from builds.
async fn fetch_all(config: &BuilderConfig) -> Result<()> {
let _lock = lock_saying(&config.directory.join("fetch.lock"), "Waiting for another fetch…").await?;
let repository = mirror(config);
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")?;
Ok(())
}
/// What approvers see of a commit: Git only, nothing from the commit runs.
async fn describe_commit(config: &BuilderConfig, commit: &CommitId) -> Result<Description> {
fetch(config, commit).await?;
let repository = mirror(config);
let branch = format!("refs/remotes/origin/{}", config.branch);
let base = output(git(config, &repository).args(["merge-base", commit, &branch])).await.ok();
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?;
let mut diff =
output(git(config, &repository).args(["diff", "--no-color", "--no-ext-diff", base, commit])).await?;
if diff.len() > MAX_DIFF {
let mut end = MAX_DIFF;
while !diff.is_char_boundary(end) {
end -= 1;
}
diff.truncate(end);
diff += "\n(diff cut short)\n";
}
Ok(Description { log, stat, diff, on_branch: false })
}
Some(_) => Ok(Description {
log: format!("(on {})\n", config.branch),
stat: String::new(),
diff: String::new(),
on_branch: true,
}),
None => Ok(Description {
log: format!("(not based on {})\n", config.branch),
stat: String::new(),
diff: String::new(),
on_branch: false,
}),
}
}
/// The main branch's commit, freshly fetched.
async fn branch_tip(config: &BuilderConfig) -> Result<CommitId> {
fetch_all(config).await?;
let branch = format!("refs/remotes/origin/{}", config.branch);
let commit = output(git(config, &mirror(config)).args(["rev-parse", "--verify", &format!("{branch}^{{commit}}")]))
.await
.with_context(|| format!("finding {}", config.branch))?;
commit.trim().parse().map_err(anyhow::Error::msg)
}
/// Where a blob lives on the main branch, and the branch's recipients for a path. Runs Git, and
/// evaluates the branch's rules file, never a requester's commit.
async fn secret_context(config: &BuilderConfig, request: &SecretRequest) -> Result<SecretContext> {
let commit = branch_tip(config).await?;
let repository = mirror(config);
let paths = match &request.blob {
Some(blob) => {
let tree = output(git(config, &repository).args(["ls-tree", "-r", "-z", &commit])).await?;
blob_paths(&tree, blob)
}
None => Vec::new(),
};
let rules = rules(config, &commit, &request.rules).await?;
let recipients = rules.get(&*request.path).cloned();
let names = commented(rules.values().flatten());
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients, names })
}
/// SSH keys by their comments, like `ssh-ed25519 AAAA… shill`; age ignores the comment.
fn commented<'a>(keys: impl Iterator<Item = &'a String>) -> BTreeMap<String, String> {
keys.filter_map(|key| match key.split_whitespace().collect::<Vec<_>>().as_slice() {
[kind, key, comment @ ..] if kind.starts_with("ssh-") && !comment.is_empty() => {
Some((comment.join(" "), format!("{kind} {key}")))
}
_ => None,
})
.collect()
}
/// Paths in `git ls-tree -r -z` output whose object is `blob`.
fn blob_paths(tree: &str, blob: &ObjectId) -> Vec<String> {
tree.split('\0')
.filter_map(|entry| {
let (info, path) = entry.split_once('\t')?;
let mut fields = info.split(' ');
(fields.nth(1) == Some("blob") && fields.next() == Some(&**blob)).then(|| path.to_owned())
})
.collect()
}
/// The rules file's recipients by path, at `commit`. Evaluated once per commit, since that can
/// mean evaluating every system that declares secrets.
async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) -> Result<BTreeMap<String, Vec<String>>> {
let cache = config.directory.join("secret-rules");
let file = cache.join(format!("{commit}-{}.json", hex::encode(rules.as_bytes())));
if let Ok(text) = std::fs::read_to_string(&file) {
return Ok(serde_json::from_str(&text)?);
}
eprintln!("Evaluating {rules} on {}…", config.branch);
// The values come from the environment, so none of them is ever Nix syntax.
let expression = "let \
env = builtins.getEnv; \
source = builtins.fetchGit { \
url = \"file://${env \"SLOP_REPOSITORY\"}\"; rev = env \"SLOP_REV\"; allRefs = true; \
}; \
in builtins.mapAttrs (_: v: v.publicKeys or [ ]) (import (source + \"/${env \"SLOP_RULES\"}\"))";
let evaluated = output(
command(config, "nix")
.args(["eval", "--json", "--impure"])
.args(NIX_OPTIONS)
.args(["--expr", expression])
.env("SLOP_REPOSITORY", mirror(config))
.env("SLOP_REV", &**commit)
.env("SLOP_RULES", &**rules),
)
.await
.with_context(|| format!("evaluating {rules}"))?;
let parsed: BTreeMap<String, Vec<String>> = serde_json::from_str(&evaluated).context("reading the rules")?;
// Only the newest commit's rules are worth keeping.
let _ = std::fs::remove_dir_all(&cache);
std::fs::create_dir_all(&cache)?;
std::fs::write(&file, &evaluated)?;
Ok(parsed)
}
/// The main branch's deploy-rs nodes, evaluated once per commit.
async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
let commit = branch_tip(config).await?;
let cache = config.directory.join("deploy-nodes");
// Named for what's evaluated, so a broker reading more evaluates again.
let file = cache.join(format!("{commit}.profiles.json"));
if let Ok(text) = std::fs::read_to_string(&file) {
return Ok(Nodes { commit, nodes: serde_json::from_str(&text)? });
}
eprintln!("Evaluating deploy.nodes on {}…", config.branch);
let flake = format!("git+file://{}?rev={commit}", mirror(config).display());
let apply = "d: builtins.mapAttrs (_: n: { \
hostname = n.hostname; \
sshUser = n.sshUser or d.sshUser or null; \
sshOpts = n.sshOpts or [ ]; \
sudo = n.sudo or d.sudo or null; \
profiles = builtins.attrNames (n.profiles or { }); \
}) d.nodes";
let evaluated = output(
command(config, "nix")
.args(["eval", "--json"])
.args(NIX_OPTIONS)
.arg(format!("{flake}#deploy"))
.args(["--apply", apply]),
)
.await
.context("evaluating deploy.nodes")?;
let nodes = serde_json::from_str(&evaluated).context("reading deploy.nodes")?;
// Only the newest commit's nodes are worth keeping.
let _ = std::fs::remove_dir_all(&cache);
std::fs::create_dir_all(&cache)?;
std::fs::write(&file, &evaluated)?;
Ok(Nodes { commit, nodes })
}
async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResult> {
let commit = &request.commit;
let repository = mirror(config);
// Normally fetched when it was described
if !has_commit(config, commit).await {
fetch(config, commit).await?;
}
// 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: Vec<String> = 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)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()?
.wait_with_output()
.await?;
ensure!(built.status.success(), "nix build failed");
#[derive(Deserialize)]
struct Built {
outputs: BTreeMap<String, String>,
}
let built: Vec<Built> = serde_json::from_slice(&built.stdout).context("reading nix build's result")?;
ensure!(
built.len() == installables.len(),
"nix build returned {} results for {} installables",
built.len(),
installables.len()
);
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 { profiles, outputs };
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 finds_paths_of_a_blob() {
let blob: ObjectId = "0123456789abcdef0123456789abcdef01234567".parse().unwrap();
let tree = format!(
"100644 blob {blob}\tsecrets/a.age\0100644 blob {}\tsecrets/b.age\0\
100644 blob {blob}\tsecrets/copy of a.age\0160000 commit {blob}\tsub\0",
"f".repeat(40)
);
assert_eq!(blob_paths(&tree, &blob), ["secrets/a.age", "secrets/copy of a.age"]);
}
#[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::<Vec<_>>(), ["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());
}
}