Files
slop-broker/tests/broker.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

707 lines
30 KiB
Rust

//! End-to-end tests of the request handler with a fake `ssh`.
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use nix::sys::signal::kill;
use nix::unistd::{Pid, geteuid};
use serde_json::json;
use tokio::io::DuplexStream;
use slop_broker::builder::Node;
use slop_broker::config::Config;
use slop_broker::proto::{ApproveRequest, ApproveResponse, receive, send};
use slop_broker::proto::{
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Query, Request, SecretFile,
SecretOp, ServerMessage, Target, Transport, decode, encode, transport,
};
use slop_broker::queue::Decision;
use slop_broker::remote::{Hello, Role, write_hello};
use slop_broker::server::{Broker, handle};
use slop_broker::types::{Arg, Lines};
const FAKE_SSH: &str = r#"#!/bin/sh
echo $$ > "${0%/*}/pid"
echo "args: $*"
while read -r line; do
[ "$line" = block ] && exec sleep 60
echo "in: $line"
done
echo done >&2
exit 3
"#;
fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
let ssh = directory.join("ssh");
std::fs::write(&ssh, FAKE_SSH).unwrap();
std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
let config: Config = serde_json::from_value(json!({
"requesters": { "agent": { "remote": true, "policy": "agent" } },
"policies": { "agent": { "ops": ops } },
"timeout": 2,
"approve_socket": "/unused",
"approver_group": "root",
"audit_log": directory.join("audit.jsonl"),
"remote": { "socket": "/unused", "user": "root", "approvers": ["laptop"] },
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh" },
"deploy": {
"builder": { "hostname": "builder.example.org", "user": "builder", "ssh_opts": [] },
"nix": "/unused",
"cache": directory.join("cache"),
},
}))
.unwrap();
// The main branch's nodes, as the builder would have found them
let broker = Broker::new(config).unwrap();
let river = Node {
hostname: "river.example.org".into(),
ssh_user: Some("deploy".into()),
ssh_opts: vec![],
sudo: None,
profiles: vec!["system".into(), "container-web".into()],
};
broker.targets.assume(&broker.config, [("river".to_owned(), river)].into());
Arc::new(broker)
}
struct Client {
transport: Transport<DuplexStream>,
}
impl Client {
async fn start(broker: &Arc<Broker>, operation: Operation) -> Client {
Client::start_with(broker, Request { version: PROTOCOL_VERSION, label: Some("test".into()), operation }).await
}
async fn start_with(broker: &Arc<Broker>, request: Request) -> Client {
let (client, server) = tokio::io::duplex(1 << 16);
tokio::spawn(handle(broker.clone(), server, "agent".into()));
let mut client = Client { transport: transport(client) };
client.send(ClientMessage::Request(request)).await;
client
}
async fn send(&mut self, message: ClientMessage) {
self.transport.send(encode(&message).unwrap()).await.unwrap();
}
/// Reads until the next message other than output, collecting output.
async fn next(&mut self, output: &mut String) -> ServerMessage {
loop {
let frame =
tokio::time::timeout(Duration::from_secs(10), self.transport.next()).await.unwrap().unwrap().unwrap();
match decode::<ServerMessage>(&frame).unwrap() {
ServerMessage::Stdout(data) | ServerMessage::Stderr(data) => {
output.push_str(&String::from_utf8_lossy(&data))
}
message => return message,
}
}
}
}
fn ssh(command: &[&str]) -> Operation {
ssh_with(command, None)
}
fn ssh_with(command: &[&str], stdin: Option<&[u8]>) -> Operation {
Operation::Ssh {
destination: Destination::Node("river".parse().unwrap()),
command: command.iter().map(|c| c.parse::<Arg>().unwrap()).collect(),
stdin: stdin.map(<[u8]>::to_vec),
}
}
fn finished(exit: i32) -> ServerMessage {
ServerMessage::Finished { exit, result: None }
}
#[tokio::test]
async fn auto_runs_with_stdio_and_exit_status() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let mut client = Client::start(&broker, ssh_with(&["uptime", "-p"], Some(b"hello\n"))).await;
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
assert_eq!(client.next(&mut output).await, finished(3));
assert!(output.contains("-l deploy -- river.example.org uptime -p"), "{output}");
assert!(output.contains("-o IdentityAgent=none"), "{output}");
assert!(output.contains("in: hello"), "{output}");
assert!(output.contains("done"), "{output}");
}
#[tokio::test]
async fn policy_can_deny_and_unlisted_operations_are_denied() {
let directory = tempfile::tempdir().unwrap();
let ops = json!({ "ssh": { "action": "auto", "rules": [{ "match": { "target": "river" }, "action": "deny" }] } });
let broker = broker(directory.path(), ops);
let mut client = Client::start(&broker, ssh(&["true"])).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_)));
let query = Operation::Query { destination: Destination::Node("river".parse().unwrap()), query: Query::Failed };
let mut client = Client::start(&broker, query).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_)));
}
#[tokio::test]
async fn unknown_nodes_and_versions_are_rejected() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let operation =
Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![], stdin: None };
let mut client = Client::start(&broker, operation).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("unknown node")));
let request = Request { version: PROTOCOL_VERSION + 1, label: None, operation: ssh(&["true"]) };
let mut client = Client::start_with(&broker, request).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("protocol version")));
}
#[tokio::test]
async fn builds_need_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 deploys_have_a_rule_scope_per_target() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "deploy": { "action": "ask" } }));
let operation = Operation::Deploy {
targets: vec!["river".parse().unwrap()],
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
boot: true,
};
let parsed = slop_broker::ops::plan(&broker, operation).unwrap();
assert_eq!(parsed.rule_scopes.len(), 1);
assert_eq!(parsed.rule_scopes[0]["node"], "river");
assert_eq!(parsed.rule_scopes[0]["mode"], "boot");
}
#[tokio::test]
async fn invalid_messages_are_rejected() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let raw = |node: &str, extra: bool| {
let mut ssh = json!({ "destination": { "node": node }, "command": [], "stdin": null });
if extra {
ssh["unexpected"] = json!(true);
}
json!({ "request": { "version": PROTOCOL_VERSION, "label": null, "operation": { "ssh": ssh } } })
};
for (message, valid) in
[(raw("river", false), true), (raw("-oProxyCommand=x", false), false), (raw("river", true), false)]
{
let (client, server) = tokio::io::duplex(1 << 16);
tokio::spawn(handle(broker.clone(), server, "agent".into()));
let mut client = Client { transport: transport(client) };
client.transport.send(encode(&message).unwrap()).await.unwrap();
let reply = client.next(&mut String::new()).await;
assert_eq!(matches!(reply, ServerMessage::Approved { .. }), valid, "{message} → {reply:?}");
}
}
#[tokio::test]
async fn approvers_see_the_whole_command_and_stdin_that_run() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
// The words go to the remote shell joined with spaces, so that's what approvers see.
let script = b"echo one\necho two\n";
let mut client = Client::start(&broker, ssh_with(&["bash", "-s", "a b"], Some(script))).await;
let id = pending_id(&mut client).await;
let detail = broker.queue.list()[0].detail.to_text();
assert!(detail.starts_with("Command: bash -s a b\nStdin: 2 lines, 18 bytes\n"), "{detail}");
assert!(detail.ends_with("Stdin:\necho one\necho two"), "{detail}");
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
let mut output = String::new();
client.next(&mut output).await;
assert_eq!(client.next(&mut output).await, finished(3));
assert!(output.contains("in: echo one\nin: echo two\n"), "{output}");
// So is the audit log.
let records = broker.audit.tail(10).unwrap();
let slop_broker::audit::Event::Request { detail: logged, .. } = &records[0].event else { panic!("{records:?}") };
assert_eq!(logged.to_text(), detail);
// Multi-line commands are shown as text rather than a one-line field.
let mut client = Client::start(&broker, ssh(&["echo one\necho two"])).await;
pending_id(&mut client).await;
let detail = broker.queue.list()[0].detail.to_text();
assert_eq!(detail, "Command:\necho one\necho two");
}
#[tokio::test]
async fn stdin_that_cant_be_shown_is_refused() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let binary = ssh_with(&["tar", "x"], Some(b"\xff\xfe"));
let mut client = Client::start(&broker, binary).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("UTF-8")));
let large = vec![b'x'; slop_broker::proto::MAX_SSH_SHOWN];
let mut client = Client::start(&broker, ssh_with(&["cat"], Some(&large))).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("KiB")));
}
async fn pending_id(client: &mut Client) -> String {
pending_for(client, "ssh river").await
}
async fn pending_for(client: &mut Client, expected: &str) -> String {
match client.next(&mut String::new()).await {
ServerMessage::Pending { id, summary } => {
assert_eq!(summary, expected);
// Then how long approvers have, so agents know how long to wait.
let window = client.next(&mut String::new()).await;
assert!(matches!(&window, ServerMessage::Info(m) if m.starts_with("approvers have ")), "{window:?}");
id
}
other => panic!("expected pending, got {other:?}"),
}
}
#[tokio::test]
async fn ask_waits_for_an_approver_and_leases_cover_repeats() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask", "leases": [300] } }));
let mut client = Client::start(&broker, ssh(&["true"])).await;
let id = pending_id(&mut client).await;
let listed = broker.queue.list();
assert_eq!(listed[0].label.as_deref(), Some("test"));
assert_eq!(listed[0].offers, [Decision::Once, Decision::Lease(300), Decision::Deny]);
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).unwrap();
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false });
assert_eq!(client.next(&mut output).await, finished(3));
// Same scope, different command: covered by the lease.
let mut client = Client::start(&broker, ssh(&["reboot"])).await;
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: false });
// Every step is in the audit log under the request's ID.
let records = broker.audit.tail(10).unwrap();
let events: Vec<String> = records.iter().map(|r| r.event.to_string()).collect();
let short = &id[..6];
assert_eq!(events[0], format!("{short} agent asks: ssh river; Command: true (label: test)"));
assert_eq!(events[1], format!("{short} answered 5m by test"));
assert_eq!(events[2], format!("{short} approved by test"));
assert!(events[3].starts_with(&format!("{short} finished with exit status 3 after ")), "{events:?}");
assert!(events[4].ends_with("agent asks: ssh river; Command: reboot (label: test)"), "{events:?}");
assert!(events[5].ends_with("approved by a lease"), "{events:?}");
}
#[tokio::test]
async fn denial_and_expiry() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
let mut client = Client::start(&broker, ssh(&["true"])).await;
let id = pending_id(&mut client).await;
assert!(
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).is_err(),
"lease not offered"
);
slop_broker::approve::approve(&broker, &id, Decision::Deny, "test", false).unwrap();
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_)));
let mut client = Client::start(&broker, ssh(&["true"])).await;
pending_id(&mut client).await;
assert_eq!(client.next(&mut String::new()).await, ServerMessage::Expired);
assert!(broker.queue.list().is_empty());
}
#[tokio::test]
async fn disconnecting_drops_the_request() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
let mut client = Client::start(&broker, ssh(&["true"])).await;
pending_id(&mut client).await;
drop(client);
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(broker.queue.list().is_empty());
}
#[tokio::test]
async fn disconnecting_kills_the_process() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await;
client.next(&mut String::new()).await;
let pid_file = directory.path().join("pid");
let mut pid = None;
for _ in 0..50 {
tokio::time::sleep(Duration::from_millis(50)).await;
pid = std::fs::read_to_string(&pid_file).ok().and_then(|p| p.trim().parse::<i32>().ok());
if pid.is_some() {
break;
}
}
let pid = pid.expect("fake ssh started");
drop(client);
tokio::time::sleep(Duration::from_millis(500)).await;
let alive = kill(Pid::from_raw(pid), None).is_ok();
assert!(!alive, "process {pid} survived its requester");
}
#[tokio::test]
async fn stdin_an_operation_doesnt_read_doesnt_hide_a_disconnect() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await;
client.next(&mut String::new()).await;
for _ in 0..64 {
client.send(ClientMessage::Stdin(b"ignored\n".to_vec())).await;
}
let pid_file = directory.path().join("pid");
let mut pid = None;
for _ in 0..50 {
tokio::time::sleep(Duration::from_millis(50)).await;
pid = std::fs::read_to_string(&pid_file).ok().and_then(|p| p.trim().parse::<i32>().ok());
if pid.is_some() {
break;
}
}
let pid = pid.expect("fake ssh started");
drop(client);
tokio::time::sleep(Duration::from_millis(500)).await;
let alive = kill(Pid::from_raw(pid), None).is_ok();
assert!(!alive, "process {pid} survived its requester");
}
#[tokio::test]
async fn queries_run_a_fixed_quoted_command_without_stdin() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "query": { "action": "auto" } }));
let query = Query::Logs {
unit: "nginx.service".parse().unwrap(),
lines: Lines::try_from(50).unwrap(),
since: Some("2h".parse().unwrap()),
};
let operation = Operation::Query { destination: Destination::Node("river".parse().unwrap()), query };
let mut client = Client::start(&broker, operation).await;
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
assert_eq!(client.next(&mut output).await, finished(3));
assert!(
output.contains(
"river.example.org journalctl --no-pager --output=short-iso --lines=50 --since=-7200s --unit=nginx.service"
),
"{output}"
);
}
#[tokio::test]
async fn containers_are_queried_through_their_host_and_must_be_known() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(
directory.path(),
json!({ "query": { "action": "auto", "rules": [
{ "match": { "container": "*" }, "action": "ask" },
] } }),
);
let container = |name: &str| Destination::Container { node: "river".parse().unwrap(), name: name.parse().unwrap() };
// Rules can tell container queries apart.
let mut client =
Client::start(&broker, Operation::Query { destination: container("web"), query: Query::Failed }).await;
let id = pending_for(&mut client, "failed on river.container-web").await;
assert_eq!(
broker.queue.list()[0].detail.to_text(),
"Command: sudo -u root systemctl --machine=web list-units --failed --no-pager"
);
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
let mut output = String::new();
client.next(&mut output).await;
assert_eq!(client.next(&mut output).await, finished(3));
assert!(
output.contains("river.example.org sudo -u root systemctl --machine=web list-units --failed --no-pager"),
"{output}"
);
let mut client =
Client::start(&broker, Operation::Query { destination: container("db"), query: Query::Failed }).await;
let ServerMessage::Error(error) = client.next(&mut String::new()).await else { panic!() };
assert!(error.contains("unknown container river.container-db"), "{error}");
}
#[tokio::test]
async fn requests_lists_pending_and_leases() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask", "leases": [300] } }));
let mut waiting = Client::start(&broker, ssh(&["true"])).await;
pending_id(&mut waiting).await;
let mut client = Client::start(&broker, Operation::Requests).await;
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
match client.next(&mut output).await {
ServerMessage::Finished { exit: 0, result: Some(OpResult::Requests { pending, leases }) } => {
assert_eq!(pending.len(), 1);
assert_eq!(pending[0].summary, "ssh river");
assert!(leases.is_empty());
}
other => panic!("unexpected {other:?}"),
}
}
/// Connects to the remote socket the way `slop-broker remote` does.
async fn remote(path: &Path, role: Role, name: &str) -> Transport<tokio::net::UnixStream> {
let mut stream = tokio::net::UnixStream::connect(path).await.unwrap();
write_hello(&mut stream, &Hello { role, name: name.into() }).await.unwrap();
transport(stream)
}
#[tokio::test]
async fn remote_requesters_and_approvers_use_one_socket() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
let path = directory.path().join("remote.sock");
let listener = tokio::net::UnixListener::bind(&path).unwrap();
tokio::spawn(slop_broker::remote::listen(broker.clone(), listener, geteuid().as_raw()));
let mut requester = remote(&path, Role::Requester, "agent").await;
let request = ClientMessage::Request(Request { version: PROTOCOL_VERSION, label: None, operation: ssh(&["true"]) });
send(&mut requester, &request).await.unwrap();
let Some(ServerMessage::Pending { id, .. }) = receive(&mut requester).await.unwrap() else { panic!("not pending") };
let Some(ServerMessage::Info(_)) = receive::<_, ServerMessage>(&mut requester).await.unwrap() else {
panic!("no window")
};
// One approver connection carries several requests.
let mut approver = remote(&path, Role::Approver, "laptop").await;
send(&mut approver, &ApproveRequest::List).await.unwrap();
let Some(ApproveResponse::Pending(entries)) = receive(&mut approver).await.unwrap() else { panic!("no list") };
assert_eq!(entries[0].id, id);
send(&mut approver, &ApproveRequest::Decide { id: id.clone(), decision: Decision::Once }).await.unwrap();
assert!(matches!(receive(&mut approver).await.unwrap(), Some(ApproveResponse::Recorded)));
assert!(matches!(
receive::<_, ServerMessage>(&mut requester).await.unwrap(),
Some(ServerMessage::Approved { by: ApprovedBy::Approver, .. })
));
let events: Vec<String> = broker.audit.tail(10).unwrap().iter().map(|r| r.event.to_string()).collect();
assert!(events.iter().any(|e| e.ends_with("answered once by laptop (ssh)")), "{events:?}");
// Names must be configured for the role they claim.
for (role, name) in [(Role::Approver, "agent"), (Role::Requester, "laptop")] {
let mut stream = remote(&path, role, name).await;
let _ = send(&mut stream, &ApproveRequest::List).await;
assert!(receive::<_, ApproveResponse>(&mut stream).await.map_or(true, |r| r.is_none()));
}
}
/// The directory holding `program`, if it's installed.
fn program_directory(program: &str) -> Option<std::path::PathBuf> {
let output = std::process::Command::new("sh").args(["-c", &format!("command -v {program}")]).output().ok()?;
let path = std::path::PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
output.status.success().then(|| path.parent().map(Path::to_owned)).flatten()
}
fn run_git(directory: &Path, args: &[&str]) {
let status = std::process::Command::new("git")
.arg("-C")
.arg(directory)
.args(["-c", "user.name=dev", "-c", "user.email=dev@example", "-c", "commit.gpgsign=false"])
.args(args)
.status()
.unwrap();
assert!(status.success(), "git {args:?}");
}
fn encrypt(recipients: &[&age::x25519::Identity], plaintext: &[u8]) -> Vec<u8> {
use std::io::Write;
let public: Vec<age::x25519::Recipient> = recipients.iter().map(|i| i.to_public()).collect();
let encryptor = age::Encryptor::with_recipients(public.iter().map(|r| r as &dyn age::Recipient)).unwrap();
let mut ciphertext = Vec::new();
let armor = age::armor::ArmoredWriter::wrap_output(&mut ciphertext, age::armor::Format::AsciiArmor).unwrap();
let mut writer = encryptor.wrap_output(armor).unwrap();
writer.write_all(plaintext).unwrap();
writer.finish().unwrap().finish().unwrap();
ciphertext
}
/// A broker with secrets, whose builder is `slop-broker builder` (reached through a fake `ssh`)
/// on a local repository. Its main branch has `secrets/a.env.age` (`A=1`), encrypted to `dev` and
/// the broker, and rules naming both.
struct Secrets {
broker: Arc<Broker>,
dev: age::x25519::Identity,
file: Vec<u8>,
}
fn secrets_broker(directory: &Path) -> Option<Secrets> {
let (git, nix) = (program_directory("git")?, program_directory("nix")?);
let (own, dev) = (age::x25519::Identity::generate(), age::x25519::Identity::generate());
let work = directory.join("work");
std::fs::create_dir_all(work.join("secrets")).unwrap();
run_git(&work, &["init", "--quiet", "--initial-branch=master"]);
let file = encrypt(&[&dev, &own], b"A=1\n");
std::fs::write(work.join("secrets/a.env.age"), &file).unwrap();
let rules =
format!("{{ \"secrets/a.env.age\".publicKeys = [ \"{}\" \"{}\" ]; }}\n", dev.to_public(), own.to_public());
std::fs::write(work.join("secrets.nix"), rules).unwrap();
run_git(&work, &["add", "."]);
run_git(&work, &["commit", "--quiet", "-m", "Secrets"]);
let state = directory.join("state");
std::fs::create_dir(&state).unwrap();
let builder = directory.join("builder.toml");
let builder_config = format!(
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}, {:?}]\n",
work.display().to_string(),
state.display().to_string(),
git.display().to_string(),
nix.display().to_string(),
);
std::fs::write(&builder, builder_config).unwrap();
let ssh = directory.join("ssh");
let script = format!("#!/bin/sh\nexec {:?} builder --config {:?}\n", env!("CARGO_BIN_EXE_slop-broker"), builder);
std::fs::write(&ssh, script).unwrap();
std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
use age::secrecy::ExposeSecret;
let identity = directory.join("identity");
std::fs::write(&identity, format!("# the broker\n{}\n", own.to_string().expose_secret())).unwrap();
let config: Config = serde_json::from_value(json!({
"requesters": { "agent": { "remote": true, "policy": "agent" } },
"policies": { "agent": { "ops": { "secret": {
"action": "ask",
"leases": [300],
"rules": [{ "match": { "action": "keys" }, "action": "auto" }],
} } } },
"timeout": 5,
"approve_socket": "/unused",
"approver_group": "root",
"audit_log": directory.join("audit.jsonl"),
"remote": { "socket": "/unused", "user": "root", "approvers": [] },
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh" },
"deploy": {
"builder": { "hostname": "builder.example.org", "user": "builder", "ssh_opts": [] },
"nix": "/unused",
"cache": directory.join("cache"),
},
"secrets": { "identity": identity, "names": { "dev": dev.to_public().to_string() } },
}))
.unwrap();
Some(Secrets { broker: Arc::new(Broker::new(config).unwrap()), dev, file })
}
impl Client {
/// The next message other than output and progress.
async fn next_quiet(&mut self, output: &mut String) -> ServerMessage {
loop {
match self.next(output).await {
ServerMessage::Info(_) => {}
message => return message,
}
}
}
}
fn secret_file(path: &str, ciphertext: &[u8]) -> SecretFile {
SecretFile { path: path.parse().unwrap(), ciphertext: ciphertext.to_vec() }
}
#[tokio::test]
async fn secrets_are_checked_against_the_branch_and_read_always_asks() {
let directory = tempfile::tempdir().unwrap();
let Some(Secrets { broker, dev, file }) = secrets_broker(directory.path()) else {
eprintln!("skipped: git or nix isn't installed");
return;
};
let mut output = String::new();
// Listing keys is allowed by policy.
let keys = Operation::Secret(SecretOp::Keys { file: secret_file("secrets/a.env.age", &file) });
let mut client = Client::start(&broker, keys).await;
assert_eq!(client.next_quiet(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
let keys = ServerMessage::Finished { exit: 0, result: Some(OpResult::SecretKeys(vec!["A".into()])) };
assert_eq!(client.next_quiet(&mut output).await, keys);
// Setting a field shows what the file is and whom it's for, then takes the value on stdin.
let set = Operation::Secret(SecretOp::Set {
path: "secrets/a.env.age".parse().unwrap(),
base: Some(file.clone()),
target: Target::Field("B".parse().unwrap()),
recipients: vec![dev.to_public().to_string().parse().unwrap()],
});
let mut client = Client::start(&broker, set).await;
let ServerMessage::Pending { id, .. } = client.next_quiet(&mut output).await else { panic!("expected pending") };
let pending = broker.queue.list();
let detail = &pending[0].detail.to_text();
assert!(detail.contains("Content: secrets/a.env.age as on master"), "{detail}");
assert!(detail.contains("Recipients: as in secrets.nix on master"), "{detail}");
assert!(detail.contains("Broker's key: added") && !pending[0].sensitive, "{detail}");
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(client.next_quiet(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true });
client.send(ClientMessage::Stdin(b"2\n".to_vec())).await;
client.send(ClientMessage::StdinEnd).await;
let ServerMessage::Finished { exit: 0, result: Some(OpResult::Secret { ciphertext, public: None }) } =
client.next_quiet(&mut output).await
else {
panic!("expected a secret")
};
assert_eq!(age::decrypt(&dev, &ciphertext).unwrap(), b"A=1\nB=2\n");
// Reading never offers a lease, and a copy of a file under another name is called out.
let read = Operation::Secret(SecretOp::Read { file: secret_file("secrets/harmless.age", &file) });
let mut client = Client::start(&broker, read).await;
let ServerMessage::Pending { id, .. } = client.next_quiet(&mut output).await else { panic!("expected pending") };
let pending = broker.queue.list();
assert_eq!(pending[0].offers, [Decision::Once, Decision::Deny]);
assert!(pending[0].sensitive);
assert!(pending[0].detail.to_text().contains("the same as secrets/a.env.age on master, not secrets/harmless.age"));
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(
client.next_quiet(&mut output).await,
ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false }
);
assert_eq!(client.next_quiet(&mut output).await, finished(0));
// After the builder's progress on stderr
assert!(output.ends_with("\nA=1\n"), "{output}");
}