diff --git a/nix/vm-test.nix b/nix/vm-test.nix index d365e3a..0455eb0 100644 --- a/nix/vm-test.nix +++ b/nix/vm-test.nix @@ -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'") diff --git a/slop-tools.md b/slop-tools.md index 64473f4..08b9895 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -19,20 +19,25 @@ applies a policy, and asks a human to approve most requests. ## Commands -| Command | What it does | -|---|---| -| `slop ssh -- …` | Run a command over SSH on a deploy node, as the node's configured user. | -| `slop ssh --host @ [-p ] -- …` | The same for a host outside the deploy nodes. | -| `slop requests` | Your pending requests and active leases. | +| Command | What it does | Approval | +|---|---|---| +| `slop status [unit]` | `systemctl status`, of one unit or the whole box | usually none | +| `slop logs [-n 200] [--since 2h]` | A unit's journal; `--since` takes a duration or a date (`2026-01-31 12:00`) | usually none | +| `slop failed ` | Failed units | usually none | +| `slop ssh -- …` | 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 @ [-p ]` 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 -- 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 -- 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 diff --git a/src/bin/slop.rs b/src/bin/slop.rs index b92dbd2..b7e7fab 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -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, }, + /// `systemctl status` on a box, of one unit or overall. + Status { + #[command(flatten)] + target: Target, + unit: Option, + }, + /// 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, + }, + /// 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 { 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!(), }) diff --git a/src/ops/mod.rs b/src/ops/mod.rs index 15634cb..a45d4bb 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -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 { 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 diff --git a/src/ops/query.rs b/src/ops/query.rs new file mode 100644 index 0000000..f9fa5e4 --- /dev/null +++ b/src/ops/query.rs @@ -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 { + let mut words: Vec = 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 { + 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"); + } +} diff --git a/src/proto.rs b/src/proto.rs index 2217b18..37b856e 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -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 }, + /// 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, + }, + Logs { + unit: UnitName, + lines: Lines, + since: Option, + }, + 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 }, }, }); diff --git a/src/types.rs b/src/types.rs index cd668c3..fecf471 100644 --- a/src/types.rs +++ b/src/types.rs @@ -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 for Lines { + type Error = String; + fn try_from(value: u32) -> Result { + 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 { + value.parse::().map_err(|e| e.to_string()).and_then(Lines::try_from) + } +} + +impl From 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::().is_err()); } + #[test] + fn units() { + assert!("nginx.service".parse::().is_ok()); + assert!("container@hass.service".parse::().is_ok()); + assert!(r"dev-disk-by\x2duuid-1.device".parse::().is_ok()); + assert!("-H".parse::().is_err()); + assert!("a;b".parse::().is_err()); + assert!(r"a\\b".parse::().is_err()); + } + + #[test] + fn since_and_lines() { + assert_eq!("2h".parse::().unwrap().journalctl(), "-7200s"); + assert_eq!("2026-01-31 12:00".parse::().unwrap().journalctl(), "2026-01-31 12:00"); + assert!("yesterday; reboot".parse::().is_err()); + assert!("-1h".parse::().is_err()); + assert!("0".parse::().is_err()); + assert!("5001".parse::().is_err()); + assert_eq!("50".parse::().unwrap().get(), 50); + } + #[test] fn deserializing_validates() { let ok: Result = serde_json::from_str("\"river\""); assert!(ok.is_ok()); let bad: Result = serde_json::from_str("\"-x\""); assert!(bad.is_err()); + let bad: Result = serde_json::from_str("0"); + assert!(bad.is_err()); } } diff --git a/tests/broker.rs b/tests/broker.rs index e2696d1..49c066a 100644 --- a/tests/broker.rs +++ b/tests/broker.rs @@ -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();