The builder and the broker run Nix with `--log-format internal-json` and turn its activities into `Progress` messages for each phase: the build, each node's copy, comparison and activation, and the push to the cache. Build logs no longer stream by default, since they're mostly noise to an agent; `--logs` brings them back, and a failed build's error still ends with the last lines of its log. Text from Nix loses its terminal escapes. The builder now answers with progress frames before its result. Protocol 4. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
10 KiB
Rust
249 lines
10 KiB
Rust
//! The builder's Git-only stages against a local Git repository. Skipped where `git` (or, for
|
|
//! secrets and deploy nodes, `nix`) isn't installed, such as the package build's sandbox.
|
|
use std::io::{Read, Write};
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Command, Stdio};
|
|
|
|
use serde::de::DeserializeOwned;
|
|
use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, Nodes, Reply, SecretContext, SecretRequest};
|
|
use slop_broker::proto::{decode, encode};
|
|
use slop_broker::types::ObjectId;
|
|
|
|
fn git_directory() -> Option<PathBuf> {
|
|
program_directory("git")
|
|
}
|
|
|
|
fn program_directory(program: &str) -> Option<PathBuf> {
|
|
let output = Command::new("sh").args(["-c", &format!("command -v {program}")]).output().ok()?;
|
|
if !output.status.success() {
|
|
return None;
|
|
}
|
|
let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
|
|
Some(path.parent()?.to_owned())
|
|
}
|
|
|
|
fn git(directory: &Path, args: &[&str]) -> String {
|
|
let output = Command::new("git")
|
|
.arg("-C")
|
|
.arg(directory)
|
|
.args(["-c", "user.name=agent", "-c", "user.email=agent@example", "-c", "commit.gpgsign=false"])
|
|
.args(args)
|
|
.output()
|
|
.unwrap();
|
|
assert!(output.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&output.stderr));
|
|
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
|
}
|
|
|
|
/// Sends one request to `slop-broker builder` and reads its answer.
|
|
fn ask<T: DeserializeOwned>(config: &Path, request: &BuilderRequest) -> T {
|
|
let mut child = Command::new(env!("CARGO_BIN_EXE_slop-broker"))
|
|
.args(["builder", "--config"])
|
|
.arg(config)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::inherit())
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
let frame = encode(request).unwrap();
|
|
let mut stdin = child.stdin.take().unwrap();
|
|
stdin.write_all(&(frame.len() as u32).to_be_bytes()).unwrap();
|
|
stdin.write_all(&frame).unwrap();
|
|
|
|
// The builder exits after answering; stdin stays open until then, as the broker keeps it.
|
|
let mut answer = Vec::new();
|
|
child.stdout.take().unwrap().read_to_end(&mut answer).unwrap();
|
|
assert!(child.wait().unwrap().success());
|
|
drop(stdin);
|
|
|
|
// Progress frames, if any, then the result
|
|
let mut rest = &answer[..];
|
|
loop {
|
|
let length = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize;
|
|
let (frame, after) = rest[4..].split_at(length);
|
|
if let Reply::Done(result) = decode(frame).unwrap() {
|
|
return decode(&result).unwrap();
|
|
}
|
|
rest = after;
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn describes_commits_with_git_alone() {
|
|
let Some(git_path) = git_directory() else {
|
|
eprintln!("skipped: git isn't installed");
|
|
return;
|
|
};
|
|
|
|
let directory = tempfile::tempdir().unwrap();
|
|
let work = directory.path().join("work");
|
|
std::fs::create_dir(&work).unwrap();
|
|
git(&work, &["init", "--quiet", "--initial-branch=master"]);
|
|
std::fs::write(work.join("flake.nix"), "{ outputs = _: { }; }\n").unwrap();
|
|
git(&work, &["add", "."]);
|
|
git(&work, &["commit", "--quiet", "-m", "Initial"]);
|
|
let reviewed = git(&work, &["rev-parse", "HEAD"]);
|
|
|
|
// Anything in it would run if it were evaluated; describing mustn't.
|
|
git(&work, &["checkout", "--quiet", "-b", "agent"]);
|
|
let flake = format!("{{ outputs = _: builtins.trace \"evaluated\" {{ }}; }}\n# {}\n", "x".repeat(MAX_DIFF));
|
|
std::fs::write(work.join("flake.nix"), flake).unwrap();
|
|
git(&work, &["commit", "--quiet", "-am", "Add \x1b[2Ksomething"]);
|
|
let agent = git(&work, &["rev-parse", "HEAD"]);
|
|
|
|
let state = directory.path().join("state");
|
|
std::fs::create_dir(&state).unwrap();
|
|
let config = directory.path().join("builder.toml");
|
|
std::fs::write(
|
|
&config,
|
|
format!(
|
|
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}]\n",
|
|
work.display().to_string(),
|
|
state.display().to_string(),
|
|
git_path.display().to_string(),
|
|
),
|
|
)
|
|
.unwrap();
|
|
|
|
let described: Description = ask(&config, &BuilderRequest::Describe(agent.parse().unwrap()));
|
|
assert!(!described.on_branch);
|
|
assert!(described.log.contains("Add \x1b[2Ksomething"), "{}", described.log);
|
|
assert!(described.stat.contains("flake.nix"), "{}", described.stat);
|
|
assert!(described.diff.contains("builtins.trace") && described.diff.ends_with("(diff cut short)\n"));
|
|
assert!(described.diff.len() < MAX_DIFF + 100);
|
|
|
|
let described: Description = ask(&config, &BuilderRequest::Describe(reviewed.parse().unwrap()));
|
|
assert!(described.on_branch && described.diff.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn secrets_are_looked_up_on_the_branch() {
|
|
let (Some(git_path), Some(nix_path)) = (git_directory(), program_directory("nix")) else {
|
|
eprintln!("skipped: git or nix isn't installed");
|
|
return;
|
|
};
|
|
|
|
// The branch has a secret, a copy of it under another name, and rules for the first.
|
|
let directory = tempfile::tempdir().unwrap();
|
|
let work = directory.path().join("work");
|
|
std::fs::create_dir_all(work.join("secrets")).unwrap();
|
|
git(&work, &["init", "--quiet", "--initial-branch=master"]);
|
|
std::fs::write(work.join("secrets/a.age"), "age-encryption.org/v1\nreal\n").unwrap();
|
|
std::fs::write(work.join("secrets/copy.age"), "age-encryption.org/v1\nreal\n").unwrap();
|
|
let rules = |keys: &str| {
|
|
format!("{{ \"secrets/a.age\".publicKeys = [ \"age1dev\" ]; \"secrets/b.age\".publicKeys = [ {keys} ]; }}\n")
|
|
};
|
|
std::fs::write(work.join("secrets.nix"), rules("\"ssh-ed25519 AAAA box\"")).unwrap();
|
|
git(&work, &["add", "."]);
|
|
git(&work, &["commit", "--quiet", "-m", "Secrets"]);
|
|
|
|
// An agent's branch can't change what the main branch says.
|
|
git(&work, &["checkout", "--quiet", "-b", "agent"]);
|
|
std::fs::write(work.join("secrets.nix"), rules("\"ssh-ed25519 AAAA box\" \"ssh-ed25519 BBBB box\"")).unwrap();
|
|
git(&work, &["commit", "--quiet", "-am", "Change the rules"]);
|
|
|
|
let state = directory.path().join("state");
|
|
std::fs::create_dir(&state).unwrap();
|
|
let config = directory.path().join("builder.toml");
|
|
std::fs::write(
|
|
&config,
|
|
format!(
|
|
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}, {:?}]\n",
|
|
work.display().to_string(),
|
|
state.display().to_string(),
|
|
git_path.display().to_string(),
|
|
nix_path.display().to_string(),
|
|
),
|
|
)
|
|
.unwrap();
|
|
|
|
let request = SecretRequest {
|
|
blob: Some(ObjectId::blob(b"age-encryption.org/v1\nreal\n")),
|
|
path: "secrets/a.age".parse().unwrap(),
|
|
rules: "secrets.nix".parse().unwrap(),
|
|
};
|
|
let context: SecretContext = ask(&config, &BuilderRequest::Secret(request.clone()));
|
|
assert_eq!(context.paths, ["secrets/a.age", "secrets/copy.age"]);
|
|
assert_eq!(context.recipients, Some(vec!["age1dev".to_owned()]));
|
|
// Names come from comments on every path's keys.
|
|
assert_eq!(context.names, std::collections::BTreeMap::from([("box".to_owned(), "ssh-ed25519 AAAA".to_owned())]));
|
|
assert_eq!(&*context.commit, git(&work, &["rev-parse", "master"]));
|
|
|
|
let unknown = SecretRequest { blob: None, path: "secrets/new.age".parse().unwrap(), ..request };
|
|
let context: SecretContext = ask(&config, &BuilderRequest::Secret(unknown));
|
|
assert!(context.paths.is_empty() && context.recipients.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn deploy_nodes_are_looked_up_on_the_branch() {
|
|
let (Some(git_path), Some(nix_path)) = (git_directory(), program_directory("nix")) else {
|
|
eprintln!("skipped: git or nix isn't installed");
|
|
return;
|
|
};
|
|
|
|
// Flake-wide defaults, which a node can override; the flake-wide `sshOpts` aren't used.
|
|
let directory = tempfile::tempdir().unwrap();
|
|
let work = directory.path().join("work");
|
|
std::fs::create_dir_all(&work).unwrap();
|
|
git(&work, &["init", "--quiet", "--initial-branch=master"]);
|
|
let flake = |web: &str| {
|
|
format!(
|
|
"{{ outputs = _: {{ deploy = {{ sshUser = \"deploy\"; sudo = \"doas -u\"; sshOpts = [ \"-i\" \"key\" ];\n\
|
|
nodes.web = {{ hostname = \"{web}\"; sshOpts = [ \"-p\" \"2222\" ]; profiles = {{ }}; }};\n\
|
|
nodes.box = {{ hostname = \"box.example\"; sshUser = \"root\"; sudo = \"sudo -u\"; profiles = {{ }}; }};\n\
|
|
}}; }}; }}\n"
|
|
)
|
|
};
|
|
std::fs::write(work.join("flake.nix"), flake("web.example")).unwrap();
|
|
git(&work, &["add", "."]);
|
|
git(&work, &["commit", "--quiet", "-m", "Nodes"]);
|
|
|
|
// An agent's branch can't move a node.
|
|
git(&work, &["checkout", "--quiet", "-b", "agent"]);
|
|
std::fs::write(work.join("flake.nix"), flake("attacker.example")).unwrap();
|
|
git(&work, &["commit", "--quiet", "-am", "Move web"]);
|
|
|
|
let state = directory.path().join("state");
|
|
std::fs::create_dir(&state).unwrap();
|
|
let config = directory.path().join("builder.toml");
|
|
std::fs::write(
|
|
&config,
|
|
format!(
|
|
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}, {:?}]\n",
|
|
work.display().to_string(),
|
|
state.display().to_string(),
|
|
git_path.display().to_string(),
|
|
nix_path.display().to_string(),
|
|
),
|
|
)
|
|
.unwrap();
|
|
|
|
let found: Nodes = ask(&config, &BuilderRequest::Nodes);
|
|
assert_eq!(&*found.commit, git(&work, &["rev-parse", "master"]));
|
|
let web = &found.nodes["web"];
|
|
assert_eq!(web.hostname, "web.example");
|
|
assert_eq!(web.ssh_user.as_deref(), Some("deploy"));
|
|
assert_eq!(web.ssh_opts, ["-p", "2222"]);
|
|
assert_eq!(web.sudo.as_deref(), Some("doas -u"));
|
|
let other = &found.nodes["box"];
|
|
assert_eq!((other.ssh_user.as_deref(), other.sudo.as_deref()), (Some("root"), Some("sudo -u")));
|
|
assert!(other.ssh_opts.is_empty());
|
|
|
|
// Asked again at the same commit, the cached answer is the same.
|
|
let again: Nodes = ask(&config, &BuilderRequest::Nodes);
|
|
assert_eq!(again, found);
|
|
}
|
|
|
|
#[test]
|
|
fn blob_ids_match_git() {
|
|
let Some(_) = git_directory() else {
|
|
eprintln!("skipped: git isn't installed");
|
|
return;
|
|
};
|
|
let directory = tempfile::tempdir().unwrap();
|
|
let file = directory.path().join("blob");
|
|
std::fs::write(&file, b"some\0bytes\n").unwrap();
|
|
let output = Command::new("git").arg("hash-object").arg(&file).output().unwrap();
|
|
assert_eq!(&*ObjectId::blob(b"some\0bytes\n"), String::from_utf8(output.stdout).unwrap().trim());
|
|
}
|