diff --git a/slop-tools.md b/slop-tools.md index 5293a2d..966b5e6 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -48,17 +48,19 @@ applies a policy, and asks a human to approve most requests. - 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. +- Before anything is built, a human approves your use of the builder after seeing your commits + and their diff; that may be covered by a lease from an earlier request. Then the build and the + copy to the nodes happen, their output streaming to you, and the deploy itself waits for + approval. Keep commits focused so the diff is quick to review. - `--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. +- `slop build` builds on the broker's box from a pushed commit, like `slop deploy` (including the + approval to use the builder first), 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. diff --git a/src/audit.rs b/src/audit.rs index 26f878b..bdeed5a 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -55,6 +55,9 @@ pub enum Event { /// Who answered, when an approver did. #[serde(default, skip_serializing_if = "Option::is_none")] approver: Option, + /// A step before the request itself, such as `builder` for using the builder. + #[serde(default, skip_serializing_if = "Option::is_none")] + step: Option, }, /// An approver's answer. Decision { @@ -122,14 +125,17 @@ impl fmt::Display for Event { } Ok(()) } - Event::Approved { id, by, approver } => { + Event::Approved { id, by, approver, step } => { let by = match (by, approver) { (ApprovedBy::Policy, _) => "policy", (ApprovedBy::Lease, _) => "a lease", (ApprovedBy::Approver, Some(approver)) => approver, (ApprovedBy::Approver, None) => "an approver", }; - write!(f, "{} approved by {by}", short(id)) + match step { + Some(step) => write!(f, "{} {step} approved by {by}", short(id)), + None => write!(f, "{} approved by {by}", short(id)), + } } Event::Decision { id, decision, approver, .. } => { write!(f, "{} answered {decision} by {approver}", short(id)) diff --git a/src/builder.rs b/src/builder.rs index 434b4bb..121ca69 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1,11 +1,12 @@ -//! 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. +//! 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, and evaluates it there: evaluation runs agent-written Nix, which is why it happens -//! here and not in the broker. +//! 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. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::process::Stdio; @@ -13,6 +14,7 @@ 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; @@ -43,6 +45,32 @@ 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), +} + +/// 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 { @@ -56,10 +84,6 @@ pub struct BuildRequest { #[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, /// The output paths of each attribute, in request order. @@ -117,7 +141,18 @@ impl BuildResult { // The broker's side -/// Runs a build and returns what to deploy. Build output goes to `out` as it happens. +/// 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 { + 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, @@ -125,6 +160,18 @@ pub async fn build( out: &Output, cancel: &CancellationToken, ) -> Result { + let result: BuildResult = call(ssh, deploy, &BuilderRequest::Build(request.clone()), out, cancel).await?; + result.check()?; + Ok(result) +} + +async fn call( + ssh: &crate::config::SshConfig, + deploy: &crate::config::DeployConfig, + request: &BuilderRequest, + 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")?; @@ -153,10 +200,8 @@ pub async fn build( 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) + ensure!(status.success(), "the builder failed; its output is above"); + decode(&frame.context("the builder sent no result")?) } // The builder's side @@ -167,17 +212,22 @@ pub async fn worker(config: &Path) -> Result<()> { 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")??)?; + 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 { - let _lock = lock(&config.directory.join("build.lock")).await?; - run(&config, &request).await + match &request { + BuilderRequest::Describe(commit) => encode(&describe_commit(&config, commit).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(encode(&result?)?).await?; + 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) @@ -188,11 +238,15 @@ pub async fn worker(config: &Path) -> Result<()> { /// Waits for the lock, saying so if it's held. async fn lock(path: &Path) -> Result { + lock_saying(path, "Waiting for another build to finish…").await +} + +async fn lock_saying(path: &Path, waiting: &str) -> 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…"); + eprintln!("{waiting}"); said = true; } tokio::time::sleep(Duration::from_secs(2)).await; @@ -290,9 +344,18 @@ fn select(target: &DeployTarget, node: &NodeProfiles) -> Result Result { - let commit = &request.commit; - let repository = config.directory.join("repository.git"); +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; one fetch at a time, separately from builds. +async fn fetch(config: &BuilderConfig, commit: &CommitId) -> 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?; } @@ -308,25 +371,62 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result Result { + fetch(config, commit).await?; + let repository = mirror(config); - // 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) { + 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) + 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(_) => (format!("(on {})\n", config.branch), String::new()), - None => (format!("(not based on {})\n", config.branch), String::new()), - }; + 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, + }), + } +} + +async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result { + 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()); @@ -394,7 +494,7 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result Result { stdin: false, builtin: false, prepared: None, + description: None, operation, }) } @@ -75,7 +76,8 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<() 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); + let description = parsed.description.as_ref().context("the commit wasn't described")?; + let mut detail = super::describe_source(commit, description); detail += "Outputs (closure sizes):\n"; for output in &built.outputs { detail += &format!(" {}:\n", output.attr); diff --git a/src/ops/deploy.rs b/src/ops/deploy.rs index 90815af..b25b026 100644 --- a/src/ops/deploy.rs +++ b/src/ops/deploy.rs @@ -13,13 +13,12 @@ use serde_json::json; use tokio::process::Command; use super::{Parsed, shell_quote, ssh}; -use crate::builder::{self, BuildRequest, BuildResult, BuiltProfile}; +use crate::builder::{self, BuildRequest, 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; @@ -74,6 +73,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { stdin: false, builtin: false, prepared: None, + description: None, operation, }) } @@ -101,7 +101,8 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<() })) .await; - let mut detail = describe_commit(commit, &built); + let description = parsed.description.as_ref().context("the commit wasn't described")?; + let mut detail = super::describe_source(commit, description); for report in reports { detail += &report?; detail.push('\n'); @@ -157,14 +158,6 @@ fn group(profiles: &[BuiltProfile]) -> Vec<(String, Vec<&BuiltProfile>)> { groups } -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"); - } - 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( diff --git a/src/ops/mod.rs b/src/ops/mod.rs index cd3db9c..ad37d7e 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -1,12 +1,14 @@ //! Operations the broker carries out. [`plan`] checks a request against the broker's //! configuration and works out its scope and what approvers are shown; [`execute`] runs it. -use anyhow::{Context, Result}; -use serde_json::{Map, Value}; +use anyhow::{Context, Result, bail}; +use serde_json::{Map, Value, json}; +use crate::builder::Description; use crate::exec::Io; use crate::policy::Limits; use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary}; use crate::server::Broker; +use crate::types::CommitId; pub mod build; pub mod deploy; @@ -31,6 +33,8 @@ pub struct Parsed { pub builtin: bool, /// What [`prepare`] made before approval. pub prepared: Option, + /// The commit, as [`describe`] found it, for operations that build. + pub description: Option, pub operation: Operation, } @@ -71,6 +75,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { builtin: false, rule_scopes: Vec::new(), prepared: None, + description: None, operation, }) } @@ -91,6 +96,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { builtin: false, rule_scopes: Vec::new(), prepared: None, + description: None, operation, }) } @@ -107,11 +113,76 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { builtin: true, rule_scopes: Vec::new(), prepared: None, + description: None, operation, }), } } +/// Operations that run agent-written Nix in the builder: they need its use approved first. +pub fn builds(parsed: &Parsed) -> bool { + matches!(parsed.operation, Operation::Deploy { .. } | Operation::Build { .. }) +} + +fn commit(operation: &Operation) -> Result<&CommitId> { + match operation { + Operation::Deploy { commit, .. } | Operation::Build { commit, .. } => Ok(commit), + _ => bail!("this operation doesn't build"), + } +} + +/// Fetches and describes the commit an operation builds; runs only Git. +pub async fn describe(broker: &Broker, parsed: &Parsed, io: &Io) -> Result { + let commit = commit(&parsed.operation)?; + 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")?; + + io.out.info(format!("fetching {}; it's built once its use of the builder is approved", commit.short())).await; + crate::builder::describe(ssh, deploy, commit, &io.out, &io.cancel).await +} + +/// The request to use the builder for `parsed`: approvers see the commits and their diff before +/// anything agent-written runs. Its scope is empty, so a lease lets the requester build any commit +/// for a while; rules see the commit, whether it's already on the branch, and the operation. +pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result { + let commit = commit(&parsed.operation)?; + let rule_scope = json!({ + "commit": &**commit, + "on_branch": description.on_branch.to_string(), + "for": parsed.op, + }); + + let mut detail = format!("For: {}\n{}", parsed.summary, describe_source(commit, description)); + if !description.diff.is_empty() { + detail += "Diff:\n"; + detail += &description.diff; + } + + Ok(Parsed { + op: "builder", + scope: Map::new(), + rule_scopes: vec![rule_scope.as_object().unwrap().clone()], + summary: format!("run the builder for {}", parsed.summary), + detail: truncate(detail.trim_end(), 60_000), + limits: Limits::default(), + sensitive: false, + stdin: false, + builtin: false, + prepared: None, + description: None, + operation: parsed.operation.clone(), + }) +} + +/// The commit and its log and diffstat, for approvals. +pub fn describe_source(commit: &CommitId, description: &Description) -> String { + let mut text = format!("Commit {commit}\nCommits:\n"); + for line in description.log.lines().chain(description.stat.lines()) { + text += &format!(" {line}\n"); + } + text +} + /// 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<()> { @@ -196,6 +267,39 @@ pub fn truncate(text: &str, limit: usize) -> String { mod tests { use super::*; + #[test] + fn the_builder_gate_shows_the_diff_and_leases_cover_any_commit() { + let commit: CommitId = "0123456789abcdef0123456789abcdef01234567".parse().unwrap(); + let parsed = Parsed { + op: "build", + scope: Map::new(), + rule_scopes: Vec::new(), + summary: "build hello at 0123456789ab".into(), + detail: String::new(), + limits: Limits::default(), + sensitive: false, + stdin: false, + builtin: false, + prepared: None, + description: None, + operation: Operation::Build { attrs: vec!["hello".parse().unwrap()], commit }, + }; + let description = Description { + log: "0123456 pkgs: Add hello\n".into(), + stat: " pkgs/hello.nix | 1 +\n".into(), + diff: "+{ hello }: hello\n".into(), + on_branch: false, + }; + + let gate = builder_gate(&parsed, &description).unwrap(); + assert_eq!(gate.op, "builder"); + assert_eq!(gate.lease_key(), "builder {}"); + assert_eq!(gate.rule_scopes[0]["on_branch"], "false"); + assert_eq!(gate.rule_scopes[0]["for"], "build"); + assert!(gate.summary.starts_with("run the builder for build hello")); + assert!(gate.detail.contains("0123456 pkgs: Add hello") && gate.detail.ends_with("+{ hello }: hello")); + } + #[test] fn makes_text_printable() { assert_eq!(printable("a\x1b[2Kb\rc\u{202e}d\n\te"), "a\u{fffd}[2Kb\u{fffd}c\u{fffd}d\n\te"); diff --git a/src/server.rs b/src/server.rs index c592fb6..c4e20e3 100644 --- a/src/server.rs +++ b/src/server.rs @@ -195,9 +195,11 @@ 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 matches!(parsed.op, "deploy" | "build") { + // Operations that build run agent-written Nix in the builder, which needs its own approval; + // approvers first see the commits and their diff, which only takes Git. Then they build, so + // the request's own approval can show what it changes. None of it happens if policy would + // refuse anyway. + if ops::builds(&parsed) { let refused = match verdict(broker, requester, &parsed) { Ok(verdict) if verdict.action == Action::Deny => Some(denied("denied by policy")), Ok(_) => None, @@ -213,14 +215,46 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io return Some(message); } - if let Err(error) = ops::prepare(broker, &mut parsed, io).await { - if io.cancel.is_cancelled() { - log(Event::Disconnected { id }); + let cancel = io.cancel.clone(); + let failed = |error: anyhow::Error| { + if cancel.is_cancelled() { + log(Event::Disconnected { id: id.clone() }); return None; } let error = format!("{error:#}"); - log(Event::Failed { id, error: error.clone() }); - return Some(ServerMessage::Error(error)); + log(Event::Failed { id: id.clone(), error: error.clone() }); + Some(ServerMessage::Error(error)) + }; + + let description = match ops::describe(broker, &parsed, io).await { + Ok(description) => description, + Err(error) => return failed(error), + }; + let gate = match ops::builder_gate(&parsed, &description) { + Ok(gate) => gate, + Err(error) => return failed(error), + }; + log(Event::Prepared { id: id.clone(), detail: gate.detail.clone() }); + + let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await { + Ok(Some(approval)) => approval, + Ok(None) => { + log(Event::Disconnected { id }); + return None; + } + Err(message) => { + log(refusal(&id, &message)); + return Some(message); + } + }; + log(Event::Approved { id: id.clone(), by, approver: approver.clone(), step: Some("builder".into()) }); + io.out + .info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by)))) + .await; + parsed.description = Some(description); + + if let Err(error) = ops::prepare(broker, &mut parsed, io).await { + return failed(error); } log(Event::Prepared { id: id.clone(), detail: parsed.detail.clone() }); @@ -233,18 +267,12 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io return None; } Err(message) => { - log(match &message { - ServerMessage::Expired => Event::Expired { id }, - ServerMessage::Denied(reason) | ServerMessage::Error(reason) => { - Event::Denied { id, reason: reason.clone() } - } - other => Event::Denied { id, reason: format!("{other:?}") }, - }); + log(refusal(&id, &message)); return Some(message); } }; - log(Event::Approved { id: id.clone(), by: approved_by, approver }); + log(Event::Approved { id: id.clone(), by: approved_by, approver, step: None }); io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await; let (start, builtin) = (std::time::Instant::now(), parsed.builtin); @@ -351,6 +379,24 @@ async fn authorize( } } +/// The audit event for a request that wasn't authorized. +fn refusal(id: &str, message: &ServerMessage) -> Event { + let id = id.to_owned(); + match message { + ServerMessage::Expired => Event::Expired { id }, + ServerMessage::Denied(reason) | ServerMessage::Error(reason) => Event::Denied { id, reason: reason.clone() }, + other => Event::Denied { id, reason: format!("{other:?}") }, + } +} + +fn approved_by_name(by: ApprovedBy) -> &'static str { + match by { + ApprovedBy::Policy => "policy", + ApprovedBy::Lease => "a lease", + ApprovedBy::Approver => "an approver", + } +} + fn denied(reason: &str) -> ServerMessage { ServerMessage::Denied(reason.into()) } diff --git a/tests/builder.rs b/tests/builder.rs new file mode 100644 index 0000000..3b663b3 --- /dev/null +++ b/tests/builder.rs @@ -0,0 +1,103 @@ +//! The builder's describe stage against a local Git repository. Skipped where `git` 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 slop_broker::builder::{BuilderRequest, Description, MAX_DIFF}; +use slop_broker::proto::{decode, encode}; + +fn git_directory() -> Option { + let output = Command::new("sh").args(["-c", "command -v git"]).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 one-frame answer. +fn ask(config: &Path, request: &BuilderRequest) -> Description { + 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); + + let length = u32::from_be_bytes(answer[..4].try_into().unwrap()) as usize; + decode(&answer[4..4 + length]).unwrap() +} + +#[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 = 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 = ask(&config, &BuilderRequest::Describe(reviewed.parse().unwrap())); + assert!(described.on_branch && described.diff.is_empty()); +}