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>
This commit was merged in pull request #14.
This commit is contained in:
1 parent
00d3c65cfd
commit
4b2c32636e
16 files changed
+350
-55
No files matched your search
@@ -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`
|
||||
}
|
||||
|
||||
|
||||
+18
-3
@@ -196,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 |
|
||||
@@ -341,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).
|
||||
|
||||
@@ -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" ];
|
||||
|
||||
+31
-1
@@ -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)
|
||||
|
||||
@@ -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
@@ -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)?));
|
||||
}
|
||||
|
||||
|
||||
+6
-1
@@ -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)]
|
||||
@@ -594,7 +597,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 +610,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")
|
||||
|
||||
+7
-1
@@ -210,6 +210,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.
|
||||
@@ -386,7 +389,10 @@ 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]
|
||||
|
||||
+35
-16
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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 {
|
||||
|
||||
+33
-8
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
+47
-3
@@ -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:?}");
|
||||
@@ -415,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();
|
||||
|
||||
Reference in new issue
Block a user