//! Messages between `slop` and the broker, and between `slop-approve` and the broker. //! //! Each message is CBOR, framed with a 4-byte big-endian length (`LengthDelimitedCodec`). A //! requester sends one [`ClientMessage::Request`], then (only after an `Approved` that asks for //! it) stdin. `ssh` carries its stdin in the request instead, so approvers see it. The broker answers with [`ServerMessage`]s and closes after a terminal one. use std::num::NonZeroU16; use anyhow::{Context, Result, bail}; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_util::codec::{Framed, LengthDelimitedCodec}; use crate::audit::Record; use crate::queue::{Decision, PendingInfo}; use crate::types::{ 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 = 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; pub const DEFAULT_VSOCK_PORT: u32 = 6262; /// The host's CID, as seen from a guest. pub const HOST_CID: u32 = 2; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum ClientMessage { Request(Request), Stdin(#[serde(with = "serde_bytes")] Vec), StdinEnd, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Request { pub version: u32, /// Free text from the agent (who it is, why); shown to approvers as agent-supplied. pub label: Option, pub operation: Operation, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum Operation { /// A command over SSH, joined with spaces and run by the remote shell (as `ssh` does). Ssh { destination: Destination, command: Vec, /// All of the command's stdin, as UTF-8 text; approvers see it before it runs. #[serde(with = "serde_bytes")] stdin: Option>, }, /// 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, /// Builds a pushed commit and, once approved, activates it on deploy nodes, all at once. Deploy { targets: Vec, commit: CommitId, /// Make it the boot default without switching to it. boot: bool, }, /// Builds flake attributes of a pushed commit and, once approved, pushes them to the binary /// cache. Build { attrs: Vec, commit: CommitId }, /// Works with an age secret the requester sends; the broker returns new ciphertext and never /// writes to a checkout. Secret(SecretOp), } /// What to do with a secret. Each action carries only what it uses; the path is the requester's /// name for the file, which the broker checks against the main branch. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum SecretOp { /// Key names of an env or JSON secret. Keys { file: SecretFile }, /// The plaintext, on stdout. Read { file: SecretFile }, /// A value from stdin. `base` is the current file; a new file has none. Set { path: SecretPath, #[serde(with = "serde_bytes")] base: Option>, target: Target, recipients: Vec, }, /// A value the broker makes; keypair kinds return the public half. Generate { path: SecretPath, #[serde(with = "serde_bytes")] base: Option>, target: Target, kind: GenKind, recipients: Vec, }, /// The same plaintext, encrypted to these recipients. Rekey { file: SecretFile, recipients: Vec }, } impl SecretOp { pub fn path(&self) -> &SecretPath { match self { Self::Keys { file } | Self::Read { file } | Self::Rekey { file, .. } => &file.path, Self::Set { path, .. } | Self::Generate { path, .. } => path, } } /// The current file, if there is one. pub fn ciphertext(&self) -> Option<&[u8]> { match self { Self::Keys { file } | Self::Read { file } | Self::Rekey { file, .. } => Some(&file.ciphertext), Self::Set { base, .. } | Self::Generate { base, .. } => base.as_deref(), } } /// Who the new file is encrypted to, for actions that write one. pub fn recipients(&self) -> Option<&[Recipient]> { match self { Self::Keys { .. } | Self::Read { .. } => None, Self::Set { recipients, .. } | Self::Generate { recipients, .. } | Self::Rekey { recipients, .. } => { Some(recipients) } } } pub fn action(&self) -> &'static str { match self { Self::Keys { .. } => "keys", Self::Read { .. } => "read", Self::Set { .. } => "set", Self::Generate { .. } => "generate", Self::Rekey { .. } => "rekey", } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SecretFile { pub path: SecretPath, #[serde(with = "serde_bytes")] pub ciphertext: Vec, } /// Which part of a secret a value replaces. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum Target { Whole, /// A key of an env or JSON file. Field(SecretKey), } /// Values the broker can generate. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum GenKind { /// 32 letters and digits. Password, /// 32 random bytes in hex. Hex, /// 32 random bytes in base64. Base64, /// A WireGuard private key; returns the public key. Wireguard, /// An OpenSSH private key; returns the public key. SshEd25519, /// An age identity; returns its recipient. Age, } impl GenKind { pub fn name(self) -> &'static str { match self { Self::Password => "password", Self::Hex => "hex", Self::Base64 => "base64", Self::Wireguard => "wireguard", Self::SshEd25519 => "ssh-ed25519", Self::Age => "age", } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] 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-` deploy-rs profiles. Container { node: NodeName, name: ContainerName, }, Host { user: UserName, host: HostName, port: NonZeroU16, }, } 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 { /// `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 { /// Waiting for an approver. Pending { id: String, summary: String, }, /// Output follows. The client sends its stdin only if `stdin` is set. Approved { by: ApprovedBy, stdin: bool, }, /// Progress from the broker itself. Info(String), Stdout(#[serde(with = "serde_bytes")] Vec), Stderr(#[serde(with = "serde_bytes")] Vec), /// The operation ran; `exit` is its status and `result` any structured output. Finished { exit: i32, result: Option, }, Denied(String), Expired, Error(String), } impl ServerMessage { pub fn is_terminal(&self) -> bool { matches!(self, Self::Finished { .. } | Self::Denied(_) | Self::Expired | Self::Error(_)) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ApprovedBy { Policy, Lease, Approver, } /// Structured results of operations that produce data rather than a stream. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum OpResult { Requests { pending: Vec, leases: Vec, }, /// The keys of an env or JSON secret. SecretKeys(Vec), /// A secret's new ciphertext, and the public half of a generated keypair. Secret { #[serde(with = "serde_bytes")] ciphertext: Vec, public: Option, }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PendingSummary { pub id: String, pub summary: String, pub expires_in: u64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LeaseSummary { pub scope: String, pub remaining: u64, } /// Approver socket requests. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum ApproveRequest { List, Decide { id: String, decision: Decision, }, /// The last `count` audit records, at most [`MAX_LOG_RECORDS`]. Log { count: usize, }, } /// Keeps a `Log` response well within [`MAX_MESSAGE`]. pub const MAX_LOG_RECORDS: usize = 200; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum ApproveResponse { Pending(Vec), Recorded, Log(Vec), Error(String), } pub type Transport = Framed; pub fn codec() -> LengthDelimitedCodec { LengthDelimitedCodec::builder().max_frame_length(MAX_MESSAGE).new_codec() } pub fn transport(stream: S) -> Transport { Framed::new(stream, codec()) } pub fn encode(message: &T) -> Result { let mut buffer = Vec::new(); ciborium::into_writer(message, &mut buffer)?; if buffer.len() > MAX_MESSAGE { bail!("message too large"); } Ok(buffer.into()) } pub fn decode(data: &[u8]) -> Result { ciborium::from_reader(data).context("invalid message") } pub async fn send(transport: &mut S, message: &T) -> Result<()> where S: futures_util::Sink + Unpin, T: Serialize, { transport.send(encode(message)?).await?; Ok(()) } /// The next message, or `None` at a clean end of stream. pub async fn receive(transport: &mut S) -> Result> where S: futures_util::Stream> + Unpin, T: DeserializeOwned, { match transport.next().await { None => Ok(None), Some(frame) => Ok(Some(decode(&frame?)?)), } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn messages_round_trip() { let (a, b) = tokio::io::duplex(1024); let (mut a, mut b) = (transport(a), transport(b)); let request = ClientMessage::Request(Request { version: PROTOCOL_VERSION, label: Some("test".into()), operation: Operation::Query { destination: Destination::Node("river".parse().unwrap()), query: Query::Logs { unit: "nginx.service".parse().unwrap(), lines: Lines::DEFAULT, since: None }, }, }); send(&mut a, &request).await.unwrap(); send(&mut a, &ClientMessage::Stdin(b"\0\xffbytes".to_vec())).await.unwrap(); drop(a); assert_eq!(receive::<_, ClientMessage>(&mut b).await.unwrap(), Some(request)); assert_eq!( receive::<_, ClientMessage>(&mut b).await.unwrap(), Some(ClientMessage::Stdin(b"\0\xffbytes".to_vec())) ); assert_eq!(receive::<_, ClientMessage>(&mut b).await.unwrap(), None); } #[test] fn invalid_values_fail_to_decode() { #[derive(Serialize)] #[serde(rename_all = "kebab-case")] enum Loose { Node(String), } let data = encode(&Loose::Node("-oProxyCommand=x".into())).unwrap(); assert!(decode::(&data).is_err()); let data = encode(&Loose::Node("river".into())).unwrap(); assert!(decode::(&data).is_ok()); } #[tokio::test] async fn oversized_frames_are_rejected() { use tokio::io::AsyncWriteExt; let (mut a, b) = tokio::io::duplex(64); a.write_all(&u32::MAX.to_be_bytes()).await.unwrap(); assert!(receive::<_, ClientMessage>(&mut transport(b)).await.is_err()); } }