detail: Structure what approvers see

Request details become fields, then tables, lists and text, with a
tone on fields and rows. The web app shows them as a grid and tables
like the audit log; everything else, the audit log and passkey
fingerprints use the text rendering, with headline fields first in
notifications. Deploys get a packages table per profile, secrets a
recipients table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-24 01:28:47 +00:00
1 parent 005e3d32df
commit 63b256c21b
18 files changed
+849 -143

No files matched your search

+7 -2
View File
@@ -14,7 +14,8 @@ How the code is put together, and how to extend it. The design and its rationale
| `src/queue.rs` | Pending approvals, decisions, leases, per-requester limits and rate limits |
| `src/server.rs` | Listeners (vsock, Unix), the per-connection handler, `authorize` |
| `src/exec.rs` | Running processes on the requester's framed stdio; cancellation |
| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval text), `execute`, quoting |
| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval detail), `execute`, quoting |
| `src/detail.rs` | What approvers see of a request (`Detail`: fields, tables, lists, text) and its text rendering |
| `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also has the `INSPECT` comparison script and its parser |
| `src/ops/secret.rs`, `src/ops/secret/format.rs` | Age secrets: what approvers see, encryption, generated values; env and JSON fields |
| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also looks secrets up on the main branch |
@@ -159,7 +160,11 @@ Arguments from the requester are validated so none can be read as an option.
would misread anything.
2. `src/ops/<op>.rs` and a `plan` arm in `src/ops/mod.rs`: the config checks, a scope that is
exactly what an approval should cover, and an `execute` arm.
- Put anything shown but not part of the approval (commands, diffs) in `detail`.
- Put anything shown but not part of the approval (commands, diffs) in `detail`: short facts
as fields, anything with rows as a table or list, and preformatted text as a text section.
Tone a field or row `Warn` when approvers must notice it, and mark the field `headline` if
notifications must keep it. Mark commands, paths and the like as code, and diffs with
`Section::diff`.
- Set `limits` and `sensitive` where the operation reveals or redistributes secrets.
- If approvers need something looked up first (as secrets do, on the main branch), list the
operation in `prepares` and fill in `detail` in a `prepare` arm; it runs before approval and
+34 -2
View File
@@ -219,6 +219,37 @@ worker answers with the session like the page does. Requests that need a passkey
| Web Push to the web app | Android; desktop while the browser runs; iOS 16.4 and later once added to the Home Screen | Yes, except on iOS | Nobody: the payload is end-to-end encrypted to the browser | An OIDC provider and a reverse proxy |
| [Home Assistant Companion](#home-assistant-notifications) | Yes | Yes | Google: pushes go through Firebase Cloud Messaging, encrypted only in transit, except with Local Push while the app holds its own connection to Home Assistant | Home Assistant |
### Request details
What approvers see of a request is a `Detail` (`src/detail.rs`): fields, then sections, each a
table, a list or preformatted text. Fields and table rows have a tone, and a warning tone marks
what needs attention, such as a secret whose content belongs to another file.
- **Web app:** fields as a label/value grid that stays in view; sections under a fold, tables
styled like the audit log. The request's own page opens the fold. Fields, columns and lists
marked as code (commands, commits, paths, keys) are in monospace, and diffs are coloured.
- **Everything else** shows the text rendering: a field per line, then each section under its
title, with tables in aligned columns and warnings marked `⚠`. `slop-approve` shows it as it is,
Home Assistant and Web Push a cut-down version that puts headline fields first.
- **Audit log and passkeys:** the audit log keeps the text rendering, so old records read the same
whatever the structure becomes, and passkey confirmations fingerprint it.
- **Limits:** each value, row count and text section is capped, and sections past the total limit
are dropped with a note saying which.
The structure is the same for every operation; what's particular to each is only how it fills the
fields and sections:
- **SSH and queries:** the command.
- **Builder approvals:** the commit, whether it's on the main branch, the commits, changed files
and diff.
- **Deploys:** the commit, and for each profile a packages table (version and size changes), the
changed units and `/etc` files, and whether a reboot is needed.
- **Builds:** each output with its closure size.
- **Secrets:** see [what approvers see](#what-approvers-see).
A typed detail per operation was considered: every surface would need a renderer for every
operation, and nothing acts on the structure besides showing it.
### Audit log
Each request, decision, approver, lease use and result is an event with the request's ID. The
@@ -363,8 +394,9 @@ which only people should be able to push to, and the approval shows what that br
branch). A pushed commit wouldn't prove anything here, since any branch can copy a blob to any
path.
- **Whether the recipients are right.** The builder evaluates the branch's own agenix rules file
(`secrets.rules`, cached per commit) for the path, and the approval says the requested
recipients match it, or lists what's added and removed, or that the path isn't in the rules.
(`secrets.rules`, cached per commit) for the path. The approval says whether the requested
recipients match it, with a table of the keys, each as in the rules, added or removed; or that
the path isn't in the rules.
Only the protected branch's Nix is evaluated, never a requester's commit, so this doesn't need
the builder approval. `secrets.names` labels well-known keys (such as people's); other keys are
shown abbreviated.
+3 -2
View File
@@ -116,7 +116,8 @@ pub fn format(entry: &PendingInfo, full: bool) -> String {
let mut text =
format!("{} {} {}{marker} (expires in {}s)\n", entry.id, entry.requester, entry.summary, entry.expires_in);
let lines: Vec<_> = entry.detail.lines().collect();
let detail = entry.detail.to_text();
let lines: Vec<_> = detail.lines().collect();
let shown = if full { lines.len() } else { lines.len().min(6) };
for line in &lines[..shown] {
text += &format!(" {line}\n");
@@ -316,7 +317,7 @@ mod tests {
requester: "r".into(),
op: "ssh".into(),
summary: "ssh river".into(),
detail: String::new(),
detail: Default::default(),
label: None,
sensitive: false,
passkey: false,
+409
View File
@@ -0,0 +1,409 @@
//! What approvers are shown of a request: fields, then tables, lists and text. Operations build
//! it; every surface renders it. The web app shows the structure, the others [`Detail::to_text`],
//! which is also what the audit log keeps and passkey confirmations fingerprint.
//!
//! The structure is the same for every operation, so surfaces don't need to know any of them.
//! All of it can carry agent-written text, which every surface makes printable when it shows it.
use std::fmt::Write;
use serde::{Deserialize, Serialize};
use crate::ops::truncate;
/// Characters in one field value, table cell or list item.
const MAX_VALUE: usize = 1000;
/// Rows of a table or items of a list; the rest are counted.
const MAX_ROWS: usize = 200;
/// Characters of one text section.
const MAX_TEXT: usize = 40_000;
/// Characters of the whole text rendering; sections past it are dropped.
const MAX_TOTAL: usize = 60_000;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Detail {
pub fields: Vec<Field>,
pub sections: Vec<Section>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
pub label: String,
pub value: String,
#[serde(default)]
pub tone: Tone,
/// What a notification must carry when there's little room.
#[serde(default)]
pub headline: bool,
/// A command, path, key or the like, shown in monospace where that's possible.
#[serde(default)]
pub code: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tone {
#[default]
Normal,
Good,
Warn,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Section {
Table {
title: String,
columns: Vec<Column>,
rows: Vec<Row>,
/// Rows left out.
#[serde(default)]
more: usize,
},
List {
title: String,
items: Vec<String>,
#[serde(default)]
more: usize,
#[serde(default)]
code: bool,
},
/// Diffs, commands and other preformatted text.
Text {
title: String,
text: String,
/// A unified diff, which the web app colours.
#[serde(default)]
diff: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Column {
pub title: String,
#[serde(default)]
pub code: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
pub cells: Vec<String>,
#[serde(default)]
pub tone: Tone,
}
impl Tone {
/// The CSS class, matching the audit log's outcome badges.
pub fn class(&self) -> &'static str {
match self {
Tone::Normal => "neutral",
Tone::Good => "good",
Tone::Warn => "warn",
}
}
fn marker(&self) -> &'static str {
if *self == Tone::Warn { "⚠ " } else { "" }
}
}
impl Field {
pub fn new(label: impl Into<String>, value: impl AsRef<str>) -> Field {
Field {
label: label.into(),
value: truncate(value.as_ref(), MAX_VALUE),
tone: Tone::Normal,
headline: false,
code: false,
}
}
pub fn code(mut self) -> Field {
self.code = true;
self
}
pub fn tone(mut self, tone: Tone) -> Field {
self.tone = tone;
self
}
pub fn headline(mut self) -> Field {
self.headline = true;
self
}
fn text(&self) -> String {
format!("{}{}: {}", self.tone.marker(), self.label, self.value)
}
}
impl Column {
pub fn text(title: impl Into<String>) -> Column {
Column { title: title.into(), code: false }
}
pub fn code(title: impl Into<String>) -> Column {
Column { title: title.into(), code: true }
}
}
impl Row {
pub fn new<S: AsRef<str>>(cells: impl IntoIterator<Item = S>, tone: Tone) -> Row {
Row { cells: cells.into_iter().map(|c| truncate(c.as_ref(), MAX_VALUE)).collect(), tone }
}
}
impl Section {
pub fn table(title: impl Into<String>, columns: Vec<Column>, rows: impl IntoIterator<Item = Row>) -> Section {
let (rows, more) = capped(rows);
Section::Table { title: title.into(), columns, rows, more }
}
pub fn list<S: AsRef<str>>(title: impl Into<String>, items: impl IntoIterator<Item = S>) -> Section {
let (items, more) = capped(items.into_iter().map(|i| truncate(i.as_ref(), MAX_VALUE)));
Section::List { title: title.into(), items, more, code: false }
}
/// A list of commands, paths, units or the like.
pub fn code_list<S: AsRef<str>>(title: impl Into<String>, items: impl IntoIterator<Item = S>) -> Section {
let mut list = Section::list(title, items);
if let Section::List { code, .. } = &mut list {
*code = true;
}
list
}
pub fn text(title: impl Into<String>, text: impl AsRef<str>) -> Section {
Section::Text { title: title.into(), text: truncate(text.as_ref().trim_end(), MAX_TEXT), diff: false }
}
pub fn diff(title: impl Into<String>, text: impl AsRef<str>) -> Section {
Section::Text { title: title.into(), text: truncate(text.as_ref().trim_end(), MAX_TEXT), diff: true }
}
pub fn title(&self) -> &str {
match self {
Section::Table { title, .. } | Section::List { title, .. } | Section::Text { title, .. } => title,
}
}
fn render(&self, out: &mut String) {
let _ = writeln!(out, "{}:", self.title());
match self {
Section::Table { rows, more, .. } => {
// Columns padded to line up, as the terminal and notifications show them.
let mut widths = Vec::new();
for row in rows {
widths.resize(widths.len().max(row.cells.len()), 0);
for (width, cell) in widths.iter_mut().zip(&row.cells) {
*width = (*width).max(cell.chars().count());
}
}
for row in rows {
let mut line = format!(" {}", row.tone.marker());
for (index, cell) in row.cells.iter().enumerate() {
let last = index + 1 == row.cells.len();
let pad = if last { 0 } else { widths[index] - cell.chars().count() + 2 };
let _ = write!(line, "{cell}{}", " ".repeat(pad));
}
let _ = writeln!(out, "{}", line.trim_end());
}
more_line(out, *more);
}
Section::List { items, more, .. } => {
for item in items {
let _ = writeln!(out, " {item}");
}
more_line(out, *more);
}
Section::Text { text, .. } => {
let _ = writeln!(out, "{text}");
}
}
}
}
/// Each line of a unified diff with what it is: `add`, `del`, `hunk`, `meta` (file headers) or
/// `context`.
pub fn diff_lines(text: &str) -> Vec<(&'static str, &str)> {
text.lines()
.map(|line| {
let kind = if line.starts_with("+++ ") || line.starts_with("--- ") {
"meta"
} else if line.starts_with('+') {
"add"
} else if line.starts_with('-') {
"del"
} else if line.starts_with("@@") {
"hunk"
} else if ["diff ", "index ", "new file", "deleted file", "similarity", "rename ", "Binary files"]
.iter()
.any(|p| line.starts_with(p))
{
"meta"
} else {
"context"
};
(kind, line)
})
.collect()
}
fn capped<T>(items: impl IntoIterator<Item = T>) -> (Vec<T>, usize) {
let mut kept = Vec::new();
let mut more = 0;
for item in items {
if kept.len() < MAX_ROWS {
kept.push(item);
} else {
more += 1;
}
}
(kept, more)
}
fn more_line(out: &mut String, more: usize) {
if more > 0 {
let _ = writeln!(out, " … {more} more");
}
}
impl Detail {
pub fn new() -> Detail {
Detail::default()
}
/// A detail of one field, for requests that need no more.
pub fn of(label: impl Into<String>, value: impl AsRef<str>) -> Detail {
let mut detail = Detail::new();
detail.field(Field::new(label, value));
detail
}
/// A detail of one code field, such as a command.
pub fn code(label: impl Into<String>, value: impl AsRef<str>) -> Detail {
let mut detail = Detail::new();
detail.field(Field::new(label, value).code());
detail
}
pub fn field(&mut self, field: Field) -> &mut Detail {
self.fields.push(field);
self
}
pub fn section(&mut self, section: Section) -> &mut Detail {
self.sections.push(section);
self
}
pub fn extend(&mut self, other: Detail) {
self.fields.extend(other.fields);
self.sections.extend(other.sections);
}
pub fn is_empty(&self) -> bool {
self.fields.is_empty() && self.sections.is_empty()
}
/// Drops sections from the end until the text rendering fits, noting what was left out.
pub fn limited(mut self) -> Detail {
let mut dropped = Vec::new();
while self.sections.len() > 1 && self.to_text().chars().count() > MAX_TOTAL {
dropped.push(self.sections.pop().unwrap().title().to_owned());
}
if !dropped.is_empty() {
dropped.reverse();
self.field(Field::new("Left out (too long)", dropped.join(", ")).tone(Tone::Warn));
}
self
}
/// Fields one per line, then each section under its title.
pub fn to_text(&self) -> String {
self.render(false)
}
/// As [`Detail::to_text`], with headline fields first, for notifications that get cut short.
pub fn brief(&self) -> String {
self.render(true)
}
fn render(&self, headlines_first: bool) -> String {
let mut out = String::new();
let mut fields: Vec<&Field> = self.fields.iter().collect();
if headlines_first {
fields.sort_by_key(|f| !f.headline);
}
for field in fields {
let _ = writeln!(out, "{}", field.text());
}
for section in &self.sections {
section.render(&mut out);
}
out.truncate(out.trim_end().len());
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Detail {
let mut detail = Detail::new();
detail
.field(Field::new("File", "secrets/a.env.age"))
.field(Field::new("Content", "the same as secrets/b.age").tone(Tone::Warn).headline())
.section(Section::table(
"Recipients",
vec![Column::code("Key"), Column::text("Status")],
[
Row::new(["dev", "as in the rules"], Tone::Normal),
Row::new(["ssh-ed25519 …abcd", "added"], Tone::Warn),
],
))
.section(Section::code_list("Commits", ["0123456 Add a"]))
.section(Section::diff("Diff", "+a\n-b\n"));
detail
}
#[test]
fn renders_as_text() {
assert_eq!(
sample().to_text(),
"File: secrets/a.env.age\n⚠ Content: the same as secrets/b.age\nRecipients:\n dev \
as in the rules\n ⚠ ssh-ed25519 …abcd added\nCommits:\n 0123456 Add a\nDiff:\n+a\n-b"
);
assert!(sample().brief().starts_with("⚠ Content: the same as secrets/b.age\nFile:"));
}
#[test]
fn classifies_diff_lines() {
let diff = "diff --git a/x b/x\nindex 1..2 100644\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n a\n-b\n+c";
let kinds: Vec<_> = diff_lines(diff).into_iter().map(|(kind, _)| kind).collect();
assert_eq!(kinds, ["meta", "meta", "meta", "meta", "hunk", "context", "del", "add"]);
}
#[test]
fn long_details_are_cut() {
let section = Section::list("Units", (0..250).map(|i| format!("u{i}")));
assert!(matches!(&section, Section::List { items, more: 50, .. } if items.len() == 200));
assert!(Detail { fields: Vec::new(), sections: vec![section] }.to_text().ends_with(" … 50 more"));
let mut detail = Detail::of("Commit", "abc");
detail.section(Section::text("Diff", "x".repeat(MAX_TEXT + 10)));
detail.section(Section::text("More", "y".repeat(MAX_TEXT)));
let detail = detail.limited();
assert_eq!(detail.sections.len(), 1);
assert!(detail.to_text().contains("Left out (too long): More"));
}
#[test]
fn round_trips() {
let json = serde_json::to_string(&sample()).unwrap();
assert_eq!(serde_json::from_str::<Detail>(&json).unwrap(), sample());
}
}
+1 -1
View File
@@ -173,7 +173,7 @@ impl Notifier<'_> {
})
.collect();
let mut message = format!("{}\n{}", entry.summary, truncate(&entry.detail, 400));
let mut message = format!("{}\n{}", entry.summary, truncate(&entry.detail.brief(), 400));
if let Some(label) = &entry.label {
message += &format!("\nAgent says: {}", truncate(label, 120));
}
+1
View File
@@ -4,6 +4,7 @@ pub mod approve;
pub mod audit;
pub mod builder;
pub mod config;
pub mod detail;
pub mod exec;
pub mod ha;
pub mod ops;
+15 -10
View File
@@ -15,6 +15,7 @@ use super::deploy::nix_ssh_options;
use super::{Parsed, shell_quote, ssh};
use crate::builder::{self, BuildRequest};
use crate::config::{CacheConfig, DeployConfig, SshConfig};
use crate::detail::{Column, Detail, Row, Section, Tone};
use crate::exec::{self, Io};
use crate::policy::Limits;
use crate::proto::{Operation, ServerMessage};
@@ -53,7 +54,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
scope: scope.as_object().unwrap().clone(),
rule_scopes,
summary: format!("build {names} at {}", commit.short()),
detail: format!("Commit {commit}\n(building; the outputs are shown once it's built)"),
detail: super::deploy::building(commit, "Outputs"),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -78,17 +79,21 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
let sizes = closure_sizes(deploy, &paths, &io.cancel).await?;
let description = parsed.description.as_ref().context("the commit wasn't described")?;
let mut detail = super::describe_source(commit, description);
detail += "Outputs (closure sizes):\n";
for output in &built.outputs {
detail += &format!(" {}:\n", output.attr);
for path in &output.paths {
let mut detail = Detail::new();
super::source(&mut detail, commit, description);
let rows = built.outputs.iter().flat_map(|output| {
output.paths.iter().map(|path| {
let size = sizes.iter().find(|(p, _)| p == path).map_or("?", |(_, s)| s.as_str());
detail += &format!(" {path} ({size})\n");
}
}
Row::new([output.attr.to_string(), path.clone(), size.to_owned()], Tone::Normal)
})
});
detail.section(Section::table(
"Outputs",
vec![Column::code("Attribute"), Column::code("Path"), Column::code("Closure")],
rows,
));
parsed.detail = super::truncate(detail.trim_end(), 20_000);
parsed.detail = detail.limited();
parsed.prepared = Some(built);
Ok(())
}
+69 -44
View File
@@ -15,6 +15,7 @@ use tokio::process::Command;
use super::{Parsed, shell_quote, ssh};
use crate::builder::{self, BuildRequest, BuiltProfile};
use crate::config::{DeployConfig, SshConfig};
use crate::detail::{Column, Detail, Field, Row, Section, Tone};
use crate::exec::{self, Io, Output};
use crate::policy::Limits;
use crate::proto::{Destination, Operation};
@@ -67,7 +68,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
scope: scope.as_object().unwrap().clone(),
rule_scopes,
summary: format!("deploy {names} ({}) at {}", mode(*boot), commit.short()),
detail: format!("Commit {commit}\n(building; the changes are shown once it's built)"),
detail: building(commit, "Changes"),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -79,6 +80,13 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
})
}
/// What a request shows until it's built.
pub fn building(commit: &crate::types::CommitId, label: &str) -> Detail {
let mut detail = Detail::code("Commit", commit);
detail.field(Field::new(label, "shown once it's built"));
detail
}
/// Builds, copies and compares; fills in the approval detail.
pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> {
let Operation::Deploy { targets, commit, boot } = &parsed.operation else { return Ok(()) };
@@ -93,23 +101,23 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
let reports = join_all(by_node.iter().map(|(node, profiles)| async move {
copy(ssh, deploy, node, profiles, &io.out, &io.cancel).await?;
let mut sections = Vec::new();
let mut detail = Detail::new();
for profile in profiles {
let changes = inspect(ssh, node, profile, &io.cancel).await?;
sections.push(format!("{node}.{} ({}):\n{}", profile.profile, mode(*boot), changes.describe()));
changes.describe(&format!("{node}.{} ({})", profile.profile, mode(*boot)), &mut detail);
}
anyhow::Ok(sections.join("\n"))
anyhow::Ok(detail)
}))
.await;
let description = parsed.description.as_ref().context("the commit wasn't described")?;
let mut detail = super::describe_source(commit, description);
let mut detail = Detail::new();
super::source(&mut detail, commit, description);
for report in reports {
detail += &report?;
detail.push('\n');
detail.extend(report?);
}
parsed.detail = super::truncate(detail.trim_end(), 20_000);
parsed.detail = detail.limited();
parsed.prepared = Some(built);
Ok(())
}
@@ -389,47 +397,50 @@ impl Changes {
}
}
fn describe(&self) -> String {
fn listing(label: &str, items: &[String], limit: usize) -> String {
if items.is_empty() {
return String::new();
}
let mut shown = items.iter().take(limit).cloned().collect::<Vec<_>>().join(", ");
if items.len() > limit {
shown += &format!(", … {} more", items.len() - limit);
}
format!(" {label}: {shown}\n")
/// Adds the changes to `target` (such as `river.system (switch)`) to an approval.
fn describe(&self, target: &str, detail: &mut Detail) {
if self.new {
detail.field(Field::new(target, "a new profile: nothing to compare with"));
return;
}
let mut text = String::new();
if self.new {
text += " new profile: nothing to compare with\n";
} else if self.packages.is_empty() {
text += " packages: no version changes\n";
if self.packages.is_empty() {
detail.field(Field::new(format!("{target} packages"), "no version changes"));
} else {
text += " packages:\n";
for line in self.packages.iter().take(40) {
text += &format!(" {line}\n");
}
if self.packages.len() > 40 {
text += &format!(" … {} more\n", self.packages.len() - 40);
}
let rows = self.packages.iter().map(|line| Row::new(package_cells(line), Tone::Normal));
detail.section(Section::table(
format!("{target}: packages"),
vec![Column::code("Package"), Column::code("Version"), Column::code("Size")],
rows,
));
}
if !self.boot.is_empty() {
text += &format!(" {} changed: takes effect after a reboot\n", self.boot.join(" and "));
let changed = format!("{} changed: takes effect after a reboot", self.boot.join(" and "));
detail.field(Field::new(format!("{target} reboot"), changed).tone(Tone::Warn));
}
text += &listing("changed units", &self.units.changed, 40);
text += &listing("added units", &self.units.added, 40);
text += &listing("removed units", &self.units.removed, 40);
text += &listing("changed files", &self.files.changed, 30);
text += &listing("added files", &self.files.added, 30);
text += &listing("removed files", &self.files.removed, 30);
if !self.new && self.units == Diff::default() && self.files == Diff::default() {
text += " no unit or /etc changes\n";
for (kind, diff) in [("units", &self.units), ("files", &self.files)] {
for (change, items) in [("changed", &diff.changed), ("added", &diff.added), ("removed", &diff.removed)] {
if !items.is_empty() {
detail.section(Section::code_list(format!("{target}: {change} {kind}"), items));
}
}
}
text
if self.units == Diff::default() && self.files == Diff::default() {
detail.field(Field::new(format!("{target} units and /etc"), "no changes"));
}
}
}
/// A line of `nix store diff-closures` (`name: 1.0 → 1.1, +3.4 KiB`) as package, version change
/// and size change.
fn package_cells(line: &str) -> [&str; 3] {
let Some((name, rest)) = line.split_once(": ") else { return [line, "", ""] };
let is_size = |s: &str| s.starts_with(['+', '-']);
match rest.rsplit_once(", ") {
Some((version, size)) if is_size(size) => [name, version, size],
_ if is_size(rest) => [name, "", rest],
_ => [name, rest, ""],
}
}
@@ -437,6 +448,14 @@ impl Changes {
mod tests {
use super::*;
#[test]
fn splits_package_lines() {
assert_eq!(package_cells("a: 1.0 → 1.1, +3.4 KiB"), ["a", "1.0 → 1.1", "+3.4 KiB"]);
assert_eq!(package_cells("b: -12.0 KiB"), ["b", "", "-12.0 KiB"]);
assert_eq!(package_cells("c: ∅ → 2.0"), ["c", "∅ → 2.0", ""]);
assert_eq!(package_cells("odd"), ["odd", "", ""]);
}
#[test]
fn compares_etc_trees() {
let output = "@@packages\nhome-assistant: 2026.11.1 → 2026.11.2, +3.4 MiB\n@@boot\nkernel\n@@old\n\
@@ -463,11 +482,17 @@ mod tests {
assert_eq!(changes.files.removed, ["/etc/gone"]);
assert!(changes.files.changed.is_empty());
let text = changes.describe();
assert!(text.contains("changed units: a.service\n") && text.contains("kernel changed"), "{text}");
let mut detail = Detail::new();
changes.describe("river.system (switch)", &mut detail);
let text = detail.to_text();
assert!(text.contains("river.system (switch): changed units:\n a.service\n"), "{text}");
assert!(text.contains("⚠ river.system (switch) reboot: kernel changed"), "{text}");
assert!(text.contains(" home-assistant 2026.11.1 → 2026.11.2 +3.4 MiB"), "{text}");
let fresh = Changes::parse("@@old\n@@new\n./hosts\t/nix/store/x\n");
assert!(fresh.new && fresh.describe().contains("new profile"));
let mut detail = Detail::new();
fresh.describe("river.system (switch)", &mut detail);
assert!(fresh.new && detail.to_text().contains("new profile"));
}
#[test]
+26 -16
View File
@@ -4,6 +4,7 @@ use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};
use crate::builder::Description;
use crate::detail::{Detail, Field, Section, Tone};
use crate::exec::Io;
use crate::policy::Limits;
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
@@ -24,7 +25,7 @@ pub struct Parsed {
/// answer applies (such as one per node of a deploy).
pub rule_scopes: Vec<Map<String, Value>>,
pub summary: String,
pub detail: String,
pub detail: Detail,
pub limits: Limits,
/// Reveals a secret or changes who can read one.
pub sensitive: bool,
@@ -71,7 +72,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
op: "ssh",
scope: ssh::scope(destination),
summary: format!("ssh {}", ssh::describe(destination)),
detail: format!("Command: {shown}"),
detail: Detail::code("Command", shown),
limits: Limits::default(),
sensitive: false,
stdin: true,
@@ -93,7 +94,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
op: "query",
scope,
summary: format!("{} on {}", query::name(query), ssh::describe(destination)),
detail: format!("Command: {}", shell_quote(&query::remote_command(query))),
detail: Detail::code("Command", shell_quote(&query::remote_command(query))),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -112,7 +113,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
op: "requests",
scope: Map::new(),
summary: "list requests".into(),
detail: String::new(),
detail: Detail::new(),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -164,10 +165,10 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
"for": parsed.op,
});
let mut detail = format!("For: {}\n{}", parsed.summary, describe_source(commit, description));
let mut detail = Detail::of("For", &parsed.summary);
source(&mut detail, commit, description);
if !description.diff.is_empty() {
detail += "Diff:\n";
detail += &description.diff;
detail.section(Section::diff("Diff", &description.diff));
}
Ok(Parsed {
@@ -175,7 +176,7 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
scope: Map::new(),
rule_scopes: vec![rule_scope.as_object().unwrap().clone()],
summary: format!("run the builder for {}", parsed.summary),
detail: truncate(detail.trim_end(), 60_000),
detail: detail.limited(),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -187,13 +188,17 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
})
}
/// The commit and its log and diffstat, for approvals.
pub fn describe_source(commit: &CommitId, description: &Description) -> String {
let mut text = format!("Commit {commit}\nCommits:\n");
for line in description.log.lines().chain(description.stat.lines()) {
text += &format!(" {line}\n");
/// The commit, whether it's on the main branch, and its log and diffstat, for approvals.
pub fn source(detail: &mut Detail, commit: &CommitId, description: &Description) {
let (on_branch, tone) = if description.on_branch { ("yes", Tone::Good) } else { ("no", Tone::Normal) };
detail.field(Field::new("Commit", commit).code()).field(Field::new("On the main branch", on_branch).tone(tone));
if !description.log.trim().is_empty() {
detail.section(Section::code_list("Commits", description.log.lines()));
}
if !description.stat.trim().is_empty() {
detail.section(Section::text("Files", &description.stat));
}
text
}
/// Work done before approval so approvers can see what a request does, such as building a
@@ -290,7 +295,7 @@ mod tests {
scope: Map::new(),
rule_scopes: Vec::new(),
summary: "build hello at 0123456789ab".into(),
detail: String::new(),
detail: Detail::new(),
limits: Limits::default(),
sensitive: false,
stdin: false,
@@ -313,7 +318,12 @@ mod tests {
assert_eq!(gate.rule_scopes[0]["on_branch"], "false");
assert_eq!(gate.rule_scopes[0]["for"], "build");
assert!(gate.summary.starts_with("run the builder for build hello"));
assert!(gate.detail.contains("0123456 pkgs: Add hello") && gate.detail.ends_with("+{ hello }: hello"));
let text = gate.detail.to_text();
assert!(
text.contains("Commits:\n 0123456 pkgs: Add hello") && text.ends_with("Diff:\n+{ hello }: hello"),
"{text}"
);
assert!(text.contains("On the main branch: no"));
}
#[test]
+78 -45
View File
@@ -13,6 +13,7 @@ use serde_json::{Map, Value};
use crate::builder::{SecretContext, SecretRequest};
use crate::config::SecretsConfig;
use crate::detail::{Column, Detail, Field, Row, Section, Tone};
use crate::exec::Io;
use crate::policy::Limits;
use crate::proto::{GenKind, OpResult, Operation, SecretOp, ServerMessage, Target};
@@ -61,7 +62,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
op: "secret",
scope,
summary: summary(op),
detail: String::new(),
detail: Detail::new(),
// The plaintext reaches the requester, so a person decides each time.
limits: if read { Limits { never_auto: true, never_lease: true } } else { Limits::default() },
sensitive: read,
@@ -119,36 +120,40 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
}
/// What approvers see, and whether anything in it needs their attention.
fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own: &Recipient) -> (String, bool) {
fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own: &Recipient) -> (Detail, bool) {
let path = op.path();
let branch = &context.branch;
let mut sensitive = false;
let mut lines = vec![format!("File: {path}"), format!("Checked against {branch} at {}", context.commit.short())];
let mut detail = Detail::code("File", path);
detail.field(Field::new("Checked against", format!("{branch} at {}", context.commit.short())));
// What the content really is, whatever the requester called it
let claimed = repository_path(&config.rules, path);
lines.push(match op.ciphertext() {
None => "Content: a new file".into(),
detail.field(match op.ciphertext() {
None => Field::new("Content", "a new file"),
Some(ciphertext) if context.paths.contains(&claimed) => {
format!("Content: {path} as on {branch} (blob {})", ObjectId::blob(ciphertext).short())
let blob = ObjectId::blob(ciphertext);
let blob = blob.short();
Field::new("Content", format!("{path} as on {branch} (blob {blob})")).tone(Tone::Good)
}
Some(_) if !context.paths.is_empty() => {
sensitive = true;
format!("⚠ Content: the same as {} on {branch}, not {path}", context.paths.join(", "))
let others = context.paths.join(", ");
Field::new("Content", format!("the same as {others} on {branch}, not {path}")).tone(Tone::Warn).headline()
}
Some(ciphertext) => {
format!(
"Content: not on {branch}: new, or changed on a branch (blob {})",
ObjectId::blob(ciphertext).short()
)
let blob = ObjectId::blob(ciphertext);
let blob = blob.short();
Field::new("Content", format!("not on {branch}: new, or changed on a branch (blob {blob})"))
}
});
match op {
SecretOp::Set { target, .. } => lines.push(describe_target(target)),
SecretOp::Set { target, .. } => {
detail.field(describe_target(target));
}
SecretOp::Generate { target, kind, .. } => {
lines.push(describe_target(target));
lines.push(format!("Generates: {}", kind.name()));
detail.field(describe_target(target)).field(Field::new("Generates", kind.name()).code());
}
_ => {}
}
@@ -158,42 +163,48 @@ fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own:
let rules = &config.rules;
let label = |r: &Recipient| label(r, &config.names);
match context.recipients.as_ref().map(|keys| expected(keys)) {
Some(expected) if same(&expected, &recipients) => {
lines.push(format!("Recipients: as in {rules} on {branch}: {}", join(&recipients, label)));
}
let rows: Vec<Row> = match context.recipients.as_ref().map(|keys| expected(keys)) {
Some(expected) => {
sensitive = true;
lines.push(format!("⚠ Recipients differ from {rules} on {branch}:"));
for r in recipients.iter().filter(|r| !expected.contains(r)) {
lines.push(format!(" + {}", label(r)));
let mut rows = Vec::new();
for r in &recipients {
let (status, tone) =
if expected.contains(r) { ("as in the rules", Tone::Normal) } else { ("added", Tone::Warn) };
rows.push(Row::new([label(r), status.to_owned()], tone));
}
for r in expected.iter().filter(|r| !recipients.contains(r)) {
lines.push(format!(" − {}", label(r)));
rows.push(Row::new([label(r), "removed".to_owned()], Tone::Warn));
}
let kept: Vec<&Recipient> = recipients.iter().filter(|r| expected.contains(r)).collect();
if !kept.is_empty() {
lines
.push(format!(" unchanged: {}", kept.iter().map(|r| label(r)).collect::<Vec<_>>().join(", ")));
if same(&expected, &recipients) {
detail.field(Field::new("Recipients", format!("as in {rules} on {branch}")).tone(Tone::Good));
} else {
sensitive = true;
let summary = format!("differ from {rules} on {branch}");
detail.field(Field::new("Recipients", summary).tone(Tone::Warn).headline());
}
rows
}
None => {
sensitive = true;
lines.push(format!("⚠ Recipients ({path} isn't in {rules} on {branch}): {}", join(&recipients, label)));
let summary = format!("{path} isn't in {rules} on {branch}");
detail.field(Field::new("Recipients", summary).tone(Tone::Warn).headline());
recipients.iter().map(|r| Row::new([label(r), "requested".to_owned()], Tone::Normal)).collect()
}
}
};
if added {
lines.push(format!("The broker adds its own key ({}) so it can change the file later.", label(own)));
let note = format!("added ({}), so the broker can change the file later", label(own));
detail.field(Field::new("Broker's key", note));
}
detail.section(Section::table("Recipients", vec![Column::code("Key"), Column::text("Status")], rows));
}
(lines.join("\n"), sensitive)
(detail, sensitive)
}
fn describe_target(target: &Target) -> String {
fn describe_target(target: &Target) -> Field {
match target {
Target::Whole => "Replaces: the whole file".into(),
Target::Field(key) => format!("Field: {key}"),
Target::Whole => Field::new("Replaces", "the whole file"),
Target::Field(key) => Field::new("Field", key).code(),
}
}
@@ -218,10 +229,6 @@ fn label(recipient: &Recipient, names: &BTreeMap<String, Recipient>) -> String {
names.iter().find(|(_, r)| *r == recipient).map_or_else(|| recipient.abbreviated(), |(name, _)| name.clone())
}
fn join(recipients: &[Recipient], label: impl Fn(&Recipient) -> String) -> String {
recipients.iter().map(label).collect::<Vec<_>>().join(", ")
}
/// The recipients with the broker's own key, and whether it had to be added.
fn with_own(recipients: &[Recipient], own: &Recipient) -> (Vec<Recipient>, bool) {
let mut all = recipients.to_vec();
@@ -480,13 +487,15 @@ mod tests {
let read = SecretOp::Read { file };
let (detail, sensitive) = describe(&read, &context(&["secrets/test.age"], None), &config, &own);
assert!(detail.contains("Content: secrets/test.age as on master") && !sensitive, "{detail}");
let text = detail.to_text();
assert!(text.contains("Content: secrets/test.age as on master") && !sensitive, "{text}");
let (detail, sensitive) = describe(&read, &context(&["secrets/colony/borg.age"], None), &config, &own);
assert!(detail.contains("the same as secrets/colony/borg.age on master, not secrets/test.age") && sensitive);
let warning = "⚠ Content: the same as secrets/colony/borg.age on master, not secrets/test.age";
assert!(detail.brief().starts_with(warning) && sensitive, "{}", detail.brief());
let (detail, _) = describe(&read, &context(&[], None), &config, &own);
assert!(detail.contains("not on master"), "{detail}");
assert!(detail.to_text().contains("not on master"), "{}", detail.to_text());
}
#[test]
@@ -504,14 +513,38 @@ mod tests {
let rules = Some(vec![dev.to_string(), own.to_string()]);
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], rules.clone()), &config, &own);
assert!(detail.contains("Content: a new file") && detail.contains("Recipients: as in secrets.nix"), "{detail}");
assert!(detail.contains("The broker adds its own key") && !sensitive, "{detail}");
let text = detail.to_text();
assert!(text.contains("Content: a new file") && text.contains("Recipients: as in secrets.nix"), "{text}");
assert!(text.contains("Broker's key: added") && !sensitive, "{text}");
assert_eq!(
statuses(&detail),
[
("dev".into(), "as in the rules".into(), Tone::Normal),
(own.abbreviated(), "as in the rules".into(), Tone::Normal)
]
);
let (detail, sensitive) = describe(&set(vec![host.clone(), own.clone()]), &context(&[], rules), &config, &own);
assert!(sensitive && detail.contains(&format!(" + {}", host.abbreviated())) && detail.contains(" − dev"));
assert!(sensitive && detail.brief().starts_with("⚠ Recipients: differ from secrets.nix"));
assert_eq!(
statuses(&detail),
[
(host.abbreviated(), "added".into(), Tone::Warn),
(own.abbreviated(), "as in the rules".into(), Tone::Normal),
("dev".into(), "removed".into(), Tone::Warn),
]
);
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], None), &config, &own);
assert!(sensitive && detail.contains("isn't in secrets.nix"), "{detail}");
assert!(sensitive && detail.to_text().contains("isn't in secrets.nix"), "{}", detail.to_text());
}
/// Each recipient row's key, status and tone.
fn statuses(detail: &Detail) -> Vec<(String, String, Tone)> {
let Some(Section::Table { rows, .. }) = detail.sections.iter().find(|s| s.title() == "Recipients") else {
panic!("no recipients table");
};
rows.iter().map(|r| (r.cells[0].clone(), r.cells[1].clone(), r.tone)).collect()
}
#[test]
+5 -3
View File
@@ -8,6 +8,8 @@ use anyhow::{Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use tokio::sync::{oneshot, watch};
use crate::detail::Detail;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Decision {
@@ -90,7 +92,7 @@ pub struct PendingInfo {
pub requester: String,
pub op: String,
pub summary: String,
pub detail: String,
pub detail: Detail,
/// Agent-supplied; never trusted.
pub label: Option<String>,
/// Marks requests that reveal a secret or change who can read one.
@@ -107,7 +109,7 @@ pub struct NewRequest {
pub op: String,
pub lease_key: String,
pub summary: String,
pub detail: String,
pub detail: Detail,
pub label: Option<String>,
pub sensitive: bool,
pub passkey: bool,
@@ -315,7 +317,7 @@ mod tests {
op: "ssh".into(),
lease_key: key.into(),
summary: "ssh river".into(),
detail: String::new(),
detail: Detail::new(),
label: None,
sensitive: false,
passkey: false,
+3 -3
View File
@@ -191,7 +191,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
requester: requester.to_owned(),
op: parsed.op.to_owned(),
summary: parsed.summary.clone(),
detail: parsed.detail.clone(),
detail: parsed.detail.to_text(),
label: label.clone(),
});
@@ -235,7 +235,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
Ok(gate) => gate,
Err(error) => return failed(error),
};
log(Event::Prepared { id: id.clone(), detail: gate.detail.clone() });
log(Event::Prepared { id: id.clone(), detail: gate.detail.to_text() });
let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await {
Ok(Some(approval)) => approval,
@@ -259,7 +259,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
return failed(error);
}
log(Event::Prepared { id: id.clone(), detail: parsed.detail.clone() });
log(Event::Prepared { id: id.clone(), detail: parsed.detail.to_text() });
}
let (approved_by, approver) = match authorize(broker, &id, requester, &parsed, label, io).await {
+114
View File
@@ -140,6 +140,120 @@ h2 {
color: var(--warn-text);
}
/* A request's fields: labels beside values, stacked on narrow screens. */
dl.fields {
display: grid;
grid-template-columns: max-content 1fr;
gap: 2px 12px;
margin: 8px 0;
}
dl.fields dt {
color: var(--muted);
}
dl.fields dd {
margin: 0;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
dl.fields dd.good {
color: var(--good);
}
dl.fields dd.warn,
table.detail tr.warn td {
background: var(--warn-bg);
color: var(--warn-text);
}
dl.fields dd.warn {
padding: 0 4px;
border-radius: 4px;
}
dl.fields dd.warn::before,
table.detail tr.warn td:first-child::before {
content: "⚠ ";
}
@media (max-width: 30rem) {
dl.fields {
grid-template-columns: 1fr;
}
dl.fields dd {
margin-bottom: 6px;
}
}
/* Code in details: on a tint, wrapping anywhere so long paths and keys fit a phone. */
dl.fields code,
section.detail li code,
table.detail code {
padding: 0 3px;
border-radius: 3px;
background: var(--code-bg);
overflow-wrap: anywhere;
}
dl.fields dd.warn code,
table.detail tr.warn code {
background: none;
}
/* Diffs: whole lines tinted, so changes stand out while scrolling sideways. */
pre.diff span {
display: inline-block;
min-width: 100%;
}
pre.diff .diff-add {
background: var(--good-bg);
color: var(--good);
}
pre.diff .diff-del {
background: var(--bad-bg);
color: var(--bad);
}
pre.diff .diff-hunk {
color: var(--active);
}
pre.diff .diff-meta {
color: var(--muted);
}
section.detail h3 {
margin: 12px 0 4px;
font-size: 0.95rem;
}
section.detail ul {
margin: 4px 0;
padding-left: 20px;
overflow-wrap: anywhere;
}
/* Tables in details keep code (keys, paths, versions) on one line and wrap text between words,
like the audit log; a table wider than the card scrolls sideways inside `.scroll`. */
table.detail {
font-size: 0.9rem;
}
table.detail th,
table.detail td.code {
white-space: nowrap;
}
table.detail td {
overflow-wrap: normal;
min-width: 5rem;
}
details summary {
cursor: pointer;
color: var(--muted);
+5 -4
View File
@@ -181,7 +181,7 @@ fn urlencode(text: &str) -> String {
/// A hash of what an approver was shown, so a confirmation only applies to what they saw.
fn fingerprint(entry: &PendingInfo) -> String {
let mut hash = Sha256::new();
for part in [&entry.requester, &entry.op, &entry.summary, &entry.detail] {
for part in [&entry.requester, &entry.op, &entry.summary, &entry.detail.to_text()] {
hash.update(part.as_bytes());
hash.update([0]);
}
@@ -492,6 +492,7 @@ async fn signed_out() -> Response {
#[cfg(test)]
mod tests {
use super::*;
use crate::detail::Detail;
#[test]
fn origins() {
@@ -507,15 +508,15 @@ mod tests {
requester: "slop-cannon".into(),
op: "deploy".into(),
summary: "deploy river".into(),
detail: "x".into(),
detail: Detail::of("Command", "x"),
label: None,
sensitive: false,
passkey: true,
offers: vec![],
expires_in: 10,
};
let changed = PendingInfo { detail: "y".into(), ..entry.clone() };
let shifted = PendingInfo { summary: "deploy river\0x".into(), detail: String::new(), ..entry.clone() };
let changed = PendingInfo { detail: Detail::of("Command", "y"), ..entry.clone() };
let shifted = PendingInfo { summary: "deploy river\0x".into(), detail: Detail::new(), ..entry.clone() };
assert_ne!(fingerprint(&entry), fingerprint(&changed));
assert_ne!(fingerprint(&entry), fingerprint(&shifted));
assert_eq!(fingerprint(&entry), fingerprint(&PendingInfo { expires_in: 3, ..entry.clone() }));
+33 -2
View File
@@ -9,6 +9,7 @@ use axum::response::{Html, IntoResponse, Response};
use super::history::{self, History};
use crate::audit::{Record, short};
use crate::detail::{Column, Detail, Section};
use crate::ops::printable;
use crate::queue::{Decision, PendingInfo};
@@ -52,6 +53,20 @@ fn answer(decision: &Decision) -> String {
}
}
/// Whether a table's column holds code.
fn is_code(columns: &[Column], index: &usize) -> bool {
columns.get(*index).is_some_and(|c| c.code)
}
fn diff_lines(text: &str) -> Vec<(&'static str, &str)> {
crate::detail::diff_lines(text)
}
/// What a request's folded details hold, like `Recipients` or `Commits, Diff`.
fn section_titles(detail: &Detail) -> String {
detail.sections.iter().map(Section::title).collect::<Vec<_>>().join(", ")
}
fn describe(record: &Record) -> (String, Option<String>) {
history::describe(&record.event)
}
@@ -217,12 +232,24 @@ mod tests {
#[test]
fn cards_offer_each_answer() {
use crate::detail::{Field, Row, Tone};
let entry = PendingInfo {
id: "abc".into(),
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: "ssh river <x>".into(),
detail: "one\ntwo".into(),
detail: {
let mut detail = Detail::code("Command", "uptime");
detail.field(Field::new("Content", "another file's").tone(Tone::Warn));
detail.section(Section::table(
"Recipients",
vec![Column::code("Key"), Column::text("Status")],
[Row::new(["dev", "added"], Tone::Warn)],
));
detail.section(Section::diff("Diff", "@@ -1 +1 @@\n-b\n+a"));
detail
},
label: Some("<script>".into()),
sensitive: true,
passkey: true,
@@ -234,7 +261,11 @@ mod tests {
assert!(html.contains("For 5m"));
assert!(html.contains("ssh river &#60;x&#62;"));
assert!(!html.contains("<script>"));
assert!(html.contains("Details (2 lines)"));
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"));
assert!(html.contains("<dd class=\"warn\">another file&#39;s</dd>"));
assert!(html.contains("Details (Recipients, Diff)"));
assert!(html.contains("<tr class=\"warn\"><td class=\"code\"><code>dev</code></td><td>added</td></tr>"));
assert!(html.contains("<span class=\"diff-del\">-b</span>\n<span class=\"diff-add\">+a</span>"), "{html}");
assert!(html.contains("expires in 2m 5s"));
assert!(html.contains("needs-passkey"));
assert!(html.contains("Needs passkey"));
+2 -2
View File
@@ -237,7 +237,7 @@ pub fn notification(entry: &PendingInfo) -> serde_json::Value {
}
actions.push(json!({ "action": Decision::Deny.name(), "title": Decision::Deny.title() }));
let mut body = format!("{}\n{}", entry.summary, truncate(&entry.detail, 300));
let mut body = format!("{}\n{}", entry.summary, truncate(&entry.detail.brief(), 300));
if let Some(label) = &entry.label {
body += &format!("\nLabel (agent-supplied): {}", truncate(label, 120));
}
@@ -287,7 +287,7 @@ mod tests {
requester: "slop-cannon".into(),
op: "deploy".into(),
summary: "deploy river".into(),
detail: "Commits:\n…".into(),
detail: crate::detail::Detail::of("Commit", "0123456"),
label: None,
sensitive: false,
passkey: false,
+41 -4
View File
@@ -12,10 +12,7 @@
{% if let Some(label) = entry.label %}
<p class="label">Label (agent-supplied): {{ label }}</p>
{% endif %}
{% let lines = entry.detail.lines().count() %}
{% if lines > 0 %}
<details{% if open %} open{% endif %}><summary>Details ({{ lines }} line{% if lines != 1 %}s{% endif %})</summary><pre>{{ entry.detail }}</pre></details>
{% endif %}
{% call detail(entry.detail, open) %}{% endcall %}
<form method="post" action="/requests/{{ entry.id }}" class="answers">
<input type="hidden" name="csrf" value="{{ csrf }}">
{% for decision in entry.offers %}
@@ -30,6 +27,46 @@
</article>
{% endmacro %}
{# Fields stay in view; tables, lists and text fold away unless `open`. #}
{% macro detail(detail, open) %}
{% if !detail.fields.is_empty() %}
<dl class="fields">
{% for field in detail.fields %}
<dt>{{ field.label }}</dt><dd class="{{ field.tone.class() }}">{% if field.code %}<code>{{ field.value }}</code>{% else %}{{ field.value }}{% endif %}</dd>
{% endfor %}
</dl>
{% endif %}
{% if !detail.sections.is_empty() %}
<details{% if open %} open{% endif %}><summary>Details ({{ self::section_titles(detail) }})</summary>
{% for section in detail.sections %}
<section class="detail">
<h3>{{ section.title() }}</h3>
{% match section %}
{% when Section::Table with { columns, rows, more, .. } %}
<div class="scroll"><table class="detail">
<thead><tr>{% for column in columns %}<th>{{ column.title }}</th>{% endfor %}</tr></thead>
<tbody>
{% for row in rows %}<tr class="{{ row.tone.class() }}">{% for cell in row.cells %}{% if self::is_code(columns, loop.index0) %}<td class="code"><code>{{ cell }}</code></td>{% else %}<td>{{ cell }}</td>{% endif %}{% endfor %}</tr>
{% endfor %}
</tbody></table></div>
{% if *more > 0 %}<p class="note">… {{ more }} more</p>{% endif %}
{% when Section::List with { items, more, code, .. } %}
<ul>{% for item in items %}<li>{% if *code %}<code>{{ item }}</code>{% else %}{{ item }}{% endif %}</li>{% endfor %}</ul>
{% if *more > 0 %}<p class="note">… {{ more }} more</p>{% endif %}
{% when Section::Text with { text, diff, .. } %}
{% if *diff %}
<pre class="diff">{% for (kind, line) in self::diff_lines(text) %}<span class="diff-{{ kind }}">{{ line }}</span>
{% endfor %}</pre>
{% else %}
<pre>{{ text }}</pre>
{% endif %}
{% endmatch %}
</section>
{% endfor %}
</details>
{% endif %}
{% endmacro %}
{% macro time(rfc3339) -%}
<time datetime="{{ rfc3339 }}">{{ rfc3339.replace('T', " ").trim_end_matches('Z') }} UTC</time>
{%- endmacro %}
+3 -3
View File
@@ -524,10 +524,10 @@ async fn secrets_are_checked_against_the_branch_and_read_always_asks() {
let mut client = Client::start(&broker, set).await;
let ServerMessage::Pending { id, .. } = client.next_quiet(&mut output).await else { panic!("expected pending") };
let pending = broker.queue.list();
let detail = &pending[0].detail;
let detail = &pending[0].detail.to_text();
assert!(detail.contains("Content: secrets/a.env.age as on master"), "{detail}");
assert!(detail.contains("Recipients: as in secrets.nix on master"), "{detail}");
assert!(detail.contains("The broker adds its own key") && !pending[0].sensitive, "{detail}");
assert!(detail.contains("Broker's key: added") && !pending[0].sensitive, "{detail}");
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(client.next_quiet(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true });
@@ -547,7 +547,7 @@ async fn secrets_are_checked_against_the_branch_and_read_always_asks() {
let pending = broker.queue.list();
assert_eq!(pending[0].offers, [Decision::Once, Decision::Deny]);
assert!(pending[0].sensitive);
assert!(pending[0].detail.contains("the same as secrets/a.env.age on master, not secrets/harmless.age"));
assert!(pending[0].detail.to_text().contains("the same as secrets/a.env.age on master, not secrets/harmless.age"));
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(