ops: Add box queries

`slop status`, `slop logs` and `slop failed` run fixed read-only
commands that the broker builds and quotes from validated values, so a
policy can let them run without asking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-23 00:39:35 +00:00
1 parent 67b11b0c61
commit d71bbb04db
8 files changed
+291 -21

No files matched your search

+11 -1
View File
@@ -27,7 +27,11 @@ pkgs.testers.runNixOSTest {
enable = true;
package = slop-broker;
approvers = [ "reviewer" ];
policies.agent.ops.ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
policies.agent.ops = {
query.action = "auto";
ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
};
requesters.agent = {
vsockCid = 1;
policy = "agent";
@@ -50,6 +54,12 @@ pkgs.testers.runNixOSTest {
status, out = machine.execute(f"su agent -c \"{env} slop ssh denied -- true\" 2>&1")
assert status == 125 and "denied by policy" in out, (status, out)
# Fixed queries run without asking
out = machine.succeed(f"su agent -c \"{env} slop status local sshd.service\"")
assert "sshd.service" in out, out
out = machine.succeed(f"su agent -c \"{env} slop logs local sshd.service -n 5 --since 1h\"")
print(out)
# Ask, approve from a terminal, and see the real ssh run
machine.execute(f"su agent -c \"{env} slop ssh local -- 'echo hi from \\$(whoami)'\" > /tmp/out 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh local'")
+15 -10
View File
@@ -19,20 +19,25 @@ applies a policy, and asks a human to approve most requests.
## Commands
| Command | What it does |
|---|---|
| `slop ssh <node> -- <command>…` | Run a command over SSH on a deploy node, as the node's configured user. |
| `slop ssh --host <user>@<host> [-p <port>] -- <command>…` | The same for a host outside the deploy nodes. |
| `slop requests` | Your pending requests and active leases. |
| Command | What it does | Approval |
|---|---|---|
| `slop status <node> [unit]` | `systemctl status`, of one unit or the whole box | usually none |
| `slop logs <node> <unit> [-n 200] [--since 2h]` | A unit's journal; `--since` takes a duration or a date (`2026-01-31 12:00`) | usually none |
| `slop failed <node>` | Failed units | usually none |
| `slop ssh <node> -- <command>…` | Any command over SSH, as the node's configured user | asks |
| `slop requests` | Your pending requests and active leases | none |
- Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a
human.
- 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.
- The remote command is joined with spaces and run by the remote login shell, as with `ssh`. Boxes
usually use `fish`, so pipe multi-statement scripts through `bash`:
`slop ssh <node> -- bash -s < script.sh`.
- For `slop ssh`, the remote command is joined with spaces and run by the remote login shell, as
with `ssh`. If a box's login shell isn't POSIX (such as `fish`), pipe multi-statement scripts
through `bash`: `slop ssh <node> -- bash -s < script.sh`.
- There is no TTY. Interactive programs won't work; use non-interactive flags (`--no-pager`,
`-y`).
- stdin is forwarded once the request is approved.
- `slop ssh` forwards stdin once the request is approved.
## Don't
+32 -2
View File
@@ -9,10 +9,10 @@ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc;
use slop_broker::proto::{
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, HOST_CID, OpResult, Operation, PROTOCOL_VERSION,
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, HOST_CID, OpResult, Operation, PROTOCOL_VERSION, Query,
Request, ServerMessage, decode, encode, transport,
};
use slop_broker::types::{Arg, HostName, NodeName, UserName};
use slop_broker::types::{Arg, HostName, Lines, NodeName, Since, UnitName, UserName};
/// Exit status when the broker didn't run the operation (denied, expired, invalid or failed).
const NOT_RUN: i32 = 125;
@@ -78,6 +78,29 @@ enum Command {
#[arg(last = true)]
command: Vec<Arg>,
},
/// `systemctl status` on a box, of one unit or overall.
Status {
#[command(flatten)]
target: Target,
unit: Option<UnitName>,
},
/// A unit's journal on a box.
Logs {
#[command(flatten)]
target: Target,
unit: UnitName,
/// Lines to show (1-5000).
#[arg(short = 'n', long, default_value = "200")]
lines: Lines,
/// Start time: a duration back from now (30m, 2h, 1d) or a date (2026-01-31 12:00).
#[arg(long)]
since: Option<Since>,
},
/// Failed units on a box.
Failed {
#[command(flatten)]
target: Target,
},
/// Show your pending requests and active leases.
Requests,
/// Print the guide for agents.
@@ -87,6 +110,13 @@ enum Command {
fn operation(command: Command) -> Result<Operation> {
Ok(match command {
Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command },
Command::Status { target, unit } => {
Operation::Query { destination: target.destination()?, query: Query::Status { unit } }
}
Command::Logs { target, unit, lines, since } => {
Operation::Query { destination: target.destination()?, query: Query::Logs { unit, lines, since } }
}
Command::Failed { target } => Operation::Query { destination: target.destination()?, query: Query::Failed },
Command::Requests => Operation::Requests,
Command::Guide => unreachable!(),
})
+22
View File
@@ -8,6 +8,7 @@ use crate::policy::Limits;
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
use crate::server::Broker;
pub mod query;
pub mod ssh;
pub struct Parsed {
@@ -64,6 +65,24 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
operation,
})
}
Operation::Query { destination, query } => {
let config = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
ssh::check(config, destination)?;
let mut scope = ssh::scope(destination);
scope.insert("query".into(), Value::from(query::name(query)));
Ok(Parsed {
op: "query",
scope,
summary: format!("{} on {}", query::name(query), ssh::describe(destination)),
detail: format!("Command: {}", shell_quote(&query::remote_command(query))),
limits: Limits::default(),
sensitive: false,
stdin: false,
builtin: false,
operation,
})
}
Operation::Requests => Ok(Parsed {
op: "requests",
scope: Map::new(),
@@ -83,6 +102,9 @@ pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut
Operation::Ssh { destination, command } => {
ssh::execute(broker, &destination, &command, io).await.map(Into::into)
}
Operation::Query { destination, query } => {
query::execute(broker, &destination, &query, io).await.map(Into::into)
}
Operation::Requests => {
let pending = broker
.queue
+65
View File
@@ -0,0 +1,65 @@
//! 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.
use anyhow::Result;
use super::{shell_quote, ssh};
use crate::exec::{self, Io};
use crate::proto::{Destination, Query};
use crate::server::Broker;
pub fn name(query: &Query) -> &'static str {
match query {
Query::Status { .. } => "status",
Query::Logs { .. } => "logs",
Query::Failed => "failed",
}
}
pub fn remote_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()],
Query::Logs { .. } => vec!["journalctl".into(), "--no-pager".into(), "--output=short-iso".into()],
};
match query {
Query::Status { unit: Some(unit) } => words.extend(["--".into(), unit.to_string()]),
Query::Logs { unit, lines, since } => {
words.push(format!("--lines={}", lines.get()));
if let Some(since) = since {
words.push(format!("--since={}", since.journalctl()));
}
words.push(format!("--unit={unit}"));
}
_ => {}
}
words
}
pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
let config = broker.config.ssh.as_ref().unwrap();
// One quoted string, so the remote login shell (POSIX or fish) sees exactly these words.
let remote = [shell_quote(&remote_command(query))];
exec::run(ssh::command(config, destination, &remote), io, false).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Lines;
#[test]
fn commands() {
let logs = Query::Logs {
unit: "nginx.service".parse().unwrap(),
lines: Lines::try_from(50).unwrap(),
since: Some("2026-01-31 12:00".parse().unwrap()),
};
assert_eq!(
shell_quote(&remote_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");
}
}
+20 -3
View File
@@ -15,7 +15,7 @@ use tokio_util::codec::{Framed, LengthDelimitedCodec};
use crate::audit::Record;
use crate::queue::{Decision, PendingInfo};
use crate::types::{Arg, HostName, NodeName, UserName};
use crate::types::{Arg, HostName, Lines, NodeName, Since, UnitName, UserName};
/// Bumped on any incompatible change; the broker refuses other versions.
pub const PROTOCOL_VERSION: u32 = 1;
@@ -46,6 +46,8 @@ pub struct Request {
pub enum Operation {
/// A command over SSH, joined with spaces and run by the remote shell (as `ssh` does).
Ssh { destination: Destination, command: Vec<Arg> },
/// A fixed read-only query, run over SSH with a command the broker builds.
Query { destination: Destination, query: Query },
/// This requester's pending requests and leases.
Requests,
}
@@ -62,6 +64,21 @@ pub enum Destination {
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Query {
/// `systemctl status`, of one unit or of the whole box.
Status {
unit: Option<UnitName>,
},
Logs {
unit: UnitName,
lines: Lines,
since: Option<Since>,
},
Failed,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum ServerMessage {
@@ -203,9 +220,9 @@ mod tests {
let request = ClientMessage::Request(Request {
version: PROTOCOL_VERSION,
label: Some("test".into()),
operation: Operation::Ssh {
operation: Operation::Query {
destination: Destination::Node("river".parse().unwrap()),
command: vec!["uptime".parse().unwrap()],
query: Query::Logs { unit: "nginx.service".parse().unwrap(), lines: Lines::DEFAULT, since: None },
},
});
+95
View File
@@ -94,6 +94,20 @@ validated_string!(
}
);
validated_string!(
/// A systemd unit name, including `\x2d`-style escapes; never an option.
UnitName,
"unit name",
|s| {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 256
&& b[0] != b'-'
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b":_.@-\\".contains(&c))
&& !s.contains("\\\\")
}
);
validated_string!(
/// One word of a command; anything but NUL.
Arg,
@@ -101,6 +115,64 @@ validated_string!(
|s| !s.contains('\0')
);
validated_string!(
/// A journal start: a duration back from now (`30m`, `2h`, `1d`) or a date
/// (`YYYY-MM-DD[ HH:MM[:SS]]`).
Since,
"time (use a duration like 2h or a date like 2026-01-31 12:00)",
|s| {
if crate::queue::parse_duration(s).is_some() {
return true;
}
let b = s.as_bytes();
(10..=19).contains(&b.len()) && b[..4].iter().all(u8::is_ascii_digit) && b.iter().all(|&c| c.is_ascii_digit() || b"-: ".contains(&c))
}
);
impl Since {
/// The value `journalctl --since` takes.
pub fn journalctl(&self) -> String {
match crate::queue::parse_duration(self) {
Some(seconds) => format!("-{seconds}s"),
None => self.0.clone(),
}
}
}
/// Journal lines to show, 1 to 5000.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u32", into = "u32")]
pub struct Lines(u32);
impl Lines {
pub const DEFAULT: Lines = Lines(200);
pub const MAX: u32 = 5000;
pub fn get(self) -> u32 {
self.0
}
}
impl TryFrom<u32> for Lines {
type Error = String;
fn try_from(value: u32) -> Result<Self, String> {
if (1..=Self::MAX).contains(&value) { Ok(Lines(value)) } else { Err(format!("lines must be 1-{}", Self::MAX)) }
}
}
impl FromStr for Lines {
type Err = String;
fn from_str(value: &str) -> Result<Self, String> {
value.parse::<u32>().map_err(|e| e.to_string()).and_then(Lines::try_from)
}
}
impl From<Lines> for u32 {
fn from(value: Lines) -> u32 {
value.0
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -120,11 +192,34 @@ mod tests {
assert!("a b".parse::<HostName>().is_err());
}
#[test]
fn units() {
assert!("nginx.service".parse::<UnitName>().is_ok());
assert!("container@hass.service".parse::<UnitName>().is_ok());
assert!(r"dev-disk-by\x2duuid-1.device".parse::<UnitName>().is_ok());
assert!("-H".parse::<UnitName>().is_err());
assert!("a;b".parse::<UnitName>().is_err());
assert!(r"a\\b".parse::<UnitName>().is_err());
}
#[test]
fn since_and_lines() {
assert_eq!("2h".parse::<Since>().unwrap().journalctl(), "-7200s");
assert_eq!("2026-01-31 12:00".parse::<Since>().unwrap().journalctl(), "2026-01-31 12:00");
assert!("yesterday; reboot".parse::<Since>().is_err());
assert!("-1h".parse::<Since>().is_err());
assert!("0".parse::<Lines>().is_err());
assert!("5001".parse::<Lines>().is_err());
assert_eq!("50".parse::<Lines>().unwrap().get(), 50);
}
#[test]
fn deserializing_validates() {
let ok: Result<NodeName, _> = serde_json::from_str("\"river\"");
assert!(ok.is_ok());
let bad: Result<NodeName, _> = serde_json::from_str("\"-x\"");
assert!(bad.is_err());
let bad: Result<Lines, _> = serde_json::from_str("0");
assert!(bad.is_err());
}
}
+31 -5
View File
@@ -12,12 +12,12 @@ use tokio::io::DuplexStream;
use slop_broker::config::Config;
use slop_broker::proto::{
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Request, ServerMessage, Transport,
decode, encode, transport,
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Query, Request, ServerMessage,
Transport, decode, encode, transport,
};
use slop_broker::queue::Decision;
use slop_broker::server::{Broker, handle};
use slop_broker::types::Arg;
use slop_broker::types::{Arg, Lines};
const FAKE_SSH: &str = r#"#!/bin/sh
echo $$ > "${0%/*}/pid"
@@ -128,8 +128,9 @@ async fn policy_can_deny_and_unlisted_operations_are_denied() {
let mut client = Client::start(&broker, ssh(&["true"])).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_)));
let broker = self::broker(directory.path(), json!({}));
let mut client = Client::start(&broker, ssh(&["true"])).await;
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(_)));
}
@@ -271,6 +272,31 @@ async fn disconnecting_kills_the_process() {
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 requests_lists_pending_and_leases() {
let directory = tempfile::tempdir().unwrap();