5 Commits
Author SHA1 Message Date
jackos1998andClaude Opus 5.5 a565260021 docs: Release separately and keep notes in issues
CI / Check (pull_request) Canceled after 0s
CI / Check (push) Successful in 5m8s
The version is bumped in a release pull request once its changes have
merged, not in each change. Running notes go in Gitea issues instead
of a WIP file on a branch, which went stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:18:41 +00:00
jackos1998andClaude Opus 5.5 b7fe2c6382 release: Bump to 0.3.0
CI / Check (pull_request) Canceled after 2m7s
Containers as targets (protocol 3), copying from the builder's
store, and stdin no longer hiding a disconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:16:47 +00:00
jackos1998andClaude Opus 5.5 5b7db9eaf9 broker: Copy from the builder's store
CI / Check (pull_request) Successful in 5m10s
CI / Check (push) Successful in 5m15s
The broker read what the builder built from its own store, which only
works while they share a box. Read it from the builder's store
instead, which also works when they do.

- Deploys and `slop build` copy `--from ssh-ng://` the builder's user,
  and closure sizes are read there.
- The builder key's forced command serves `nix-daemon --stdio` for it.
- The store URL carries the builder's port and the broker's key: one
  `NIX_SSHOPTS` serves both ends of a copy, and Nix puts the URL's
  `-p` after it. So the builder's SSH options can only set a port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:04:36 +00:00
jackos1998andClaude Opus 5.5 4b2c32636e broker: Containers as targets
CI / Check (pull_request) Successful in 5m17s
CI / Check (push) Canceled after 0s
`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
jackos1998andClaude Opus 5.5 00d3c65cfd broker: Never block reading a requester's stdin
CI / Check (pull_request) Successful in 4m53s
CI / Check (push) Canceled after 3m47s
The reader passed stdin to the operation through a channel 16 deep and
waited when it was full, so a requester sending stdin to an operation
that doesn't read it stopped the reader, and the broker no longer saw
it disconnect: the operation kept running.

Buffer stdin without waiting, up to 1 MiB (a requester sending more is
treated as gone), and drop it for operations that don't read it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:28:51 +00:00
24 changed files with 511 additions and 70 deletions

No files matched your search

+6
View File
@@ -89,6 +89,12 @@ otherwise `git add -N`) before `nix build` can use it.
one commit even when it touches code, modules and docs; split only when a reader would ask why two
things arrived together.
## Work in progress
Plans, status, next steps and handoffs go in Gitea issues on `dev/slop-broker`, one per piece of
work with its description kept current, not in files in the repository or on branches. When the
work is done, move what lasts into `docs/` or this file and close the issue.
## Writing
- In prose and commit messages, quote code-like identifiers (commands, options, paths, crate and
Generated
+1 -1
View File
@@ -3859,7 +3859,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "slop-broker"
version = "0.2.2"
version = "0.3.0"
dependencies = [
"age",
"anyhow",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "slop-broker"
version = "0.2.2"
version = "0.3.0"
edition = "2024"
description = "Approval broker that runs privileged operations for coding agents"
license = "MIT"
+4 -2
View File
@@ -52,8 +52,10 @@ compatible fixes and the minor for compatible features. While the major is zero,
use a minor bump for breaking changes and document how to upgrade. After `1.0.0`,
bump the major for breaking changes.
1. Set `package.version` in `Cargo.toml` and run `cargo check` to refresh
`Cargo.lock`. The Nix package reads the version from `Cargo.toml`.
1. In a release pull request of its own, once the changes for it have merged, set
`package.version` in `Cargo.toml` and run `cargo check` to refresh `Cargo.lock`. Feature and
fix pull requests leave the version alone. The Nix package reads the version from
`Cargo.toml`.
2. After the release commit lands on `main` and passes CI, tag it `v<version>` and
push the tag. Keep published tags fixed.
3. Update the `slop-broker` input in nixfiles to `ref=refs/tags/v<version>` and run
+5
View File
@@ -342,6 +342,7 @@ enum Operation {
enum Destination {
Node(NodeName), // a target
Container { node: NodeName, name: ContainerName }, // `node.container-<name>`
Host { user: UserName, host: HostName, port: u16 }, // `--host`
}
@@ -613,6 +614,10 @@ none can be read as an option, and `--` comes before the hostname.
- ssh keeps the first value of an option. `nix copy` to `ssh://` adds `PermitLocalCommand=yes` and
waits for `echo started`, so the broker's `PermitLocalCommand=no` would hang it forever (see
`copy_options`).
- A copy from the builder's store to a node has one `NIX_SSHOPTS` for both connections.
The builder's store URL therefore carries its port and key (`ssh-ng://user@host:port?ssh-key=`):
Nix puts them after `NIX_SSHOPTS`, and for `-p` the last value wins (see
`DeployConfig::builder_store`).
- A tokio program that reads stdin can't return from `main` while that read blocks; the builder
worker calls `std::process::exit` after writing its result.
- Session variables from home-manager only reach shells started after the next login
+24 -4
View File
@@ -102,7 +102,8 @@ and `slop-approve`. How the code does it is in
- **One connection per request**, carrying in order:
1. the request;
2. the operation's stdin, only after approval and only for operations that read it (`ssh`
carries its stdin in the request instead, below);
carries its stdin in the request instead, below). The broker drops stdin an operation
doesn't read, and treats a requester sending more than 1 MiB as gone;
3. its stdout and stderr;
4. a final message with the exit status and any structured result.
@@ -195,8 +196,8 @@ own fields. The module and the broker refuse any other operation or field.
| Operation | Fields rules can match |
|---|---|
| `query` (`status`, `logs`, `failed`) | `target` (a node), or `host` and `port` (`--host`); `query` |
| `ssh` | `target`, or `host` and `port` |
| `query` (`status`, `logs`, `failed`) | `target` (a node) and `container` (only for a container on it), or `host` and `port` (`--host`); `query` |
| `ssh` | `target` and `container`, or `host` and `port` |
| `deploy` | `node`, `profile`, `mode` (`switch` or `boot`), `commit`; checked per target, and the strictest answer applies |
| `builder` | `commit`, `on_branch` (`true` or `false`), `for` (`deploy` or `build`) |
| `build` | `attr`, `commit`; checked per attribute |
@@ -340,10 +341,25 @@ ciphertext they were sent, never values.
- **Targets** are the deploy-rs nodes on the main branch, by name, so a new box needs a commit
there rather than a new broker config. SSH therefore needs deploys set up.
- The builder evaluates each node's `hostname`, `sshUser`, `sshOpts` and `sudo`, falling back to
the flake-wide `sshUser` and `sudo`. Only the protected branch's Nix runs, as for secrets.
the flake-wide `sshUser` and `sudo`, and its profiles' names. Only the protected branch's Nix
runs, as for secrets.
- The broker looks them up again when they're stale, or when a request names a node it doesn't
know.
- `--host` covers boxes outside them (OpenWrt, switches) with an explicit `user@host` and port.
- **Containers** are targets too, as `node.container-<name>`, the same name `slop deploy` takes:
a node's `container-<name>` profiles say which containers it has, and `<name>` is the machine
name `systemd-machined` knows the container by (a NixOS container, or any `systemd-nspawn`
machine).
- The broker reaches the node as usual and runs the command there as root, through the node's
`sudo`: `systemctl --machine`, `journalctl --machine` and, for `ssh`, `systemd-run --machine
--pipe --wait` with `/bin/sh -l -c <line>`. Stdin, output and the exit status pass through.
- Approvers see the container and the remote command, including `sudo … root` and
`--machine`.
- A container's scope has the node as `target` and the container as `container`. Rules for a
node therefore apply to its containers (match `container = "*"` to tell them apart), but a
lease covers only the target it was granted for.
- Commands go to the node's login shell as one string, quoted so that a POSIX shell and `fish`
read the same words.
- **Fixed options.** SSH runs with `-F none`, the key with `IdentitiesOnly`, no agent,
`BatchMode`, no forwarding or local commands, and the broker's own `known_hosts` (new hosts are
accepted, changed ones refused).
@@ -386,6 +402,10 @@ broker runs it over SSH.
Nix daemon.
- Only `git` gets the repository key, never the evaluator.
- Build logs stream to the agent. One build runs at a time.
- The broker reads built paths from the builder's store, `nix copy --from ssh-ng://` its
user with the broker's key; the builder key's forced command serves `nix-daemon --stdio`
for that. So the builder can be on another box with a store of its own, and nothing lands
in the broker's store. The builder never holds a key to the nodes or the cache.
4. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does,
and compares each profile with the one installed.
- Nodes substitute what the caches have; progress streams to the agent.
+3 -3
View File
@@ -37,8 +37,8 @@ let
# The operations a policy can allow, as the broker names them (`OpName`), and the scope fields
# their rules can match (`OpName::fields`)
opFields = {
query = [ "target" "host" "port" "query" ];
ssh = [ "target" "host" "port" ];
query = [ "target" "container" "host" "port" "query" ];
ssh = [ "target" "container" "host" "port" ];
deploy = [ "node" "profile" "mode" "commit" ];
builder = [ "commit" "on_branch" "for" ];
build = [ "attr" "commit" ];
@@ -169,7 +169,7 @@ in
hostname = mkOpt' str "localhost" "Box running the builder (`services.slop-broker-builder`).";
user = mkOpt' str "slop-broker-build" "The builder's user.";
sshOpts = mkOpt' (listOf str) [ "-p" (toString (head config.services.openssh.ports)) ]
"Extra SSH arguments for reaching the builder.";
"SSH arguments for reaching the builder: only `-p <port>`, which goes in the store URL built paths are copied from.";
};
};
+38 -1
View File
@@ -18,7 +18,8 @@ let
outputs = _: {
deploy.sshUser = "deploy";
deploy.nodes = {
local.hostname = "localhost";
# Profiles aren't built here; their names say which containers there are
local = { hostname = "localhost"; profiles = { system = { }; container-web = { }; }; };
other.hostname = "localhost";
denied.hostname = "localhost";
};
@@ -42,6 +43,13 @@ pkgs.testers.runNixOSTest {
users.users.reviewer.isNormalUser = true;
users.users.agent.isNormalUser = true;
environment.systemPackages = [ pkgs.util-linux ];
# Container commands go through `systemd-machined`, as root
security.sudo.extraRules = [ { users = [ "deploy" ]; commands = [ { command = "ALL"; options = [ "NOPASSWD" ]; } ]; } ];
containers.web = {
autoStart = true;
config.system.stateVersion = lib.trivial.release;
};
virtualisation.memorySize = 2048;
programs.ssh.extraConfig = ''
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
@@ -127,6 +135,28 @@ pkgs.testers.runNixOSTest {
out = machine.succeed(f"su agent -c \"{env} slop requests\"")
assert "ssh" in out and "lease" in out, out
# Containers: queries run without asking, as for nodes; ssh asks again, since the lease is
# for the host
machine.wait_for_unit("container@web.service")
out = machine.succeed(f"su agent -c \"{env} slop status local.container-web systemd-journald.service\"")
assert "systemd-journald.service" in out, out
out = machine.succeed(f"su agent -c \"{env} slop failed local.container-web\"")
print(out)
out = machine.succeed(f"su agent -c \"{env} slop logs local.container-web systemd-journald.service -n 5\"")
print(out)
status, out = machine.execute(f"su agent -c \"{env} slop failed local.container-nope\" 2>&1")
assert status == 125 and "unknown container local.container-nope" in out, (status, out)
status, out = machine.execute(f"su agent -c \"{env} slop failed local.system\" 2>&1")
assert status == 125 and "only containers" in out, (status, out)
machine.execute(f"echo from stdin | su agent -c \"{env} slop ssh local.container-web -- 'cat; echo in \\$(hostname) as \\$(whoami); exit 3'; echo exit \\$?\" > /tmp/out5 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh local.container-web'")
machine.succeed("su reviewer -c 'slop-approve once'")
machine.wait_until_succeeds("grep -q 'exit 3' /tmp/out5")
out = machine.succeed("cat /tmp/out5")
print(out)
assert "from stdin" in out and "in web as root" in out, out
# Unknown nodes are named plainly; usage errors exit 125 like other refusals
status, out = machine.execute(f"su agent -c \"{env} slop ssh nope -- true\" 2>&1")
assert status == 125 and "unknown node nope;" in out, (status, out)
@@ -164,6 +194,13 @@ pkgs.testers.runNixOSTest {
machine.succeed("su reviewer -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve once'")
machine.wait_until_succeeds("grep -q 'remote approval' /tmp/out4")
# A builder with a store of its own serves it to the broker's key as `nix-daemon --stdio`
machine.succeed("install -m600 /etc/slop-broker-test/key /root/builder-key")
system = machine.succeed("readlink -f /run/current-system").strip()
store = "ssh-ng://slop-broker-build@localhost:22?ssh-key=/root/builder-key"
out = machine.succeed(f"nix --extra-experimental-features nix-command path-info --store '{store}' {system}")
assert out.strip() == system, out
audit = machine.succeed("su reviewer -c 'slop-approve log'")
print(audit)
assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit
+4
View File
@@ -34,6 +34,10 @@ applies a policy, and asks a human to approve most requests.
- Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a
human.
- Every box command (`status`, `logs`, `failed`, `ssh`) also takes a container instead of a node,
as `<node>.container-<name>` (the name `slop deploy` takes, such as `host.container-web`). It
runs in the container as root, and `slop ssh` runs the command with `/bin/sh -l`. A lease for
the node doesn't cover its containers.
- Every box command also takes `--host <user>@<host> [-p <port>]` instead of a node, for hosts
outside the deploy nodes.
- `--json` prints structured results (such as `slop requests`) as JSON.
+7 -1
View File
@@ -47,7 +47,7 @@ struct Cli {
#[derive(Args)]
struct Target {
/// Deploy node, or user@host with --host.
/// Deploy node, a container on one (node.container-<name>), or user@host with --host.
target: String,
/// Treat TARGET as user@host instead of a deploy node.
#[arg(long)]
@@ -63,6 +63,12 @@ impl Target {
if self.port.is_some() {
bail!("--port needs --host; deploy nodes use their configured port");
}
if let Some((node, profile)) = self.target.split_once('.') {
let name = profile.strip_prefix("container-").with_context(|| {
format!("{}: only containers can be named after a node (node.container-<name>)", self.target)
})?;
return Ok(Destination::Container { node: parse(node)?, name: parse(name)? });
}
return Ok(Destination::Node(parse::<NodeName>(&self.target)?));
}
+15 -2
View File
@@ -79,6 +79,9 @@ pub struct Node {
/// 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)]
@@ -281,11 +284,19 @@ async fn call<R: DeserializeOwned>(
// The builder's side
/// The forced command: one build per connection, one at a time.
/// The forced command: one build per connection, one at a time. A broker whose builder has a
/// store of its own also reads built paths from it, as `nix-daemon --stdio` (`ssh-ng`).
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)?;
if std::env::var("SSH_ORIGINAL_COMMAND").is_ok_and(|c| c == "nix-daemon --stdio") {
use std::os::unix::process::CommandExt;
let daemon = config.path.iter().map(|d| d.join("nix-daemon")).find(|p| p.exists());
let daemon = daemon.context("no nix-daemon in the builder's path")?;
return Err(std::process::Command::new(daemon).arg("--stdio").exec()).context("running nix-daemon");
}
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.
@@ -594,7 +605,8 @@ async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) ->
async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
let commit = branch_tip(config).await?;
let cache = config.directory.join("deploy-nodes");
let file = cache.join(format!("{commit}.json"));
// 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)? });
}
@@ -606,6 +618,7 @@ async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
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")
+64 -1
View File
@@ -124,6 +124,32 @@ pub struct DeployConfig {
pub cache: PathBuf,
}
impl DeployConfig {
/// The builder's store, which built paths are copied from, as a `nix` store URL reached with
/// the broker's `key`; the builder's forced command serves it. That works whether the builder
/// is on this box (the same store) or another. The port is always given: it comes after
/// `NIX_SSHOPTS`, so a node's `-p` can't send the builder's connection elsewhere when one copy
/// uses both.
pub fn builder_store(&self, key: &Path) -> anyhow::Result<String> {
let builder = &self.builder;
let port: u16 = match builder.ssh_opts.as_slice() {
[] => 22,
[flag, port] if flag == "-p" => port.parse().context("the builder's port")?,
_ => anyhow::bail!("the builder's ssh_opts can only set a port (-p <port>)"),
};
let host =
if builder.hostname.contains(':') { format!("[{}]", builder.hostname) } else { builder.hostname.clone() };
let key = credential(key);
let key = key.to_str().context("the SSH key's path isn't UTF-8")?;
anyhow::ensure!(
!key.contains(|c: char| c.is_whitespace() || "?&#%".contains(c)),
"the SSH key's path can't go in a store URL: {key}"
);
Ok(format!("ssh-ng://{}@{host}:{port}?ssh-key={key}", builder.user))
}
}
/// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose
/// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose
/// builder it uses.
@@ -210,6 +236,9 @@ pub struct SshTarget {
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`); nodes only.
#[serde(default = "default_sudo")]
pub sudo: String,
/// The containers on it that requests can name; nodes only.
#[serde(default)]
pub containers: std::collections::BTreeSet<String>,
}
/// deploy-rs's default.
@@ -309,6 +338,9 @@ impl Config {
self.ssh.is_none() || self.deploy.is_some(),
"ssh needs deploy, whose builder reads the main branch's deploy-rs nodes"
);
if let (Some(ssh), Some(deploy)) = (&self.ssh, &self.deploy) {
deploy.builder_store(&ssh.key)?;
}
Ok(())
}
@@ -386,7 +418,38 @@ mod tests {
let rules = &mut misspelt.policies.get_mut("agent").unwrap().ops.get_mut(&OpName::Ssh).unwrap().rules;
rules[0].matches = BTreeMap::from([("node".to_owned(), "river".to_owned())]);
let error = misspelt.validate().unwrap_err().to_string();
assert!(error.contains("ssh rules can't match \"node\"; its fields are target, host, port"), "{error}");
assert!(
error.contains("ssh rules can't match \"node\"; its fields are target, container, host, port"),
"{error}"
);
}
#[test]
fn builder_stores() {
let builder = |hostname: &str, ssh_opts: &[&str]| SshTarget {
hostname: hostname.into(),
user: "build".into(),
ssh_opts: ssh_opts.iter().map(|o| o.to_string()).collect(),
sudo: default_sudo(),
containers: Default::default(),
};
let deploy = |builder| DeployConfig { builder, nix: "/nix".into(), cache: "/cache".into() };
let key = Path::new("/run/key");
assert_eq!(
deploy(builder("localhost", &["-p", "2222"])).builder_store(key).unwrap(),
"ssh-ng://build@localhost:2222?ssh-key=/run/key"
);
assert_eq!(
deploy(builder("builder.example", &[])).builder_store(key).unwrap(),
"ssh-ng://build@builder.example:22?ssh-key=/run/key"
);
assert_eq!(
deploy(builder("fd00::1", &["-p", "22"])).builder_store(key).unwrap(),
"ssh-ng://build@[fd00::1]:22?ssh-key=/run/key"
);
assert!(deploy(builder("b", &["-o", "ProxyJump=x"])).builder_store(key).is_err());
assert!(deploy(builder("b", &[])).builder_store(Path::new("/run/a key")).is_err());
}
#[test]
+1 -1
View File
@@ -32,7 +32,7 @@ impl Output {
pub struct Io {
/// Chunks of the requester's stdin, which it sends after approval for operations that ask for
/// it; closed at EOF.
pub stdin: mpsc::Receiver<Vec<u8>>,
pub stdin: mpsc::UnboundedReceiver<Vec<u8>>,
pub out: Output,
/// Cancelled when the requester disconnects.
pub cancel: CancellationToken,
+14 -3
View File
@@ -70,7 +70,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?;
let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect();
let sizes = closure_sizes(deploy, &paths, &io.cancel).await?;
let sizes = closure_sizes(ssh, deploy, &paths, &io.cancel).await?;
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
let mut detail = Detail::new();
@@ -135,10 +135,13 @@ fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, pat
let options = nix_ssh_options(ssh::options_with_key(ssh, &cache.key), &cache.ssh_opts);
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
let from = deploy.builder_store(&ssh.key)?;
let mut command = nix(deploy, ssh.ssh.parent());
command
.env("NIX_SSHOPTS", options.join(" "))
.args(["--extra-experimental-features", "nix-command", "copy", "--no-check-sigs"])
.args(["--from", &from])
.arg("--to")
.arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname))
.args(paths);
@@ -156,14 +159,17 @@ fn nix(deploy: &DeployConfig, ssh_directory: Option<&Path>) -> Command {
command
}
/// Each path's closure size, human-readable, from the local store.
/// Each path's closure size, human-readable, from the builder's store.
async fn closure_sizes(
ssh: &SshConfig,
deploy: &DeployConfig,
paths: &[&str],
cancel: &CancellationToken,
) -> Result<Vec<(String, String)>> {
let mut command = nix(deploy, None);
let mut command = nix(deploy, ssh.ssh.parent());
command.env("NIX_SSHOPTS", nix_ssh_options(ssh::options(ssh), &[]).join(" "));
command.args(["--extra-experimental-features", "nix-command", "path-info", "--closure-size", "--human-readable"]);
command.args(["--store", &deploy.builder_store(&ssh.key)?]);
command.args(paths);
let (exit, stdout, stderr) = exec::capture(command, cancel).await?;
@@ -219,6 +225,11 @@ mod tests {
assert!(options.contains("-i /cache-key") && options.ends_with("-p 2222"), "{options}");
assert!(!options.contains("PermitLocalCommand=no"), "{options}");
assert!(args(&copy).contains(&"ssh-ng://harmonia@object.example".to_owned()));
// From the builder's store, with the broker's key
let copy = args(&copy);
let from = copy.iter().position(|a| a == "--from").unwrap();
assert_eq!(copy[from + 1], "ssh-ng://deploy@river.example.org:2222?ssh-key=/key");
}
#[test]
+3
View File
@@ -183,6 +183,8 @@ async fn copy(
let options = copy_options(ssh, node)?;
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
let from = deploy.builder_store(&ssh.key)?;
let ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default();
let mut command = Command::new(&deploy.nix);
command
@@ -198,6 +200,7 @@ async fn copy(
"--no-check-sigs",
"--substitute-on-destination",
])
.args(["--from", &from])
.arg("--to")
.arg(format!("ssh://{}@{}", target.user, target.hostname))
.args(profiles.iter().map(|p| &p.path));
+35 -16
View File
@@ -7,7 +7,7 @@ use crate::builder::Description;
use crate::detail::{Detail, Field, Section, Tone};
use crate::exec::Io;
use crate::policy::{Limits, OpName};
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
use crate::proto::{Destination, LeaseSummary, OpResult, Operation, PendingSummary};
use crate::server::Broker;
use crate::types::CommitId;
@@ -105,7 +105,11 @@ fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
ssh::check(config, destination)?;
let summary = format!("ssh {}", ssh::describe(destination));
let detail = ssh::detail(command, stdin.as_deref())?;
let mut detail = ssh::detail(command, stdin.as_deref())?;
if let Destination::Container { node, name } = destination {
let how = format!("as root, by /bin/sh -l in the container (systemd-run --machine={name} on {node})");
detail.field(Field::new("Runs", how));
}
Ok(Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation))
}
Operation::Query { destination, query } => {
@@ -115,7 +119,7 @@ fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
scope.insert("query".into(), Value::from(query::name(query)));
let summary = format!("{} on {}", query::name(query), ssh::describe(destination));
let detail = Detail::code("Command", shell_quote(&query::remote_command(query)));
let detail = Detail::code("Command", shell_quote(&query::remote_command(config, destination, query)?));
Ok(Parsed::new(OpName::Query, scope, summary, detail, operation))
}
Operation::Deploy { .. } => deploy::plan(broker, operation),
@@ -244,20 +248,34 @@ pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed,
}
}
/// Quotes words for a POSIX shell, for showing commands and for remote commands built here.
/// Quotes words for a POSIX shell or `fish`, for showing commands and for remote commands built
/// here. `fish` reads `\\` and `\'` as escapes even in single quotes, so quotes and backslashes are
/// escaped outside them, which both read the same way.
pub fn shell_quote<S: AsRef<str>>(words: &[S]) -> String {
words
.iter()
.map(|w| {
let w = w.as_ref();
if !w.is_empty() && w.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) {
w.to_owned()
} else {
format!("'{}'", w.replace('\'', r"'\''"))
}
})
.collect::<Vec<_>>()
.join(" ")
words.iter().map(|w| quote_word(w.as_ref())).collect::<Vec<_>>().join(" ")
}
fn quote_word(word: &str) -> String {
if !word.is_empty() && word.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) {
return word.to_owned();
}
let (mut quoted, mut open) = (String::new(), false);
for c in word.chars() {
let escaped = matches!(c, '\'' | '\\');
if escaped == open {
quoted.push('\'');
open = !open;
}
if escaped {
quoted.push('\\');
}
quoted.push(c);
}
if open {
quoted.push('\'');
}
if quoted.is_empty() { "''".into() } else { quoted }
}
/// Text that can't control a terminal, for showing approvers what agents wrote (commit messages,
@@ -320,5 +338,6 @@ mod tests {
#[test]
fn quotes_for_the_shell() {
assert_eq!(shell_quote(&["systemctl", "status", "a b", "it's", ""]), r"systemctl status 'a b' 'it'\''s' ''");
assert_eq!(shell_quote(&[r"a\\b", "'", r"\x2d"]), r"'a'\\\\'b' \' \\'x2d'");
}
}
+41 -7
View File
@@ -1,8 +1,9 @@
//! Fixed read-only queries on boxes over SSH. The broker builds and quotes the remote command
//! from validated values, so policy can safely approve these by itself.
//! Fixed read-only queries on boxes and their containers over SSH. The broker builds and quotes
//! the remote command from validated values, so policy can safely approve these by itself.
use anyhow::Result;
use super::{shell_quote, ssh};
use crate::config::SshConfig;
use crate::exec::{self, Io};
use crate::proto::{Destination, Query};
use crate::server::Broker;
@@ -15,7 +16,20 @@ pub fn name(query: &Query) -> &'static str {
}
}
pub fn remote_command(query: &Query) -> Vec<String> {
/// The command to run on the destination's box. A container's runs on its host, as root, with
/// `--machine`.
pub fn remote_command(config: &SshConfig, destination: &Destination, query: &Query) -> Result<Vec<String>> {
match destination {
Destination::Container { node, name } => {
let mut words = command(query);
words.insert(1, format!("--machine={name}"));
ssh::as_root(config, node, words)
}
_ => Ok(command(query)),
}
}
fn command(query: &Query) -> Vec<String> {
let mut words: Vec<String> = match query {
Query::Status { .. } => vec!["systemctl".into(), "status".into(), "--no-pager".into()],
Query::Failed => vec!["systemctl".into(), "list-units".into(), "--failed".into(), "--no-pager".into()],
@@ -38,7 +52,7 @@ pub fn remote_command(query: &Query) -> Vec<String> {
pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
let config = broker.targets.ssh()?;
// One quoted string, so the remote login shell (POSIX or fish) sees exactly these words.
let remote = [shell_quote(&remote_command(query))];
let remote = [shell_quote(&remote_command(&config, destination, query)?)];
exec::run(ssh::command(&config, destination, &remote)?, io, None).await
}
@@ -55,11 +69,31 @@ mod tests {
since: Some("2026-01-31 12:00".parse().unwrap()),
};
assert_eq!(
shell_quote(&remote_command(&logs)),
shell_quote(&command(&logs)),
"journalctl --no-pager --output=short-iso --lines=50 '--since=2026-01-31 12:00' --unit=nginx.service"
);
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
assert_eq!(shell_quote(&remote_command(&status)), "systemctl status --no-pager -- nginx.service");
assert_eq!(shell_quote(&remote_command(&Query::Failed)), "systemctl list-units --failed --no-pager");
assert_eq!(shell_quote(&command(&status)), "systemctl status --no-pager -- nginx.service");
assert_eq!(shell_quote(&command(&Query::Failed)), "systemctl list-units --failed --no-pager");
}
#[test]
fn container_commands_run_on_the_host_as_root() {
let config = ssh::tests::config();
let node = Destination::Node("river".parse().unwrap());
let web = Destination::Container { node: "river".parse().unwrap(), name: "web".parse().unwrap() };
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
assert_eq!(shell_quote(&remote_command(&config, &node, &status).unwrap()), shell_quote(&command(&status)));
assert_eq!(
shell_quote(&remote_command(&config, &web, &status).unwrap()),
"doas -u root systemctl --machine=web status --no-pager -- nginx.service"
);
let logs =
Query::Logs { unit: "nginx.service".parse().unwrap(), lines: Lines::try_from(5).unwrap(), since: None };
assert_eq!(
shell_quote(&remote_command(&config, &web, &logs).unwrap()),
"doas -u root journalctl --machine=web --no-pager --output=short-iso --lines=5 --unit=nginx.service"
);
}
}
+83 -7
View File
@@ -1,5 +1,5 @@
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit
//! `user@host`s.
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes, containers on
//! them, or explicit `user@host`s.
use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};
use tokio::process::Command;
@@ -9,21 +9,29 @@ use crate::detail::{Detail, Field, Section};
use crate::exec::{self, Io};
use crate::proto::{Destination, MAX_SSH_SHOWN};
use crate::server::Broker;
use crate::types::Arg;
use crate::types::{Arg, ContainerName};
/// Fails if `destination` names a target the broker doesn't know.
pub fn check(config: &SshConfig, destination: &Destination) -> Result<()> {
if let Destination::Node(node) = destination
if let Some(node) = destination.node()
&& !config.targets.contains_key(&**node)
{
bail!("unknown node {node}; nodes are the main branch's deploy-rs nodes, and --host reaches other boxes");
}
if let Destination::Container { node, name } = destination
&& !config.targets[&**node].containers.contains(&**name)
{
bail!("unknown container {node}.container-{name}; containers are a node's container-* deploy-rs profiles");
}
Ok(())
}
/// What an approval covers. A container's has the node as `target`, so rules for a node apply
/// to its containers too, but leases for one don't cover the other.
pub fn scope(destination: &Destination) -> Map<String, Value> {
let value = match destination {
Destination::Node(node) => json!({ "target": node }),
Destination::Container { node, name } => json!({ "target": node, "container": name }),
Destination::Host { user, host, port } => json!({ "host": format!("{user}@{host}"), "port": port.get() }),
};
value.as_object().unwrap().clone()
@@ -32,10 +40,43 @@ pub fn scope(destination: &Destination) -> Map<String, Value> {
pub fn describe(destination: &Destination) -> String {
match destination {
Destination::Node(node) => node.to_string(),
Destination::Container { node, name } => format!("{node}.container-{name}"),
Destination::Host { user, host, port } => format!("{user}@{host} port {port} (host)"),
}
}
/// The words that run `words` as root on a node: its `sudo` (deploy-rs's, such as `sudo -u`)
/// and `root`. Commands for its containers go through `systemd-machined`, which needs root.
pub fn as_root(config: &SshConfig, node: &str, words: impl IntoIterator<Item = String>) -> Result<Vec<String>> {
let mut all: Vec<String> = target(config, node)?.sudo.split_whitespace().map(Into::into).collect();
all.push("root".into());
all.extend(words);
Ok(all)
}
/// The command on the host that runs `line` in container `name` as root, with a login shell
/// the way `ssh` runs it on a node: stdin, output and the exit status pass through.
pub fn container_shell(config: &SshConfig, node: &str, name: &ContainerName, line: &str) -> Result<Vec<String>> {
let mut words: Vec<String> = [
"systemd-run",
&format!("--machine={name}"),
"--quiet",
"--wait",
"--collect",
"--pipe",
"--expand-environment=no",
"--",
"/bin/sh",
"-l",
]
.map(Into::into)
.into();
if !line.is_empty() {
words.extend(["-c".into(), line.into()]);
}
as_root(config, node, words)
}
/// What approvers see: the line the remote shell runs and all of its stdin, in full, since nothing
/// else reaches the box. Requests too long to show whole are refused.
pub fn detail(command: &[Arg], stdin: Option<&[u8]>) -> Result<Detail> {
@@ -107,7 +148,7 @@ pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, rem
command.arg("-T").args(options(config));
match destination {
Destination::Node(node) => {
Destination::Node(node) | Destination::Container { node, .. } => {
let target = target(config, node)?;
command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]);
}
@@ -144,7 +185,16 @@ pub async fn execute(
io: &mut Io,
) -> Result<i32> {
let config = broker.targets.ssh()?;
exec::run(command(&config, destination, remote)?, io, Some(stdin.unwrap_or_default())).await
let command = match destination {
Destination::Container { node, name } => {
// `ssh` joins the words with spaces; so does this, and the container's shell runs it.
let line = remote.iter().map(|w| &**w).collect::<Vec<_>>().join(" ");
let words = container_shell(&config, node, name, &line)?;
self::command(&config, destination, &[super::shell_quote(&words)])?
}
_ => command(&config, destination, remote)?,
};
exec::run(command, io, Some(stdin.unwrap_or_default())).await
}
#[cfg(test)]
@@ -161,15 +211,41 @@ pub(crate) mod tests {
user: "deploy".into(),
ssh_opts: vec!["-p".into(), "2222".into()],
sudo: "doas -u".into(),
containers: ["web".to_owned()].into(),
},
);
SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets }
}
fn container(node: &str, name: &str) -> Destination {
Destination::Container { node: node.parse().unwrap(), name: name.parse().unwrap() }
}
#[test]
fn unknown_nodes_are_refused() {
fn unknown_nodes_and_containers_are_refused() {
assert!(check(&config(), &Destination::Node("river".parse().unwrap())).is_ok());
assert!(check(&config(), &Destination::Node("sfh".parse().unwrap())).is_err());
assert!(check(&config(), &container("river", "web")).is_ok());
assert!(check(&config(), &container("river", "db")).is_err());
assert!(check(&config(), &container("sfh", "web")).is_err());
}
#[test]
fn containers_have_their_own_scope() {
assert_eq!(Value::Object(scope(&container("river", "web"))), json!({ "target": "river", "container": "web" }));
assert_eq!(describe(&container("river", "web")), "river.container-web");
}
#[test]
fn container_commands_run_as_root_through_systemd_run() {
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "echo $HOME").unwrap();
assert_eq!(
super::super::shell_quote(&words),
"doas -u root systemd-run --machine=web --quiet --wait --collect --pipe --expand-environment=no -- /bin/sh \
-l -c 'echo $HOME'"
);
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "").unwrap();
assert_eq!(words.last().unwrap(), "-l");
}
#[test]
+2 -2
View File
@@ -53,8 +53,8 @@ impl OpName {
/// targets, a build's attributes), that scope's fields.
pub fn fields(self) -> &'static [&'static str] {
match self {
OpName::Query => &["target", "host", "port", "query"],
OpName::Ssh => &["target", "host", "port"],
OpName::Query => &["target", "container", "host", "port", "query"],
OpName::Ssh => &["target", "container", "host", "port"],
OpName::Deploy => &["node", "profile", "mode", "commit"],
OpName::Builder => &["commit", "on_branch", "for"],
OpName::Build => &["attr", "commit"],
+19 -3
View File
@@ -16,12 +16,12 @@ use tokio_util::codec::{Framed, LengthDelimitedCodec};
use crate::audit::Record;
use crate::queue::{Decision, PendingInfo};
use crate::types::{
Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since,
UnitName, UserName,
Arg, CommitId, ContainerName, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath,
Since, UnitName, UserName,
};
/// Bumped on any incompatible change; the broker refuses other versions.
pub const PROTOCOL_VERSION: u32 = 2;
pub const PROTOCOL_VERSION: u32 = 3;
pub const MAX_MESSAGE: usize = 1 << 20;
/// Bytes of an `ssh` request's command and stdin together: all of it is shown to approvers.
pub const MAX_SSH_SHOWN: usize = 32 * 1024;
@@ -196,6 +196,12 @@ impl GenKind {
pub enum Destination {
/// A configured target (normally a deploy-rs node), with its configured user and options.
Node(NodeName),
/// A container on a node, reached through the node's host: one of the node's
/// `container-<name>` deploy-rs profiles.
Container {
node: NodeName,
name: ContainerName,
},
Host {
user: UserName,
host: HostName,
@@ -203,6 +209,16 @@ pub enum Destination {
},
}
impl Destination {
/// The node it's reached through, if any.
pub fn node(&self) -> Option<&NodeName> {
match self {
Destination::Node(node) | Destination::Container { node, .. } => Some(node),
Destination::Host { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Query {
+19 -4
View File
@@ -23,6 +23,10 @@ use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerM
use crate::queue::{NewRequest, Outcome, Queue, new_id};
use crate::targets::Targets;
/// The most stdin a requester may send. Operations that read it have their own, smaller limits;
/// a requester sending more than this is treated as gone.
const MAX_STDIN: usize = 1 << 20;
pub struct Broker {
pub config: Config,
pub queue: Queue,
@@ -123,18 +127,25 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
};
// After the request, the requester only sends stdin; anything else, or the connection
// closing, means it's gone.
// closing, means it's gone. The reader never waits on the operation, so it always notices:
// stdin is buffered up to a limit, and dropped once the operation can't take it.
let cancel = CancellationToken::new();
let (stdin_tx, stdin_rx) = mpsc::channel(16);
let (stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let reader = {
let cancel = cancel.clone();
tokio::spawn(async move {
let mut stdin_tx = Some(stdin_tx);
let (mut stdin_tx, mut total) = (Some(stdin_tx), 0);
while let Some(Ok(frame)) = source.next().await {
match decode::<ClientMessage>(&frame) {
Ok(ClientMessage::Stdin(data)) => {
if let Some(tx) = &stdin_tx {
let _ = tx.send(data).await;
total += data.len();
if total > MAX_STDIN {
break;
}
if tx.send(data).is_err() {
stdin_tx = None;
}
}
}
Ok(ClientMessage::StdinEnd) => stdin_tx = None,
@@ -182,6 +193,10 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
}
};
if !parsed.stdin {
io.stdin.close();
}
// Built-in operations only read the broker's own state, so they aren't logged.
let builtin = parsed.op.builtin();
let log = |event| {
+33 -8
View File
@@ -46,7 +46,11 @@ impl Targets {
}
let mut looked = self.looked.lock().await;
let known = self.ssh().is_ok_and(|ssh| names.iter().all(|n| ssh.targets.contains_key(*n)));
let known = self.ssh().is_ok_and(|ssh| {
names.iter().all(|(node, container)| {
ssh.targets.get(*node).is_some_and(|t| container.is_none_or(|c| t.containers.contains(c)))
})
});
let due = match *looked {
None => true,
Some((at, succeeded)) => {
@@ -82,16 +86,29 @@ impl Targets {
}
}
/// The node names an operation reaches.
fn nodes(operation: &Operation) -> Vec<&str> {
/// The nodes an operation reaches, each with the container on it it names, if any.
fn nodes(operation: &Operation) -> Vec<(&str, Option<&str>)> {
match operation {
Operation::Ssh { destination: Destination::Node(node), .. }
| Operation::Query { destination: Destination::Node(node), .. } => vec![&**node],
Operation::Deploy { targets, .. } => targets.iter().map(|t| t.node()).collect(),
Operation::Ssh { destination, .. } | Operation::Query { destination, .. } => match destination {
Destination::Node(node) => vec![(&**node, None)],
Destination::Container { node, name } => vec![(&**node, Some(&**name))],
Destination::Host { .. } => Vec::new(),
},
Operation::Deploy { targets, .. } => targets.iter().map(|t| (t.node(), None)).collect(),
_ => Vec::new(),
}
}
/// The containers a node's `container-<name>` profiles deploy.
fn containers(profiles: &[String]) -> std::collections::BTreeSet<String> {
profiles
.iter()
.filter_map(|p| p.strip_prefix("container-"))
.filter(|name| name.parse::<crate::types::ContainerName>().is_ok())
.map(Into::into)
.collect()
}
/// The SSH settings with `nodes` as targets. Nodes without an SSH user or with an invalid name are
/// left out, since nothing could reach them.
fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
@@ -102,7 +119,8 @@ fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
}
let Some(user) = node.ssh_user else { continue };
let sudo = node.sudo.unwrap_or_else(default_sudo);
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo });
let containers = containers(&node.profiles);
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo, containers });
}
SshConfig { targets, ..ssh.clone() }
}
@@ -117,6 +135,7 @@ mod tests {
ssh_user: user.map(Into::into),
ssh_opts: vec!["-p".into(), "2222".into()],
sudo: sudo.map(Into::into),
profiles: vec!["system".into(), "container-web".into(), "container--x".into(), "containerx".into()],
}
}
@@ -136,6 +155,7 @@ mod tests {
assert_eq!(ssh.targets["web"].sudo, "doas -u");
assert_eq!(ssh.targets["plain"].sudo, "sudo -u");
assert_eq!(ssh.targets["web"].ssh_opts, ["-p", "2222"]);
assert_eq!(ssh.targets["web"].containers.iter().collect::<Vec<_>>(), ["web"]);
}
#[test]
@@ -145,7 +165,12 @@ mod tests {
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
boot: false,
};
assert_eq!(nodes(&deploy), ["web", "river"]);
assert_eq!(nodes(&deploy), [("web", None), ("river", None)]);
let query = Operation::Query {
destination: Destination::Container { node: "shill".parse().unwrap(), name: "web".parse().unwrap() },
query: crate::proto::Query::Failed,
};
assert_eq!(nodes(&query), [("shill", Some("web"))]);
assert!(nodes(&Operation::Requests).is_empty());
}
}
+14
View File
@@ -68,6 +68,20 @@ validated_string!(
}
);
validated_string!(
/// A container's machine name (as `machinectl` lists it), such as a deploy-rs node's
/// `container-<name>` profile names.
ContainerName,
"container name",
|s| {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 64
&& b[0].is_ascii_alphanumeric()
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
}
);
validated_string!(
/// A remote login name.
UserName,
+75 -3
View File
@@ -57,8 +57,13 @@ fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
// 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 };
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)
}
@@ -261,9 +266,13 @@ async fn stdin_that_cant_be_shown_is_refused() {
}
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, "ssh river");
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:?}");
@@ -362,6 +371,34 @@ async fn disconnecting_kills_the_process() {
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();
@@ -387,6 +424,41 @@ async fn queries_run_a_fixed_quoted_command_without_stdin() {
);
}
#[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();