web: Add approvals web app

A web app lists pending requests with full detail, leases and the
audit log grouped by request, and sends Web Push notifications that can
answer requests. Approvers sign in through an OpenID Connect provider;
policy can require a fresh passkey (`confirm = "passkey"`) to approve,
which only the web app can then give.

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:36 +00:00
1 parent 5a4cdddd7f
commit 076f4959d9
32 files changed
+5325 -57

No files matched your search

Generated
+2798 -16
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -7,6 +7,10 @@ license = "MIT"
[dependencies]
anyhow = "1"
askama = "0.16"
async-trait = "0.1.92"
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "query", "form", "json"] }
base64 = "0.23.1"
bytes = "1"
ciborium = "0.2"
clap = { version = "4", features = ["derive", "env"] }
@@ -15,17 +19,22 @@ hex = "0.4"
humantime = "2"
# Already a dependency of `tokio-vsock`
nix = { version = "0.31", default-features = false, features = ["signal", "user"] }
openidconnect = "4.1"
rand = "0.9"
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
serde_json = "1"
sha2 = "0.11.1"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = { version = "0.27", features = ["rustls-tls-webpki-roots"] }
tokio-util = { version = "0.7", features = ["codec"] }
tokio-vsock = "0.7"
toml = { version = "0.9", default-features = false, features = ["parse", "serde", "std"] }
tower-sessions = "0.15"
tower-sessions-rusqlite-store = "0.15"
url = "2"
web-push = { version = "0.11", default-features = false }
[dev-dependencies]
tempfile = "3"
+9
View File
@@ -0,0 +1,9 @@
[general]
# Collapses the blank lines that tags leave behind
whitespace = "minimize"
# What the pages show passes through `printable` before escaping, so control and bidirectional
# characters can't disguise what a request does
[[escaper]]
path = "crate::web::page::Printable"
extensions = ["html"]
+3 -2
View File
@@ -4,8 +4,9 @@
{
languages.rust.enable = true;
# `git` for the builder's tests
packages = with pkgs; [ git nixpkgs-fmt ];
# `pkg-config` with OpenSSL for Web Push's payload encryption and SQLite for the web app's
# sessions, `git` for the builder's tests
packages = with pkgs; [ pkg-config openssl sqlite git nixpkgs-fmt ];
scripts = {
vm-test = {
+32 -3
View File
@@ -10,6 +10,7 @@ let
cfg = config.services.slop-broker;
ha = cfg.homeAssistant;
web = cfg.web;
isRuntimePath = p: hasPrefix "/" p && !(hasPrefix "/nix/store/" p);
hasLocalRequesters = any (r: r.uid != null) (attrValues cfg.requesters);
@@ -37,11 +38,14 @@ let
options = {
action = mkOpt' (enum [ "auto" "ask" "deny" ]) "ask" "What happens to a request.";
leases = mkOpt' (listOf duration) [ ] "Lease lengths approvers are offered, like `5m` or `1h`.";
confirm = mkOpt' (nullOr (enum [ "passkey" ])) null
"Extra proof needed to approve: `passkey` means signing in again with a passkey in the web app.";
rules = mkOpt' (listOf (submodule {
options = {
match = mkOpt' (attrsOf str) { } "Scope fields and the globs they must match.";
action = mkOpt' (enum [ "auto" "ask" "deny" ]) null "Action for matching requests.";
leases = mkOpt' (nullOr (listOf duration)) null "Leases for matching requests (null keeps the default).";
confirm = mkOpt' (nullOr (enum [ "passkey" ])) null "Extra proof for matching requests (null keeps the default).";
};
})) [ ] "Rules checked in order; the first match wins.";
};
@@ -115,6 +119,14 @@ let
device_id = ha.deviceId;
token = "ha-token";
} else null;
web = if web.enable then {
listen = "${if hasInfix ":" web.address then "[${web.address}]" else web.address}:${toString web.port}";
inherit (web) url issuer group;
client_id = web.clientId;
client_secret = "oidc-secret";
state_dir = "/var/lib/slop-broker/web";
} else null;
});
in
{
@@ -174,6 +186,17 @@ in
"The Companion app's own ID (the `device_id` in its notification answers, not the device registry's); the broker logs it when it ignores an answer.";
tokenFile = mkOpt' str "" "Runtime path to a Home Assistant token; never a Nix store path.";
};
web = {
enable = mkBoolOpt' false "Whether to serve the approvals web app (sign-in with OpenID Connect, Web Push).";
address = mkOpt' str "127.0.0.1" "Address the web app listens on; only the reverse proxy should reach it.";
port = mkOpt' port 8095 "Port the web app listens on.";
url = mkOpt' str "" "Public URL of the web app, without a path.";
issuer = mkOpt' str "" "OpenID Connect issuer approvers sign in with.";
clientId = mkOpt' str "slop-approve" "OpenID Connect client ID.";
clientSecretFile = mkOpt' str "" "Runtime path to the client secret; never a Nix store path.";
group = mkOpt' str "slop-approvers" "Group (the ID token's `groups` claim) whose members may approve.";
};
};
config = mkIf cfg.enable {
@@ -202,6 +225,10 @@ in
assertion = ha.enable -> (ha.url != "" && ha.notifyService != "" && ha.deviceId != "" && isRuntimePath ha.tokenFile);
message = "slop-broker Home Assistant needs a URL, service, device ID and runtime token file.";
}
{
assertion = web.enable -> (web.url != "" && web.issuer != "" && isRuntimePath web.clientSecretFile);
message = "slop-broker's web app needs a URL, an issuer and a runtime client secret file.";
}
];
users = mkMerge [
@@ -228,6 +255,7 @@ in
];
environment.systemPackages = [ cfg.package ];
boot.kernelModules = optional hasVsockRequesters "vhost_vsock";
systemd.services.slop-broker = {
@@ -240,14 +268,15 @@ in
LoadCredential =
optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++
optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++
optional ha.enable "ha-token:${ha.tokenFile}";
optional ha.enable "ha-token:${ha.tokenFile}" ++
optional web.enable "oidc-secret:${web.clientSecretFile}";
User = "slop-broker";
Group = "slop-broker";
SupplementaryGroups = [ "slop-broker-approve" ] ++ optional hasRemote remoteUser;
RuntimeDirectory = "slop-broker";
RuntimeDirectoryMode = "0755";
StateDirectory = "slop-broker";
StateDirectory = [ "slop-broker" ] ++ optional web.enable "slop-broker/web";
StateDirectoryMode = "0700";
Restart = "on-failure";
@@ -263,7 +292,7 @@ in
LockPersonality = true;
RestrictAddressFamilies = [ "AF_UNIX" ]
++ optional hasVsockRequesters "AF_VSOCK"
++ optionals (cfg.ssh.enable || ha.enable) [ "AF_INET" "AF_INET6" ];
++ optionals (cfg.ssh.enable || ha.enable || web.enable) [ "AF_INET" "AF_INET6" ];
CapabilityBoundingSet = "";
UMask = "0077";
};
+6 -2
View File
@@ -1,4 +1,4 @@
{ lib, rustPlatform, callPackage }:
{ lib, rustPlatform, pkg-config, openssl, sqlite }:
let
inherit (lib.fileset) toSource unions;
in
@@ -8,10 +8,14 @@ rustPlatform.buildRustPackage {
src = toSource {
root = ../.;
fileset = unions [ ../Cargo.toml ../Cargo.lock ../src ../tests ../slop-tools.md ];
fileset = unions [ ../Cargo.toml ../Cargo.lock ../askama.toml ../src ../templates ../tests ../slop-tools.md ];
};
cargoLock.lockFile = ../Cargo.lock;
# OpenSSL for Web Push's payload encryption, SQLite for the web app's sessions
nativeBuildInputs = [ pkg-config ];
buildInputs = [ openssl sqlite ];
postInstall = ''
ln -s slop-broker $out/bin/slop-approve
install -Dm644 slop-tools.md $out/share/slop-broker/slop-tools.md
+10 -5
View File
@@ -62,16 +62,17 @@ fn answer(broker: &Broker, approver: &str, request: ApproveRequest) -> Result<Ap
match request {
ApproveRequest::List => Ok(ApproveResponse::Pending(broker.queue.list())),
ApproveRequest::Decide { id, decision } => {
approve(broker, &id, decision, approver)?;
approve(broker, &id, decision, approver, false)?;
Ok(ApproveResponse::Recorded)
}
ApproveRequest::Log { count } => Ok(ApproveResponse::Log(broker.audit.tail(count.min(MAX_LOG_RECORDS))?)),
}
}
/// Records a decision from any approver (terminal or phone).
pub fn approve(broker: &Broker, id: &str, decision: Decision, approver: &str) -> Result<()> {
let info = broker.queue.decide(id, decision, approver)?;
/// Records a decision from any approver (terminal, phone or web). `passkey` says the approver
/// just confirmed it with a passkey.
pub fn approve(broker: &Broker, id: &str, decision: Decision, approver: &str, passkey: bool) -> Result<()> {
let info = broker.queue.decide(id, decision, approver, passkey)?;
broker.audit.log(Event::Decision {
id: id.to_owned(),
requester: info.requester,
@@ -108,7 +109,10 @@ impl Client {
}
pub fn format(entry: &PendingInfo, full: bool) -> String {
let marker = if entry.sensitive { " [SENSITIVE]" } else { "" };
let mut marker = if entry.sensitive { " [SENSITIVE]" } else { "" }.to_owned();
if entry.passkey {
marker += " [PASSKEY: approve in the web app]";
}
let mut text =
format!("{} {} {}{marker} (expires in {}s)\n", entry.id, entry.requester, entry.summary, entry.expires_in);
@@ -315,6 +319,7 @@ mod tests {
detail: String::new(),
label: None,
sensitive: false,
passkey: false,
offers: vec![Decision::Once, Decision::Deny],
expires_in: 60,
}
+16 -1
View File
@@ -9,7 +9,7 @@ use nix::sys::signal::{SigHandler, Signal, signal};
use slop_broker::config::{Config, credential, group_id, user_id};
use slop_broker::remote::{self, Role};
use slop_broker::server::{self, Broker};
use slop_broker::{approve, ha};
use slop_broker::{approve, ha, web};
#[derive(Parser)]
#[command(about = "Approval broker for coding agents")]
@@ -93,6 +93,17 @@ async fn serve(path: &Path) -> Result<()> {
None => None,
};
let web = match &config.web {
Some(settings) => {
let secret = std::fs::read_to_string(credential(&settings.client_secret))
.context("reading the OIDC client secret")?;
let secret = secret.trim().to_owned();
anyhow::ensure!(!secret.is_empty(), "the OIDC client secret is empty");
Some((settings.clone(), secret))
}
None => None,
};
server::check_runtime_dir(&config.approve_socket)?;
let approve_listener = server::bind_unix(&config.approve_socket, 0o660, Some(group_id(&config.approver_group)?))?;
let request_listener = match &config.request_socket {
@@ -133,6 +144,10 @@ async fn serve(path: &Path) -> Result<()> {
});
}
if let Some((settings, secret)) = web {
tasks.spawn(web::run(broker.clone(), settings, secret));
}
eprintln!("<6>slop-broker ready");
// Any listener failing is fatal; systemd restarts the broker.
tasks.join_next().await.context("no listeners")???;
+29
View File
@@ -43,6 +43,35 @@ pub struct Config {
pub deploy: Option<DeployConfig>,
#[serde(default)]
pub cache: Option<CacheConfig>,
#[serde(default)]
pub web: Option<WebConfig>,
}
/// The approvals web app (see [`crate::web`]): approvers sign in through an OpenID Connect
/// provider, and get Web Push notifications.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WebConfig {
/// Address to listen on, like `[::]:8095`; only the reverse proxy should reach it.
pub listen: std::net::SocketAddr,
/// Public URL of the app, like `https://approve.example.org`.
pub url: String,
/// OpenID Connect issuer.
pub issuer: String,
pub client_id: String,
/// Client secret; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
pub client_secret: PathBuf,
/// Only members of this group (the ID token's `groups` claim) may sign in.
pub group: String,
/// How long a session lasts without being used.
#[serde(default = "default_session", deserialize_with = "duration")]
pub session: u64,
/// Where sessions, push subscriptions and the push signing key are kept.
pub state_dir: PathBuf,
}
fn default_session() -> u64 {
7 * 86400
}
/// Deploys: a builder evaluates and builds commits, then the broker copies and activates them
+12 -5
View File
@@ -152,10 +152,14 @@ impl Notifier<'_> {
}
fn notification(&mut self, entry: &PendingInfo) -> Value {
// Android shows at most three actions: once, the shortest lease and deny.
let mut decisions = vec![Decision::Once];
if let Some(&lease) = entry.offers.iter().find(|d| matches!(d, Decision::Lease(_))) {
decisions.push(lease);
// Android shows at most three actions: once, the shortest lease and deny. Requests that
// need a passkey can only be denied here.
let mut decisions = vec![];
if !entry.passkey {
decisions.push(Decision::Once);
if let Some(&lease) = entry.offers.iter().find(|d| matches!(d, Decision::Lease(_))) {
decisions.push(lease);
}
}
decisions.push(Decision::Deny);
@@ -174,6 +178,9 @@ impl Notifier<'_> {
message += &format!("\nAgent says: {}", truncate(label, 120));
}
message += &format!("\nFrom {}", entry.requester);
if entry.passkey {
message += "\nNeeds a passkey: approve in the web app";
}
let title = if entry.sensitive { "Agent approval (sensitive)" } else { "Agent approval" };
// Sticky, so tapping it doesn't remove it, and persistent, which stops swiping it away on
@@ -207,7 +214,7 @@ impl Notifier<'_> {
return;
};
// Fails harmlessly if it expired, was answered in a terminal, or arrived twice.
let _ = approve::approve(self.broker, &id, decision, "home-assistant");
let _ = approve::approve(self.broker, &id, decision, "home-assistant", false);
self.actions.retain(|_, (other, _)| *other != id);
}
}
+1
View File
@@ -13,3 +13,4 @@ pub mod queue;
pub mod remote;
pub mod server;
pub mod types;
pub mod web;
+45 -12
View File
@@ -5,14 +5,23 @@ use std::collections::BTreeMap;
use serde::Deserialize;
use serde_json::{Map, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Action {
Auto,
#[default]
Ask,
Deny,
}
/// Extra proof an approver must give before approving.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Confirm {
/// Signing in again with a passkey, in the web app.
Passkey,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpPolicy {
@@ -20,7 +29,9 @@ pub struct OpPolicy {
/// Lease lengths in seconds that approvers are offered.
#[serde(default, deserialize_with = "crate::config::durations")]
pub leases: Vec<u64>,
/// First matching rule wins; otherwise `action` and `leases` apply.
#[serde(default)]
pub confirm: Option<Confirm>,
/// First matching rule wins; otherwise `action`, `leases` and `confirm` apply.
#[serde(default)]
pub rules: Vec<Rule>,
}
@@ -33,13 +44,18 @@ pub struct Rule {
pub action: Action,
#[serde(default, deserialize_with = "crate::config::optional_durations")]
pub leases: Option<Vec<u64>>,
/// Replaces the operation's `confirm` (null keeps it).
#[serde(default)]
pub confirm: Option<Confirm>,
}
/// What policy decided for one request.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Verdict {
pub action: Action,
pub leases: Vec<u64>,
/// Approving needs a fresh passkey.
pub passkey: bool,
}
/// Limits an operation puts on its own requests, whatever the policy says.
@@ -53,15 +69,16 @@ pub struct Limits {
pub fn evaluate(policy: Option<&OpPolicy>, scope: &Map<String, Value>, limits: Limits) -> Verdict {
let Some(policy) = policy else {
return Verdict { action: Action::Deny, leases: vec![] };
return Verdict { action: Action::Deny, ..Verdict::default() };
};
let (mut action, mut leases) = (policy.action, policy.leases.clone());
let (mut action, mut leases, mut confirm) = (policy.action, policy.leases.clone(), policy.confirm);
if let Some(rule) = policy.rules.iter().find(|r| matches(&r.matches, scope)) {
action = rule.action;
if let Some(rule_leases) = &rule.leases {
leases = rule_leases.clone();
}
confirm = rule.confirm.or(confirm);
}
if limits.never_auto && action == Action::Auto {
@@ -70,16 +87,18 @@ pub fn evaluate(policy: Option<&OpPolicy>, scope: &Map<String, Value>, limits: L
if limits.never_lease {
leases.clear();
}
Verdict { action, leases }
Verdict { action, leases, passkey: confirm == Some(Confirm::Passkey) }
}
/// The strictest of several verdicts: the highest action, and only leases all of them allow.
/// The strictest of several verdicts: the highest action, only leases all of them allow, and a
/// passkey if any needs one.
pub fn combine(verdicts: impl IntoIterator<Item = Verdict>) -> Verdict {
let mut verdicts = verdicts.into_iter();
let Some(mut combined) = verdicts.next() else { return Verdict { action: Action::Deny, leases: vec![] } };
let Some(mut combined) = verdicts.next() else { return Verdict { action: Action::Deny, ..Verdict::default() } };
for verdict in verdicts {
combined.action = combined.action.max(verdict.action);
combined.leases.retain(|l| verdict.leases.contains(l));
combined.passkey |= verdict.passkey;
}
combined
}
@@ -129,9 +148,12 @@ mod tests {
#[test]
fn combining_takes_the_strictest() {
let verdict = |action, leases: &[u64]| Verdict { action, leases: leases.to_vec() };
let verdict = |action, leases: &[u64]| Verdict { action, leases: leases.to_vec(), passkey: false };
let combined = combine([verdict(Action::Auto, &[300, 3600]), verdict(Action::Ask, &[300])]);
assert_eq!(combined, verdict(Action::Ask, &[300]));
let passkey = Verdict { passkey: true, ..verdict(Action::Ask, &[300]) };
assert!(combine([verdict(Action::Ask, &[300]), passkey]).passkey);
assert_eq!(combine([verdict(Action::Ask, &[]), verdict(Action::Deny, &[])]).action, Action::Deny);
assert_eq!(combine([]).action, Action::Deny);
}
@@ -166,14 +188,25 @@ mod tests {
"rules": [
{"match": {"target": "river"}, "action": "deny"},
{"match": {"target": "r*"}, "action": "auto", "leases": []},
{"match": {"target": "stream"}, "action": "ask", "confirm": "passkey"},
],
}))
.unwrap();
let verdict = |s| evaluate(Some(&policy), &scope(s), Limits::default());
assert_eq!(verdict(json!({"target": "river"})).action, Action::Deny);
assert_eq!(verdict(json!({"target": "rain"})), Verdict { action: Action::Auto, leases: vec![] });
assert_eq!(verdict(json!({"target": "sfh"})), Verdict { action: Action::Ask, leases: vec![300, 3600] });
assert_eq!(
verdict(json!({"target": "rain"})),
Verdict { action: Action::Auto, leases: vec![], passkey: false }
);
assert_eq!(
verdict(json!({"target": "sfh"})),
Verdict { action: Action::Ask, leases: vec![300, 3600], passkey: false }
);
assert_eq!(
verdict(json!({"target": "stream"})),
Verdict { action: Action::Ask, leases: vec![300, 3600], passkey: true }
);
assert_eq!(verdict(json!({"host": "river"})).action, Action::Ask);
assert_eq!(verdict(json!({"target": 5})).action, Action::Ask);
}
@@ -183,6 +216,6 @@ mod tests {
let policy: OpPolicy = serde_json::from_value(json!({"action": "auto", "leases": [300]})).unwrap();
let limits = Limits { never_auto: true, never_lease: true };
let verdict = evaluate(Some(&policy), &Map::new(), limits);
assert_eq!(verdict, Verdict { action: Action::Ask, leases: vec![] });
assert_eq!(verdict, Verdict { action: Action::Ask, leases: vec![], passkey: false });
}
}
+53 -8
View File
@@ -95,6 +95,9 @@ pub struct PendingInfo {
pub label: Option<String>,
/// Marks requests that reveal a secret or change who can read one.
pub sensitive: bool,
/// Approving needs a fresh passkey, so only the web app can approve it.
#[serde(default)]
pub passkey: bool,
pub offers: Vec<Decision>,
pub expires_in: u64,
}
@@ -107,6 +110,7 @@ pub struct NewRequest {
pub detail: String,
pub label: Option<String>,
pub sensitive: bool,
pub passkey: bool,
pub leases: Vec<u64>,
}
@@ -207,10 +211,16 @@ impl Queue {
}
}
pub fn decide(&self, id: &str, decision: Decision, approver: &str) -> Result<PendingInfo> {
/// Records an answer. `passkey` says the approver just confirmed it with a passkey, which
/// requests that need one require for anything but a denial.
pub fn decide(&self, id: &str, decision: Decision, approver: &str, passkey: bool) -> Result<PendingInfo> {
let mut state = self.state.lock().unwrap();
let entry = state.pending.get(id).ok_or_else(|| anyhow!("unknown or expired request"))?;
if entry.request.passkey && decision != Decision::Deny && !passkey {
bail!("this request needs a passkey; approve it in the web app");
}
if let Decision::Lease(seconds) = decision
&& !entry.request.leases.contains(&seconds)
{
@@ -249,19 +259,29 @@ impl Queue {
/// Active leases for one requester, as (scope key, seconds left).
pub fn leases(&self, requester: &str) -> Vec<(String, u64)> {
self.all_leases().into_iter().filter(|(r, _, _)| r == requester).map(|(_, key, left)| (key, left)).collect()
}
/// Every active lease, as (requester, scope key, seconds left).
pub fn all_leases(&self) -> Vec<(String, String, u64)> {
let state = self.state.lock().unwrap();
let now = Instant::now();
let mut leases: Vec<_> = state
.leases
.iter()
.filter(|((r, _), until)| r == requester && **until > now)
.map(|((_, key), until)| (key.clone(), until.duration_since(now).as_secs()))
.filter(|(_, until)| **until > now)
.map(|((requester, key), until)| (requester.clone(), key.clone(), until.duration_since(now).as_secs()))
.collect();
leases.sort();
leases
}
/// The current version of the pending set, which [`Queue::subscribe`] reports changes of.
pub fn version(&self) -> u64 {
self.state.lock().unwrap().sequence
}
}
fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo {
@@ -279,6 +299,7 @@ fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo {
detail: r.detail.clone(),
label: r.label.clone(),
sensitive: r.sensitive,
passkey: r.passkey,
offers,
expires_in: entry.deadline.saturating_duration_since(now).as_secs(),
}
@@ -297,6 +318,7 @@ mod tests {
detail: String::new(),
label: None,
sensitive: false,
passkey: false,
leases: vec![300],
}
}
@@ -321,7 +343,7 @@ mod tests {
async fn lease_covers_the_same_scope_only() {
let queue = Queue::new(Duration::from_secs(60), 64);
let (id, reply) = submit(&queue, "a", 4).unwrap();
queue.decide(&id, Decision::Lease(300), "dev").unwrap();
queue.decide(&id, Decision::Lease(300), "dev", false).unwrap();
assert_eq!(reply.await.unwrap(), Outcome::Approved { decision: Decision::Lease(300), approver: "dev".into() });
assert!(queue.leased("a", "k"));
assert!(!queue.leased("a", "other"));
@@ -332,23 +354,46 @@ mod tests {
async fn once_and_deny_leave_no_lease() {
let queue = Queue::new(Duration::from_secs(60), 64);
let (id, reply) = submit(&queue, "a", 4).unwrap();
queue.decide(&id, Decision::Once, "dev").unwrap();
queue.decide(&id, Decision::Once, "dev", false).unwrap();
assert_eq!(reply.await.unwrap(), Outcome::Approved { decision: Decision::Once, approver: "dev".into() });
let (id, reply) = submit(&queue, "a", 4).unwrap();
queue.decide(&id, Decision::Deny, "dev").unwrap();
queue.decide(&id, Decision::Deny, "dev", false).unwrap();
assert_eq!(reply.await.unwrap(), Outcome::Denied);
assert!(!queue.leased("a", "k"));
assert!(queue.decide(&id, Decision::Once, "dev").is_err());
assert!(queue.decide(&id, Decision::Once, "dev", false).is_err());
}
#[test]
fn unoffered_leases_are_refused() {
let queue = Queue::new(Duration::from_secs(60), 64);
let (id, _reply) = submit(&queue, "a", 4).unwrap();
assert!(queue.decide(&id, Decision::Lease(3600), "dev").is_err());
assert!(queue.decide(&id, Decision::Lease(3600), "dev", false).is_err());
assert_eq!(queue.list().len(), 1);
}
#[tokio::test]
async fn passkey_requests_need_a_passkey_to_approve() {
let queue = Queue::new(Duration::from_secs(60), 64);
let mut needs = request("a", "k");
needs.passkey = true;
let id = new_id();
let reply = queue.submit(&id, needs, 4).unwrap();
assert!(queue.decide(&id, Decision::Once, "dev", false).is_err());
assert!(queue.decide(&id, Decision::Lease(300), "dev", false).is_err());
assert!(queue.list()[0].passkey);
queue.decide(&id, Decision::Once, "dev", true).unwrap();
assert_eq!(reply.await.unwrap(), Outcome::Approved { decision: Decision::Once, approver: "dev".into() });
// Anyone may deny.
let mut needs = request("a", "k");
needs.passkey = true;
let id = new_id();
let reply = queue.submit(&id, needs, 4).unwrap();
queue.decide(&id, Decision::Deny, "dev", false).unwrap();
assert_eq!(reply.await.unwrap(), Outcome::Denied);
}
#[test]
fn limits_pending_requests() {
let queue = Queue::new(Duration::from_secs(60), 3);
+1
View File
@@ -351,6 +351,7 @@ async fn authorize(
detail: parsed.detail.clone(),
label,
sensitive: parsed.sensitive,
passkey: verdict.passkey,
leases: verdict.leases,
};
+135
View File
@@ -0,0 +1,135 @@
// Keeps the page current, counts down expiry times and manages this device's push subscription.
// The page works without it: answers are ordinary form submissions.
"use strict";
const csrf = () => document.querySelector('input[name="csrf"]')?.value;
// Expiry countdowns, from the seconds left when the page or fragment was rendered.
function startCountdowns(root) {
const started = Date.now();
for (const element of root.querySelectorAll(".expires")) {
element.dataset.until = String(started + Number(element.dataset.left) * 1000);
}
}
function formatLeft(seconds) {
if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
if (seconds >= 60) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
return `${seconds}s`;
}
setInterval(() => {
for (const element of document.querySelectorAll(".expires[data-until]")) {
const seconds = Math.max(0, Math.round((Number(element.dataset.until) - Date.now()) / 1000));
element.textContent = seconds > 0 ? `expires in ${formatLeft(seconds)}` : "expired";
}
}, 1000);
// Polls for changes to the pending set while the page is visible.
async function refresh() {
const pending = document.getElementById("pending");
const request = document.getElementById("request");
const container = pending || request;
if (!container || document.hidden) return;
const response = await fetch("/api/version", { credentials: "same-origin" });
if (response.status === 401) return location.reload();
if (!response.ok) return;
const { version } = await response.json();
if (String(version) === container.dataset.version) return;
if (request) return location.reload();
// Swap in the new list, keeping open details open.
const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id));
const fragment = await fetch("/pending", { credentials: "same-origin" });
if (!fragment.ok) return;
pending.innerHTML = await fragment.text();
pending.dataset.version = String(version);
for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", "");
startCountdowns(pending);
}
function base64urlToBytes(text) {
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
}
async function post(path, body) {
const response = await fetch(path, {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf() },
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
}
async function setUpPush() {
const section = document.getElementById("push");
if (!section || !("serviceWorker" in navigator) || !("PushManager" in window)) return;
const registration = await navigator.serviceWorker.register("/sw.js");
const state = document.getElementById("push-state");
const toggle = document.getElementById("push-toggle");
async function show() {
const subscription = await registration.pushManager.getSubscription();
if (Notification.permission === "denied") {
state.textContent = "Notifications are blocked for this site in the browser.";
toggle.hidden = true;
} else if (subscription) {
state.textContent = "This device gets notifications.";
toggle.textContent = "Turn off";
toggle.hidden = false;
} else {
state.textContent = "This device doesn't get notifications.";
toggle.textContent = "Turn on";
toggle.hidden = false;
}
section.hidden = false;
}
toggle.addEventListener("click", async () => {
toggle.disabled = true;
try {
const existing = await registration.pushManager.getSubscription();
if (existing) {
await post("/push/unsubscribe", { endpoint: existing.endpoint });
await existing.unsubscribe();
} else if ((await Notification.requestPermission()) === "granted") {
const key = await (await fetch("/push/key", { credentials: "same-origin" })).text();
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: base64urlToBytes(key),
});
await post("/push/subscribe", subscription.toJSON());
}
} catch (error) {
state.textContent = `That didn't work: ${error.message}`;
toggle.disabled = false;
return;
}
toggle.disabled = false;
await show();
});
await show();
}
// Audit times are UTC; show them in the browser's time zone.
function localTimes(root) {
for (const element of root.querySelectorAll("time[datetime]")) {
const date = new Date(element.getAttribute("datetime"));
if (isNaN(date)) continue;
element.textContent = date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "medium" });
element.title = element.getAttribute("datetime");
}
}
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
setUpPush().catch(() => {});
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#2f6f4f"/><path d="M18 33l9 9 19-20" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 238 B

+10
View File
@@ -0,0 +1,10 @@
{
"name": "slop approvals",
"short_name": "Approvals",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#f6f6f3",
"theme_color": "#2f6f4f",
"icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" }]
}
+312
View File
@@ -0,0 +1,312 @@
:root {
--bg: #f6f6f3;
--surface: #ffffff;
--text: #1d1d1b;
--muted: #66665f;
--border: #d9d9d2;
--accent: #2f6f4f;
--accent-text: #ffffff;
--deny: #a4362b;
--warn-bg: #fbe9d0;
--warn-text: #7a4300;
--code-bg: #f0f0ea;
--key: #4b4fb8;
--key-bg: #e6e7fa;
--good: #2f6f4f;
--good-bg: #dcefe3;
--bad: #a4362b;
--bad-bg: #f7dfdb;
--active: #1f5f99;
--active-bg: #dbe9f6;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161715;
--surface: #1f201e;
--text: #e8e8e3;
--muted: #a3a39b;
--border: #3a3b37;
--accent: #5fae83;
--accent-text: #0e1a13;
--deny: #e0766a;
--warn-bg: #4a3415;
--warn-text: #f3c98b;
--code-bg: #262724;
--key: #a9acf5;
--key-bg: #2c2d52;
--good: #8fd4ac;
--good-bg: #1f3a2a;
--bad: #f0a197;
--bad-bg: #4a2420;
--active: #9cc7f0;
--active-bg: #1d3247;
color-scheme: dark;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 16px/1.45 system-ui, sans-serif;
}
header {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
align-items: center;
justify-content: space-between;
padding: 10px 16px;
border-bottom: 1px solid var(--border);
background: var(--surface);
}
nav a {
margin-right: 16px;
}
main {
max-width: 960px;
margin: 0 auto;
padding: 16px;
}
a {
color: var(--accent);
}
h1 {
font-size: 1.4rem;
margin: 8px 0 16px;
}
h2 {
font-size: 1.1rem;
margin: 0 0 4px;
overflow-wrap: anywhere;
}
.account {
display: flex;
gap: 8px;
align-items: center;
color: var(--muted);
}
.request {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 14px;
margin-bottom: 14px;
}
.meta,
.note,
.empty {
color: var(--muted);
margin: 4px 0;
}
.label {
margin: 6px 0;
font-style: italic;
overflow-wrap: anywhere;
}
.badge {
display: inline-block;
padding: 0 6px;
border-radius: 4px;
font-size: 0.85rem;
background: var(--code-bg);
color: var(--text);
}
.badge.warn {
background: var(--warn-bg);
color: var(--warn-text);
}
details summary {
cursor: pointer;
color: var(--muted);
}
pre {
background: var(--code-bg);
padding: 10px;
border-radius: 6px;
overflow-x: auto;
font-size: 0.85rem;
line-height: 1.35;
max-height: 70vh;
}
pre.log {
max-height: none;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.answers {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
button {
font: inherit;
padding: 6px 14px;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
cursor: pointer;
}
button.approve {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-text);
}
button.deny {
border-color: var(--deny);
color: var(--deny);
}
button.quiet {
padding: 2px 10px;
}
table {
border-collapse: collapse;
width: 100%;
background: var(--surface);
}
th,
td {
text-align: left;
padding: 6px 8px;
border-bottom: 1px solid var(--border);
vertical-align: top;
overflow-wrap: anywhere;
}
code {
font-size: 0.85rem;
}
.filters {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: end;
}
.filters input {
font: inherit;
max-width: 100%;
}
#push {
margin-bottom: 12px;
color: var(--muted);
}
.request.needs-passkey {
border-left: 4px solid var(--key);
}
.badge.passkey {
background: var(--key-bg);
color: var(--key);
font-weight: 600;
}
.lock {
width: 0.85em;
height: 0.85em;
margin-right: 0.3em;
vertical-align: -0.05em;
fill: currentColor;
}
.outcome {
display: inline-block;
padding: 0 6px;
border-radius: 4px;
font-size: 0.85rem;
white-space: nowrap;
}
.outcome.good {
background: var(--good-bg);
color: var(--good);
}
.outcome.bad {
background: var(--bad-bg);
color: var(--bad);
}
.outcome.active {
background: var(--active-bg);
color: var(--active);
}
.outcome.neutral {
background: var(--code-bg);
color: var(--muted);
}
.scroll {
overflow-x: auto;
}
table.log td:first-child {
white-space: nowrap;
color: var(--muted);
font-size: 0.9rem;
}
table.log .label {
color: var(--muted);
font-size: 0.9rem;
}
.timeline {
list-style: none;
padding: 0;
margin: 0 0 16px;
border-left: 2px solid var(--border);
}
.timeline li {
padding: 4px 0 8px 14px;
overflow-wrap: anywhere;
}
.timeline time {
display: block;
color: var(--muted);
font-size: 0.85rem;
}
.filters select {
font: inherit;
}
.filters {
margin-bottom: 16px;
}
+66
View File
@@ -0,0 +1,66 @@
// Shows pushed requests as notifications and answers them from their buttons, with the same
// session the page uses. Anything that fails opens the request instead.
"use strict";
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
self.addEventListener("push", (event) => {
const data = event.data?.json();
if (!data) return;
const tag = `slop-${data.id}`;
if (data.kind === "clear") {
event.waitUntil(
self.registration.getNotifications({ tag }).then((all) => all.forEach((n) => n.close())),
);
return;
}
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
tag,
requireInteraction: true,
icon: "/icon.svg",
data: { id: data.id, url: data.url },
actions: data.actions,
}),
);
});
async function answer(id, decision) {
const token = await fetch("/api/csrf", { credentials: "same-origin" });
if (!token.ok) throw new Error("not signed in");
const { csrf } = await token.json();
const response = await fetch(`/requests/${encodeURIComponent(id)}`, {
method: "POST",
credentials: "same-origin",
headers: { "X-CSRF-Token": csrf },
body: new URLSearchParams({ decision }),
});
if (!response.ok) throw new Error(await response.text());
}
async function open(url) {
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
for (const client of windows) {
if (new URL(client.url).origin === self.location.origin && "focus" in client) {
await client.navigate(url).catch(() => {});
return client.focus();
}
}
return self.clients.openWindow(url);
}
self.addEventListener("notificationclick", (event) => {
const { id, url } = event.notification.data;
event.notification.close();
if (!event.action) {
event.waitUntil(open(url));
return;
}
event.waitUntil(answer(id, event.action).catch(() => open(url)));
});
+246
View File
@@ -0,0 +1,246 @@
//! Signing approvers in through an OpenID Connect provider, and confirming single answers by
//! sending the approver back to sign in again (`max_age=0`), which a passkey-only provider turns
//! into a passkey prompt.
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, ensure};
use openidconnect::core::{
CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow, CoreErrorResponseType, CoreGenderClaim, CoreJsonWebKey,
CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreRevocableToken,
CoreRevocationErrorResponse, CoreTokenIntrospectionResponse, CoreTokenType,
};
use openidconnect::{
AdditionalClaims, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EmptyExtraTokenFields, EndpointMaybeSet,
EndpointNotSet, EndpointSet, IdTokenFields, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl,
Scope, StandardErrorResponse, StandardTokenResponse, reqwest,
};
use serde::{Deserialize, Serialize};
use crate::config::WebConfig;
use crate::queue::Decision;
/// The `groups` claim, which providers such as Pocket ID add for the `groups` scope.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Groups {
#[serde(default)]
groups: Vec<String>,
}
impl AdditionalClaims for Groups {}
type TokenResponse = StandardTokenResponse<
IdTokenFields<
Groups,
EmptyExtraTokenFields,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
>,
CoreTokenType,
>;
type Client = openidconnect::Client<
Groups,
CoreAuthDisplay,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJsonWebKey,
CoreAuthPrompt,
StandardErrorResponse<CoreErrorResponseType>,
TokenResponse,
CoreTokenIntrospectionResponse,
CoreRevocableToken,
CoreRevocationErrorResponse,
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
>;
/// How long the provider's metadata and keys are used before fetching them again.
const METADATA_LIFETIME: Duration = Duration::from_secs(3600);
/// How long a sign-in may take.
pub const FLOW_LIFETIME: u64 = 600;
/// Why the approver was sent to the provider.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Purpose {
SignIn {
/// Local path to return to.
next: String,
},
/// Approving one request, which needs a passkey.
Confirm {
id: String,
decision: Decision,
/// [`super::fingerprint`] of what the approver was shown.
shown: String,
},
}
/// A sign-in in progress, kept in the session until the provider sends the approver back.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Flow {
pub state: String,
nonce: String,
verifier: String,
/// Unix time it started; a confirmation needs a sign-in no older than this.
pub started: i64,
pub purpose: Purpose,
}
/// Who signed in, from a verified ID token.
#[derive(Debug, Clone)]
pub struct Identity {
pub subject: String,
pub name: String,
/// Unix time the approver last authenticated with the provider.
pub auth_time: Option<i64>,
}
pub struct Oidc {
config: WebConfig,
secret: String,
http: reqwest::Client,
client: tokio::sync::Mutex<Option<(Instant, Client)>>,
}
pub fn now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
}
impl Oidc {
pub fn new(config: WebConfig, secret: String) -> Result<Oidc> {
// Following redirects would let the provider's metadata send requests anywhere.
let http = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(10))
.build()?;
Ok(Oidc { config, secret, http, client: tokio::sync::Mutex::new(None) })
}
/// The client, discovering the provider when it isn't known yet or is due for a refresh. A
/// failed refresh keeps using what was fetched before.
async fn client(&self) -> Result<Client> {
let mut cached = self.client.lock().await;
if let Some((fetched, client)) = &*cached
&& fetched.elapsed() < METADATA_LIFETIME
{
return Ok(client.clone());
}
match self.discover().await {
Ok(client) => {
*cached = Some((Instant::now(), client.clone()));
Ok(client)
}
Err(error) => match &*cached {
Some((_, client)) => Ok(client.clone()),
None => Err(error.context("reaching the sign-in provider")),
},
}
}
async fn discover(&self) -> Result<Client> {
let issuer = IssuerUrl::new(self.config.issuer.clone())?;
let metadata = CoreProviderMetadata::discover_async(issuer, &self.http).await?;
let redirect = RedirectUrl::new(format!("{}/auth/callback", self.config.url.trim_end_matches('/')))?;
Ok(Client::from_provider_metadata(
metadata,
ClientId::new(self.config.client_id.clone()),
Some(ClientSecret::new(self.secret.clone())),
)
.set_redirect_uri(redirect))
}
/// Where to send the approver, and what to remember until they're back.
pub async fn begin(&self, purpose: Purpose) -> Result<(String, Flow)> {
let client = self.client().await?;
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
let mut request = client
.authorize_url(CoreAuthenticationFlow::AuthorizationCode, CsrfToken::new_random, Nonce::new_random)
.add_scope(Scope::new("profile".into()))
.add_scope(Scope::new("groups".into()))
.set_pkce_challenge(challenge);
if matches!(purpose, Purpose::Confirm { .. }) {
request = request.set_max_age(Duration::ZERO);
}
let (url, state, nonce) = request.url();
let flow = Flow {
state: state.secret().clone(),
nonce: nonce.secret().clone(),
verifier: verifier.secret().clone(),
started: now(),
purpose,
};
Ok((url.to_string(), flow))
}
/// Exchanges the code the provider sent back, and checks the ID token and group.
pub async fn finish(&self, flow: &Flow, code: String) -> Result<Identity> {
let client = self.client().await?;
let response = client
.exchange_code(AuthorizationCode::new(code))?
.set_pkce_verifier(PkceCodeVerifier::new(flow.verifier.clone()))
.request_async(&self.http)
.await
.map_err(|e| anyhow!("exchanging the sign-in code: {e}"))?;
let token = openidconnect::TokenResponse::id_token(&response).context("the provider sent no ID token")?;
let claims = token.claims(&client.id_token_verifier(), &Nonce::new(flow.nonce.clone()))?;
ensure!(
claims.additional_claims().groups.contains(&self.config.group),
"this account isn't in the {} group",
self.config.group
);
let subject = claims.subject().as_str().to_owned();
let name = claims.preferred_username().map_or_else(|| subject.clone(), |n| n.as_str().to_owned());
Ok(Identity { subject, name, auth_time: claims.auth_time().map(|t| t.timestamp()) })
}
}
/// Checks that a confirmation came from the signed-in approver, who authenticated after it
/// started.
pub fn confirmed(flow: &Flow, identity: &Identity, subject: &str) -> Result<()> {
ensure!(identity.subject == subject, "the passkey belongs to a different account");
ensure!(
identity.auth_time.is_some_and(|t| t >= flow.started),
"the sign-in provider didn't ask for the passkey again"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn flow(started: i64) -> Flow {
Flow {
state: "s".into(),
nonce: "n".into(),
verifier: "v".into(),
started,
purpose: Purpose::Confirm { id: "r".into(), decision: Decision::Once, shown: "h".into() },
}
}
fn identity(subject: &str, auth_time: Option<i64>) -> Identity {
Identity { subject: subject.into(), name: "dev".into(), auth_time }
}
#[test]
fn confirmation_needs_a_fresh_sign_in_by_the_same_account() {
assert!(confirmed(&flow(100), &identity("a", Some(100)), "a").is_ok());
assert!(confirmed(&flow(100), &identity("a", Some(130)), "a").is_ok());
assert!(confirmed(&flow(100), &identity("a", Some(99)), "a").is_err());
assert!(confirmed(&flow(100), &identity("a", None), "a").is_err());
assert!(confirmed(&flow(100), &identity("b", Some(130)), "a").is_err());
}
}
+281
View File
@@ -0,0 +1,281 @@
//! The audit log gathered by request: what was asked, who approved it and how it ended.
use std::collections::HashMap;
use crate::audit::{Event, Record};
use crate::proto::ApprovedBy;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
/// Waiting for an approver, or for its preparation.
Waiting,
/// Approved and not finished yet.
Running,
Succeeded,
/// Ran, and exited with a non-zero status.
ExitedWith(i32),
Failed,
Denied,
Expired,
Cancelled,
Invalid,
}
impl Outcome {
pub fn name(&self) -> String {
match self {
Outcome::Waiting => "Waiting".into(),
Outcome::Running => "Running".into(),
Outcome::Succeeded => "Succeeded".into(),
Outcome::ExitedWith(status) => format!("Exit status {status}"),
Outcome::Failed => "Failed".into(),
Outcome::Denied => "Denied".into(),
Outcome::Expired => "Expired".into(),
Outcome::Cancelled => "Cancelled".into(),
Outcome::Invalid => "Invalid".into(),
}
}
/// For styling: good, bad, or still going.
pub fn tone(&self) -> &'static str {
match self {
Outcome::Waiting | Outcome::Running => "active",
Outcome::Succeeded => "good",
Outcome::Expired | Outcome::Cancelled => "neutral",
_ => "bad",
}
}
/// The filter value for this outcome.
pub fn key(&self) -> &'static str {
match self {
Outcome::Waiting | Outcome::Running => "active",
Outcome::Succeeded => "succeeded",
Outcome::ExitedWith(_) | Outcome::Failed | Outcome::Invalid => "failed",
Outcome::Denied => "denied",
Outcome::Expired | Outcome::Cancelled => "expired",
}
}
}
/// Everything the log says about one request.
#[derive(Debug, Clone)]
pub struct History {
pub id: String,
pub time: String,
pub requester: String,
pub op: String,
pub summary: String,
pub label: Option<String>,
pub outcome: Outcome,
/// Who approved it (the request itself, not a step before it), with the answer they gave.
pub approved_by: Option<String>,
pub records: Vec<Record>,
}
fn id_of(event: &Event) -> Option<&str> {
match event {
Event::Unknown { .. } => None,
Event::Invalid { id, .. }
| Event::Request { id, .. }
| Event::Prepared { id, .. }
| Event::Approved { id, .. }
| Event::Decision { id, .. }
| Event::Denied { id, .. }
| Event::Expired { id }
| Event::Disconnected { id }
| Event::Finished { id, .. }
| Event::Failed { id, .. } => Some(id),
}
}
/// Groups records (oldest first) by request, newest request first. Connections from unknown
/// peers have no request and are returned separately.
pub fn gather(records: Vec<Record>) -> (Vec<History>, Vec<Record>) {
let mut order: Vec<String> = vec![];
let mut by_id: HashMap<String, Vec<Record>> = HashMap::new();
let mut unknown = vec![];
for record in records {
match id_of(&record.event) {
Some(id) => {
if !by_id.contains_key(id) {
order.push(id.to_owned());
}
by_id.entry(id.to_owned()).or_default().push(record);
}
None => unknown.push(record),
}
}
let histories = order.into_iter().rev().map(|id| summarize(id.clone(), by_id.remove(&id).unwrap())).collect();
unknown.reverse();
(histories, unknown)
}
fn summarize(id: String, records: Vec<Record>) -> History {
let mut history = History {
id,
time: records[0].time.clone(),
requester: String::new(),
op: String::new(),
summary: String::new(),
label: None,
outcome: Outcome::Waiting,
approved_by: None,
records: vec![],
};
let mut answer = None;
for record in &records {
match &record.event {
Event::Request { requester, op, summary, label, .. } => {
history.requester = requester.clone();
history.op = op.clone();
history.summary = summary.clone();
history.label = label.clone();
}
Event::Invalid { requester, error, .. } => {
history.requester = requester.clone();
history.summary = error.clone();
history.outcome = Outcome::Invalid;
}
Event::Decision { decision, approver, .. } => answer = Some((decision.clone(), approver.clone())),
Event::Approved { by, approver, step: None, .. } => {
history.outcome = Outcome::Running;
history.approved_by = Some(match (by, approver, &answer) {
(ApprovedBy::Policy, _, _) => "policy".into(),
(ApprovedBy::Lease, _, _) => "a lease".into(),
(ApprovedBy::Approver, Some(approver), Some((decision, _))) => format!("{approver} ({decision})"),
(ApprovedBy::Approver, Some(approver), None) => approver.clone(),
(ApprovedBy::Approver, None, _) => "an approver".into(),
});
}
Event::Denied { .. } => history.outcome = Outcome::Denied,
Event::Expired { .. } => history.outcome = Outcome::Expired,
Event::Disconnected { .. } => history.outcome = Outcome::Cancelled,
Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded,
Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit),
Event::Failed { .. } => history.outcome = Outcome::Failed,
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } => {}
}
}
history.records = records;
history
}
/// One event in a request's timeline: what happened, and any longer text to show with it.
pub fn describe(event: &Event) -> (String, Option<String>) {
match event {
Event::Unknown { peer } => (format!("Refused a connection from {peer}"), None),
Event::Invalid { error, .. } => (format!("Invalid request: {error}"), None),
Event::Request { summary, detail, label, .. } => {
let mut text = format!("Asked: {summary}");
if let Some(label) = label {
text += &format!(" (label: {label})");
}
(text, Some(detail.clone()).filter(|d| !d.is_empty()))
}
Event::Prepared { detail, .. } => {
("Prepared for approval".into(), Some(detail.clone()).filter(|d| !d.is_empty()))
}
Event::Approved { by, approver, step, .. } => {
let by = match (by, approver) {
(ApprovedBy::Policy, _) => "policy".to_owned(),
(ApprovedBy::Lease, _) => "a lease".to_owned(),
(ApprovedBy::Approver, Some(approver)) => approver.clone(),
(ApprovedBy::Approver, None) => "an approver".to_owned(),
};
match step {
Some(step) => (format!("Use of the {step} approved by {by}"), None),
None => (format!("Approved by {by}"), None),
}
}
Event::Decision { decision, approver, .. } => (format!("{approver} answered {decision}"), None),
Event::Denied { reason, .. } => (format!("Refused: {reason}"), None),
Event::Expired { .. } => ("Expired without an answer".into(), None),
Event::Disconnected { .. } => ("Cancelled: the requester disconnected".into(), None),
Event::Finished { exit, seconds, .. } => {
(format!("Finished with exit status {exit} after {seconds:.1}s"), None)
}
Event::Failed { error, .. } => (format!("Failed: {error}"), None),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn record(time: &str, event: Event) -> Record {
Record { time: time.into(), event }
}
fn request(id: &str) -> Event {
Event::Request {
id: id.into(),
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: format!("ssh {id}"),
detail: "Command: uptime".into(),
label: None,
}
}
#[test]
fn gathers_requests_and_their_outcomes() {
let records = vec![
record("1", request("a")),
record("2", request("b")),
record("3", Event::Unknown { peer: "vsock CID 9".into() }),
record(
"4",
Event::Decision {
id: "a".into(),
requester: "slop-cannon".into(),
summary: "ssh a".into(),
decision: "5m".into(),
approver: "dev (web)".into(),
},
),
record(
"5",
Event::Approved {
id: "a".into(),
by: ApprovedBy::Approver,
approver: Some("dev (web)".into()),
step: None,
},
),
record("6", Event::Finished { id: "a".into(), exit: 1, seconds: 0.5 }),
record("7", Event::Expired { id: "b".into() }),
record("8", request("c")),
record("9", Event::Approved { id: "c".into(), by: ApprovedBy::Lease, approver: None, step: None }),
];
let (histories, unknown) = gather(records);
assert_eq!(unknown.len(), 1);
let ids: Vec<_> = histories.iter().map(|h| h.id.as_str()).collect();
assert_eq!(ids, ["c", "b", "a"]);
assert_eq!(histories[0].outcome, Outcome::Running);
assert_eq!(histories[0].approved_by.as_deref(), Some("a lease"));
assert_eq!(histories[1].outcome, Outcome::Expired);
assert_eq!(histories[2].outcome, Outcome::ExitedWith(1));
assert_eq!(histories[2].approved_by.as_deref(), Some("dev (web) (5m)"));
assert_eq!(histories[2].records.len(), 4);
}
#[test]
fn steps_before_the_request_dont_count_as_approving_it() {
let records = vec![
record("1", request("a")),
record(
"2",
Event::Approved { id: "a".into(), by: ApprovedBy::Lease, approver: None, step: Some("builder".into()) },
),
];
let (histories, _) = gather(records);
assert_eq!(histories[0].outcome, Outcome::Waiting);
assert_eq!(histories[0].approved_by, None);
}
}
+521
View File
@@ -0,0 +1,521 @@
//! The approvals web app: pending requests with full detail, answers, leases and the audit log,
//! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It
//! sits behind a reverse proxy, which is the only thing that should reach its listener.
mod auth;
mod history;
mod page;
mod push;
use std::sync::Arc;
use anyhow::{Context, Result};
use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tower_sessions::cookie::SameSite;
use tower_sessions::cookie::time::Duration;
use tower_sessions::{ExpiredDeletion, Expiry, Session, SessionManagerLayer};
use tower_sessions_rusqlite_store::{RusqliteStore, tokio_rusqlite};
use crate::approve;
use crate::config::WebConfig;
use crate::queue::{Decision, PendingInfo};
use crate::server::Broker;
use auth::{Flow, Oidc, Purpose};
use history::History;
use push::{Push, Subscription};
struct Web {
broker: Arc<Broker>,
/// The app's origin, which every POST must come from.
origin: String,
oidc: Oidc,
push: Arc<Push>,
}
/// The signed-in approver, kept in the session.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
subject: String,
name: String,
/// Sent back with every POST.
csrf: String,
}
const USER: &str = "user";
const FLOWS: &str = "flows";
/// Sign-ins in progress per session, for several tabs or notifications at once.
const MAX_FLOWS: usize = 8;
fn origin(url: &str) -> Result<String> {
let url = url::Url::parse(url)?;
anyhow::ensure!(url.path() == "/" && url.query().is_none(), "the web app's URL must not have a path");
Ok(url.origin().ascii_serialization())
}
pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Result<()> {
let origin = origin(&config.url)?;
let issuer = url::Url::parse(&config.issuer)?.origin().ascii_serialization();
// Sessions outlive the broker restarting, so signing in on a phone lasts.
let database = tokio_rusqlite::Connection::open(config.state_dir.join("sessions.sqlite")).await?;
let store = RusqliteStore::new(database);
store.migrate().await.context("setting up the sessions database")?;
tokio::spawn(store.clone().continuously_delete_expired(std::time::Duration::from_secs(3600)));
let push = Arc::new(Push::open(&config.state_dir, &config.url)?);
let listener = tokio::net::TcpListener::bind(config.listen).await.context("binding the web listener")?;
let sessions = SessionManagerLayer::new(store)
.with_name("slop_session")
.with_secure(config.url.starts_with("https:"))
.with_same_site(SameSite::Lax)
.with_http_only(true)
.with_expiry(Expiry::OnInactivity(Duration::seconds(config.session as i64)));
let web = Arc::new(Web { oidc: Oidc::new(config.clone(), secret)?, broker: broker.clone(), origin, push });
tokio::spawn(web.push.clone().run(broker));
let app = Router::new()
.route("/", get(index))
.route("/pending", get(pending_fragment))
.route("/requests/{id}", get(request_page).post(answer))
.route("/log", get(log_page))
.route("/api/version", get(version))
.route("/api/csrf", get(csrf))
.route("/push/key", get(push_key))
.route("/push/subscribe", post(subscribe))
.route("/push/unsubscribe", post(unsubscribe))
.route("/auth/login", get(login))
.route("/auth/callback", get(callback))
.route("/auth/logout", post(logout))
.route("/signed-out", get(signed_out))
.route("/app.js", get(|| async { page::asset("text/javascript", include_str!("assets/app.js")) }))
.route("/sw.js", get(|| async { page::asset("text/javascript", include_str!("assets/sw.js")) }))
.route("/style.css", get(|| async { page::asset("text/css", include_str!("assets/style.css")) }))
.route("/icon.svg", get(|| async { page::asset("image/svg+xml", include_str!("assets/icon.svg")) }))
.route(
"/manifest.webmanifest",
get(|| async { page::asset("application/manifest+json", include_str!("assets/manifest.webmanifest")) }),
)
.layer(axum::middleware::map_response(move |response| security_headers(response, issuer.clone())))
.layer(sessions)
.with_state(web);
axum::serve(listener, app).await.context("serving the web app")
}
async fn security_headers(mut response: Response, issuer: String) -> Response {
let headers = response.headers_mut();
// Answers that need a passkey redirect a form submission to the sign-in provider.
let policy = format!(
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; \
manifest-src 'self'; worker-src 'self'; form-action 'self' {issuer}; frame-ancestors 'none'; base-uri 'none'"
);
headers.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_str(&policy).unwrap());
headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("same-origin"));
headers.entry(header::CACHE_CONTROL).or_insert(HeaderValue::from_static("no-store"));
response
}
/// Something that went wrong, shown as a page.
struct Failure(StatusCode, String);
impl IntoResponse for Failure {
fn into_response(self) -> Response {
(self.0, page::message("Something went wrong", &self.1)).into_response()
}
}
impl From<anyhow::Error> for Failure {
fn from(error: anyhow::Error) -> Failure {
Failure(StatusCode::INTERNAL_SERVER_ERROR, format!("{error:#}"))
}
}
impl From<tower_sessions::session::Error> for Failure {
fn from(error: tower_sessions::session::Error) -> Failure {
Failure(StatusCode::INTERNAL_SERVER_ERROR, format!("session: {error}"))
}
}
fn failure(status: StatusCode, message: &str) -> Failure {
Failure(status, message.to_owned())
}
async fn user(session: &Session) -> Result<Option<User>, Failure> {
Ok(session.get::<User>(USER).await?)
}
/// The signed-in approver, or a redirect to sign in and come back to `here`.
async fn signed_in(session: &Session, here: &str) -> Result<Result<User, Response>, Failure> {
Ok(match user(session).await? {
Some(user) => Ok(user),
None => Err(Redirect::to(&format!("/auth/login?next={}", urlencode(here))).into_response()),
})
}
/// The signed-in approver, for API calls, which can't follow a sign-in.
async fn api_user(session: &Session) -> Result<User, Failure> {
user(session).await?.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "sign in first"))
}
/// Checks a POST came from the app itself: the browser's `Origin` and the session's token.
fn check_post(web: &Web, headers: &HeaderMap, user: &User, token: Option<&str>) -> Result<(), Failure> {
let origin = headers.get(header::ORIGIN).and_then(|o| o.to_str().ok());
let token = token.or_else(|| headers.get("x-csrf-token").and_then(|t| t.to_str().ok()));
if origin != Some(web.origin.as_str()) || token != Some(user.csrf.as_str()) {
return Err(failure(StatusCode::FORBIDDEN, "this form is out of date; reload the page and try again"));
}
Ok(())
}
fn urlencode(text: &str) -> String {
url::form_urlencoded::byte_serialize(text.as_bytes()).collect()
}
/// 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] {
hash.update(part.as_bytes());
hash.update([0]);
}
hex::encode(hash.finalize())
}
fn approver(user: &User, passkey: bool) -> String {
if passkey { format!("{} (web, passkey)", user.name) } else { format!("{} (web)", user.name) }
}
fn pending(web: &Web, id: &str) -> Option<PendingInfo> {
web.broker.queue.list().into_iter().find(|e| e.id == id)
}
async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
let user = match signed_in(&session, "/").await? {
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::index(&user.name, &user.csrf, &entries, &leases, web.broker.queue.version()).into_response())
}
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::pending(&user.csrf, &entries, &leases).into_response())
}
async fn request_page(
State(web): State<Arc<Web>>,
session: Session,
Path(id): Path<String>,
) -> Result<Response, Failure> {
let user = match signed_in(&session, &format!("/requests/{id}")).await? {
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
// The log may be missing or unreadable; the request itself still shows.
let past = web.broker.audit.tail(LOG_RECORDS).ok().and_then(|records| {
let (histories, _) = history::gather(records);
histories.into_iter().find(|h| h.id == id)
});
let current = pending(&web, &id);
Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version())
.into_response())
}
#[derive(Deserialize)]
struct AnswerForm {
decision: String,
csrf: Option<String>,
}
/// Records an answer from a form or the service worker. Approving a request that needs a passkey
/// sends the approver to sign in again first.
async fn answer(
State(web): State<Arc<Web>>,
session: Session,
headers: HeaderMap,
Path(id): Path<String>,
axum::Form(form): axum::Form<AnswerForm>,
) -> Result<Response, Failure> {
let user = api_user(&session).await?;
check_post(&web, &headers, &user, form.csrf.as_deref())?;
// Scripts send the token as a header and want a status rather than a page.
let script = headers.contains_key("x-csrf-token");
let decision = Decision::parse(&form.decision).map_err(|e| failure(StatusCode::BAD_REQUEST, &e.to_string()))?;
let entry = pending(&web, &id).ok_or_else(|| failure(StatusCode::GONE, "this request is no longer pending"))?;
if !entry.offers.contains(&decision) {
return Err(failure(StatusCode::BAD_REQUEST, "that answer isn't offered for this request"));
}
if entry.passkey && decision != Decision::Deny {
if script {
return Err(failure(StatusCode::FORBIDDEN, "this request needs a passkey; open it to approve"));
}
let purpose = Purpose::Confirm { id: id.clone(), decision, shown: fingerprint(&entry) };
return start(&web, &session, purpose).await;
}
approve::approve(&web.broker, &id, decision, &approver(&user, false), false)
.map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?;
Ok(if script { StatusCode::NO_CONTENT.into_response() } else { Redirect::to("/").into_response() })
}
/// Audit records the log page and request pages read.
const LOG_RECORDS: usize = 5000;
/// Requests the log page lists at most.
const LOG_ROWS: usize = 300;
async fn log_page(
State(web): State<Arc<Web>>,
session: Session,
Query(filters): Query<page::Filters>,
) -> Result<Response, Failure> {
let user = match signed_in(&session, "/log").await? {
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
let (histories, refused) = history::gather(web.broker.audit.tail(LOG_RECORDS)?);
let mut requesters: Vec<String> = web.broker.config.requesters.keys().cloned().collect();
let mut ops: Vec<String> = histories.iter().map(|h| h.op.clone()).filter(|o| !o.is_empty()).collect();
requesters.extend(histories.iter().map(|h| h.requester.clone()).filter(|r| !r.is_empty()));
for list in [&mut requesters, &mut ops] {
list.sort();
list.dedup();
}
let matching: Vec<History> = histories.into_iter().filter(|h| filters.matches(h)).collect();
let view = page::LogView {
filters: &filters,
histories: &matching[..matching.len().min(LOG_ROWS)],
matched: matching.len(),
requesters: &requesters,
ops: &ops,
refused: &refused,
};
Ok(page::log(&user.name, &user.csrf, &view).into_response())
}
async fn version(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response())
}
async fn csrf(session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response())
}
async fn push_key(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(web.push.public_key().to_owned().into_response())
}
/// A browser's `PushSubscription`, as `toJSON()` gives it.
#[derive(Deserialize)]
struct BrowserSubscription {
endpoint: String,
keys: SubscriptionKeys,
}
#[derive(Deserialize)]
struct SubscriptionKeys {
p256dh: String,
auth: String,
}
async fn subscribe(
State(web): State<Arc<Web>>,
session: Session,
headers: HeaderMap,
axum::Json(subscription): axum::Json<BrowserSubscription>,
) -> Result<Response, Failure> {
let user = api_user(&session).await?;
check_post(&web, &headers, &user, None)?;
let subscription = Subscription {
endpoint: subscription.endpoint,
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth,
subject: user.subject,
};
let service = url::Url::parse(&subscription.endpoint).ok().and_then(|u| u.host_str().map(str::to_owned));
let service = service.unwrap_or_default();
if let Err(error) = web.push.subscribe(subscription) {
eprintln!("<4>refused a push subscription from {} at {service}: {error:#}", user.name);
return Err(Failure(StatusCode::BAD_REQUEST, format!("{error:#}")));
}
eprintln!("<6>{} subscribed a device to notifications through {service}", user.name);
Ok(StatusCode::NO_CONTENT.into_response())
}
#[derive(Deserialize)]
struct Unsubscription {
endpoint: String,
}
async fn unsubscribe(
State(web): State<Arc<Web>>,
session: Session,
headers: HeaderMap,
axum::Json(request): axum::Json<Unsubscription>,
) -> Result<Response, Failure> {
let user = api_user(&session).await?;
check_post(&web, &headers, &user, None)?;
web.push.unsubscribe(&request.endpoint, &user.subject)?;
Ok(StatusCode::NO_CONTENT.into_response())
}
/// Sends the approver to the sign-in provider, remembering why.
async fn start(web: &Web, session: &Session, purpose: Purpose) -> Result<Response, Failure> {
let (url, flow) = web.oidc.begin(purpose).await?;
let mut flows = session.get::<Vec<Flow>>(FLOWS).await?.unwrap_or_default();
flows.retain(|f| auth::now() - f.started < auth::FLOW_LIFETIME as i64);
if flows.len() >= MAX_FLOWS {
flows.remove(0);
}
flows.push(flow);
session.insert(FLOWS, flows).await?;
Ok(Redirect::to(&url).into_response())
}
#[derive(Deserialize)]
struct LoginQuery {
next: Option<String>,
}
async fn login(
State(web): State<Arc<Web>>,
session: Session,
Query(query): Query<LoginQuery>,
) -> Result<Response, Failure> {
// Only paths on this site, never `//elsewhere`.
let next = query.next.filter(|n| n.starts_with('/') && !n.starts_with("//")).unwrap_or_else(|| "/".into());
start(&web, &session, Purpose::SignIn { next }).await
}
#[derive(Deserialize)]
struct CallbackQuery {
state: Option<String>,
code: Option<String>,
error: Option<String>,
error_description: Option<String>,
}
async fn callback(
State(web): State<Arc<Web>>,
session: Session,
Query(query): Query<CallbackQuery>,
) -> Result<Response, Failure> {
let mut flows = session.get::<Vec<Flow>>(FLOWS).await?.unwrap_or_default();
let position = flows
.iter()
.position(|f| Some(&f.state) == query.state.as_ref() && auth::now() - f.started < auth::FLOW_LIFETIME as i64)
.ok_or_else(|| failure(StatusCode::BAD_REQUEST, "this sign-in has expired; please try again"))?;
let flow = flows.remove(position);
session.insert(FLOWS, flows).await?;
if let Some(error) = query.error {
let description = query.error_description.unwrap_or_default();
return Err(Failure(StatusCode::FORBIDDEN, format!("the sign-in provider refused: {error} {description}")));
}
let code = query.code.ok_or_else(|| failure(StatusCode::BAD_REQUEST, "the sign-in provider sent no code"))?;
let identity = web.oidc.finish(&flow, code).await.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
match flow.purpose {
Purpose::SignIn { next } => {
// A new session ID, so one planted before signing in is useless.
session.cycle_id().await?;
let csrf = hex::encode(rand::random::<[u8; 32]>());
session.insert(USER, User { subject: identity.subject, name: identity.name, csrf }).await?;
Ok(Redirect::to(&next).into_response())
}
Purpose::Confirm { ref id, decision, ref shown } => {
let user = api_user(&session).await?;
auth::confirmed(&flow, &identity, &user.subject)
.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
let entry =
pending(&web, id).ok_or_else(|| failure(StatusCode::GONE, "this request is no longer pending"))?;
if fingerprint(&entry) != *shown {
return Err(failure(StatusCode::CONFLICT, "this request changed since you answered it; look again"));
}
approve::approve(&web.broker, id, decision, &approver(&user, true), true)
.map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?;
Ok(Redirect::to("/").into_response())
}
}
}
#[derive(Deserialize)]
struct LogoutForm {
csrf: Option<String>,
}
async fn logout(
State(web): State<Arc<Web>>,
session: Session,
headers: HeaderMap,
axum::Form(form): axum::Form<LogoutForm>,
) -> Result<Response, Failure> {
if let Some(user) = user(&session).await? {
check_post(&web, &headers, &user, form.csrf.as_deref())?;
}
session.flush().await?;
Ok(Redirect::to("/signed-out").into_response())
}
async fn signed_out() -> Response {
page::message("Signed out", "You're signed out of the approvals app.").into_response()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn origins() {
assert_eq!(origin("https://approve.example.org").unwrap(), "https://approve.example.org");
assert_eq!(origin("http://localhost:8095/").unwrap(), "http://localhost:8095");
assert!(origin("https://approve.example.org/app").is_err());
}
#[test]
fn fingerprints_cover_what_approvers_see() {
let entry = PendingInfo {
id: "a".into(),
requester: "slop-cannon".into(),
op: "deploy".into(),
summary: "deploy river".into(),
detail: "x".into(),
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() };
assert_ne!(fingerprint(&entry), fingerprint(&changed));
assert_ne!(fingerprint(&entry), fingerprint(&shifted));
assert_eq!(fingerprint(&entry), fingerprint(&PendingInfo { expires_in: 3, ..entry.clone() }));
}
}
+242
View File
@@ -0,0 +1,242 @@
//! The web app's pages, from the templates in `templates/`. Everything they show is escaped, and
//! passed through [`printable`] first (see `askama.toml`).
use std::fmt;
use askama::Template;
use askama::filters::Escaper;
use axum::http::header;
use axum::response::{Html, IntoResponse, Response};
use super::history::{self, History};
use crate::audit::{Record, short};
use crate::ops::printable;
use crate::queue::{Decision, PendingInfo};
/// HTML escaping, after replacing what [`printable`] replaces.
#[derive(Debug, Clone, Copy)]
pub struct Printable;
impl Escaper for Printable {
fn write_escaped_str<W: fmt::Write>(&self, dest: W, string: &str) -> fmt::Result {
askama::filters::Html.write_escaped_str(dest, &printable(string))
}
}
pub fn asset(content_type: &'static str, body: &'static str) -> Response {
([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, "no-cache")], body).into_response()
}
fn render(template: impl Template) -> Html<String> {
// Only a failing `Display` makes rendering fail, and nothing the pages show has one.
Html(template.render().unwrap_or_else(|error| format!("rendering the page failed: {error}")))
}
/// Time left, like `4m 10s`.
fn left(seconds: &u64) -> String {
match *seconds {
s if s >= 3600 => format!("{}h {}m", s / 3600, s % 3600 / 60),
s if s >= 60 => format!("{}m {}s", s / 60, s % 60),
s => format!("{s}s"),
}
}
fn is_deny(decision: &Decision) -> bool {
*decision == Decision::Deny
}
/// An answer's button.
fn answer(decision: &Decision) -> String {
match decision {
Decision::Lease(_) => format!("For {}", decision.title()),
_ => decision.title(),
}
}
fn describe(record: &Record) -> (String, Option<String>) {
history::describe(&record.event)
}
#[derive(Template)]
#[template(path = "message.html")]
struct Message<'a> {
title: &'a str,
text: &'a str,
}
pub fn message(title: &str, text: &str) -> Html<String> {
render(Message { title, text })
}
/// The pending requests and leases, which the page script swaps in when they change.
#[derive(Template)]
#[template(path = "pending.html")]
struct Pending<'a> {
csrf: &'a str,
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
}
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Pending { csrf, entries, leases })
}
#[derive(Template)]
#[template(path = "index.html")]
struct Index<'a> {
name: &'a str,
csrf: &'a str,
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
version: u64,
}
pub fn index(
name: &str,
csrf: &str,
entries: &[PendingInfo],
leases: &[(String, String, u64)],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, version })
}
#[derive(Template)]
#[template(path = "request.html")]
struct Request<'a> {
name: &'a str,
csrf: &'a str,
heading: String,
entry: Option<&'a PendingInfo>,
past: Option<&'a History>,
version: u64,
}
pub fn request(
name: &str,
csrf: &str,
id: &str,
entry: Option<&PendingInfo>,
past: Option<&History>,
version: u64,
) -> Html<String> {
let heading = match (entry, past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(id)),
};
render(Request { name, csrf, heading, entry, past, version })
}
/// What the log page is filtered by.
#[derive(Debug, Default, serde::Deserialize)]
pub struct Filters {
#[serde(default)]
pub requester: String,
#[serde(default)]
pub op: String,
#[serde(default)]
pub outcome: String,
#[serde(default)]
pub text: String,
}
impl Filters {
pub fn matches(&self, history: &History) -> bool {
let text = self.text.trim().to_lowercase();
(self.requester.is_empty() || history.requester == self.requester)
&& (self.op.is_empty() || history.op == self.op)
&& (self.outcome.is_empty() || history.outcome.key() == self.outcome)
&& (text.is_empty()
|| history.id.starts_with(&text)
|| history.summary.to_lowercase().contains(&text)
|| history.label.as_deref().is_some_and(|l| l.to_lowercase().contains(&text)))
}
}
pub struct LogView<'a> {
pub filters: &'a Filters,
pub histories: &'a [History],
/// How many matched before cutting the list short.
pub matched: usize,
pub requesters: &'a [String],
pub ops: &'a [String],
pub refused: &'a [Record],
}
#[derive(Template)]
#[template(path = "log.html")]
struct Log<'a> {
name: &'a str,
csrf: &'a str,
filters: &'a Filters,
histories: &'a [History],
matched: usize,
requesters: Vec<(String, String)>,
ops: Vec<(String, String)>,
outcomes: Vec<(String, String)>,
refused: &'a [Record],
}
pub fn log(name: &str, csrf: &str, view: &LogView) -> Html<String> {
let pairs = |items: &[String]| items.iter().map(|i| (i.clone(), i.clone())).collect();
let outcomes = [
("active", "Waiting or running"),
("succeeded", "Succeeded"),
("failed", "Failed"),
("denied", "Denied"),
("expired", "Expired or cancelled"),
];
render(Log {
name,
csrf,
filters: view.filters,
histories: view.histories,
matched: view.matched,
requesters: pairs(view.requesters),
ops: pairs(view.ops),
outcomes: outcomes.iter().map(|(v, t)| (v.to_string(), t.to_string())).collect(),
refused: view.refused,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_markup_and_disguises() {
let escape = |text: &str| {
let mut escaped = String::new();
Printable.write_escaped_str(&mut escaped, text).unwrap();
escaped
};
assert_eq!(escape("<a href=\"x\">'&'</a>"), "&#60;a href=&#34;x&#34;&#62;&#39;&#38;&#39;&#60;/a&#62;");
assert_eq!(escape("ok\u{202e}evil"), "ok\u{fffd}evil");
}
#[test]
fn cards_offer_each_answer() {
let entry = PendingInfo {
id: "abc".into(),
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: "ssh river <x>".into(),
detail: "one\ntwo".into(),
label: Some("<script>".into()),
sensitive: true,
passkey: true,
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
expires_in: 125,
};
let html = pending("token", &[entry], &[]).0;
assert!(html.contains(r#"value="5m""#));
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("expires in 2m 5s"));
assert!(html.contains("needs-passkey"));
assert!(html.contains("Needs passkey"));
}
}
+313
View File
@@ -0,0 +1,313 @@
//! Web Push notifications for pending requests. Payloads are encrypted to each browser, so the
//! push service only sees when they're sent and how big they are.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use openidconnect::reqwest;
use serde::{Deserialize, Serialize};
use serde_json::json;
use url::Url;
use web_push::{
ContentEncoding, PartialVapidSignatureBuilder, SubscriptionInfo, Urgency, VapidSignatureBuilder,
WebPushMessageBuilder, request_builder,
};
use crate::ops::{printable, truncate};
use crate::queue::{Decision, PendingInfo};
use crate::server::Broker;
/// Push services the major browsers use. Subscriptions elsewhere are refused, so a session can't
/// make the broker send requests to arbitrary addresses.
const PUSH_SERVICES: &[&str] =
&["fcm.googleapis.com", "push.services.mozilla.com", "push.apple.com", "notify.windows.com"];
/// Subscriptions kept for each approver; the oldest are dropped first.
const MAX_SUBSCRIPTIONS: usize = 10;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Subscription {
pub endpoint: String,
pub p256dh: String,
pub auth: String,
/// The approver's subject at the sign-in provider.
pub subject: String,
}
pub struct Push {
path: PathBuf,
/// The VAPID signing key, as base64url.
key: String,
public_key: String,
/// Who push services can contact about our pushes: the app's URL.
contact: String,
http: reqwest::Client,
subscriptions: Mutex<Vec<Subscription>>,
}
pub fn allowed_endpoint(endpoint: &str) -> Result<()> {
let url = Url::parse(endpoint)?;
let host = url.host_str().unwrap_or_default();
// Chrome's newer endpoints are on numbered hosts like `jmt17.google.com`.
let google = host
.strip_suffix(".google.com")
.and_then(|h| h.strip_prefix("jmt"))
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
ensure!(
url.scheme() == "https"
&& (google
|| PUSH_SERVICES.iter().any(|s| host == *s || host.strip_suffix(s).is_some_and(|h| h.ends_with('.')))),
"not a known push service"
);
Ok(())
}
impl Push {
/// Loads the signing key and subscriptions from `directory`, creating the key the first time.
pub fn open(directory: &Path, contact: &str) -> Result<Push> {
let key_path = directory.join("vapid.key");
let key = match std::fs::read_to_string(&key_path) {
Ok(key) => key.trim().to_owned(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let key = base64url(&rand::random::<[u8; 32]>());
std::fs::write(&key_path, &key).context("saving the push signing key")?;
key
}
Err(error) => return Err(error).context("reading the push signing key"),
};
let builder = VapidSignatureBuilder::from_base64_no_sub(&key).context("the push signing key is invalid")?;
let path = directory.join("push.json");
let subscriptions = match std::fs::read(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).context("parsing push subscriptions")?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => vec![],
Err(error) => return Err(error).context("reading push subscriptions"),
};
Ok(Push {
path,
key,
public_key: base64url(&PartialVapidSignatureBuilder::get_public_key(&builder)),
contact: contact.to_owned(),
http: reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(15))
.build()?,
subscriptions: Mutex::new(subscriptions),
})
}
/// The application server key browsers subscribe with.
pub fn public_key(&self) -> &str {
&self.public_key
}
pub fn subscribe(&self, subscription: Subscription) -> Result<()> {
allowed_endpoint(&subscription.endpoint)?;
let mut subscriptions = self.subscriptions.lock().unwrap();
subscriptions.retain(|s| s.endpoint != subscription.endpoint);
let theirs = subscriptions.iter().filter(|s| s.subject == subscription.subject).count();
if theirs >= MAX_SUBSCRIPTIONS {
let oldest = subscriptions.iter().position(|s| s.subject == subscription.subject).unwrap();
subscriptions.remove(oldest);
}
subscriptions.push(subscription);
self.save(&subscriptions)
}
pub fn unsubscribe(&self, endpoint: &str, subject: &str) -> Result<()> {
let mut subscriptions = self.subscriptions.lock().unwrap();
subscriptions.retain(|s| !(s.endpoint == endpoint && s.subject == subject));
self.save(&subscriptions)
}
fn save(&self, subscriptions: &[Subscription]) -> Result<()> {
let temporary = self.path.with_extension("tmp");
std::fs::write(&temporary, serde_json::to_vec(subscriptions)?)?;
std::fs::rename(&temporary, &self.path).context("saving push subscriptions")
}
/// Sends one push; `Ok(false)` means the subscription is gone.
async fn send(&self, subscription: &Subscription, payload: &[u8], ttl: u32, topic: &str) -> Result<bool> {
let info = SubscriptionInfo::new(&subscription.endpoint, &subscription.p256dh, &subscription.auth);
let mut signature = VapidSignatureBuilder::from_base64(&self.key, &info)?;
signature.add_claim("sub", self.contact.as_str());
let mut message = WebPushMessageBuilder::new(&info);
message.set_payload(ContentEncoding::Aes128Gcm, payload);
message.set_ttl(ttl);
message.set_urgency(Urgency::High);
// A later push with the same topic replaces one the browser hasn't received yet.
message.set_topic(topic.to_owned());
message.set_vapid_signature(signature.build()?);
let request = request_builder::build_request::<Vec<u8>>(message.build()?);
let mut outgoing = self.http.post(request.uri().to_string());
for (name, value) in request.headers() {
outgoing = outgoing.header(name.as_str(), value.as_bytes());
}
let response = outgoing.body(request.into_body()).send().await?;
match response.status().as_u16() {
200..=299 => Ok(true),
404 | 410 => Ok(false),
status => bail!("push service answered {status}"),
}
}
/// Sends a payload to every subscription, dropping those that are gone.
async fn broadcast(&self, payload: &serde_json::Value, ttl: u32, topic: &str) {
let payload = payload.to_string();
let subscriptions = self.subscriptions.lock().unwrap().clone();
let results =
futures_util::future::join_all(subscriptions.iter().map(|s| self.send(s, payload.as_bytes(), ttl, topic)))
.await;
let mut gone = vec![];
for (subscription, result) in subscriptions.iter().zip(results) {
match result {
Ok(true) => {}
Ok(false) => gone.push(subscription.endpoint.clone()),
Err(error) => eprintln!("<4>Web Push to {} failed: {error:#}", host(&subscription.endpoint)),
}
}
if !gone.is_empty() {
let mut subscriptions = self.subscriptions.lock().unwrap();
subscriptions.retain(|s| !gone.contains(&s.endpoint));
if let Err(error) = self.save(&subscriptions) {
eprintln!("<4>{error:#}");
}
}
}
/// Notifies about new pending requests, and clears notifications once they're answered.
pub async fn run(self: Arc<Self>, broker: Arc<Broker>) {
let mut changes = broker.queue.subscribe();
let mut sent: HashSet<String> = HashSet::new();
loop {
let pending = broker.queue.list();
let new: Vec<&PendingInfo> = pending.iter().filter(|e| !sent.contains(&e.id)).collect();
for entry in new {
let ttl = entry.expires_in.try_into().unwrap_or(u32::MAX);
self.broadcast(&notification(entry), ttl, &topic(&entry.id)).await;
sent.insert(entry.id.clone());
}
let gone: Vec<String> = sent.iter().filter(|id| !pending.iter().any(|e| &e.id == *id)).cloned().collect();
for id in gone {
self.broadcast(&json!({ "kind": "clear", "id": id }), 600, &topic(&id)).await;
sent.remove(&id);
}
tokio::select! {
_ = changes.changed() => {}
_ = tokio::time::sleep(Duration::from_secs(30)) => {}
}
}
}
}
fn base64url(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
fn host(endpoint: &str) -> String {
Url::parse(endpoint).ok().and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default()
}
/// Push topics are at most 32 URL-safe characters.
fn topic(id: &str) -> String {
format!("slop{}", &id[..id.len().min(28)])
}
/// What the service worker shows. Android shows two buttons at most, so leases are left to the
/// page; requests that need a passkey can only be denied from the notification.
pub fn notification(entry: &PendingInfo) -> serde_json::Value {
let mut actions = vec![];
if !entry.passkey {
actions.push(json!({ "action": Decision::Once.name(), "title": Decision::Once.title() }));
}
actions.push(json!({ "action": Decision::Deny.name(), "title": Decision::Deny.title() }));
let mut body = format!("{}\n{}", entry.summary, truncate(&entry.detail, 300));
if let Some(label) = &entry.label {
body += &format!("\nLabel (agent-supplied): {}", truncate(label, 120));
}
body += &format!("\nFrom {}", entry.requester);
if entry.passkey {
body += "\nNeeds a passkey: open to approve";
}
let title = match (entry.sensitive, entry.passkey) {
(true, _) => "Agent approval (sensitive)",
(false, true) => "Agent approval (passkey)",
(false, false) => "Agent approval",
};
json!({
"kind": "request",
"id": entry.id,
"title": title,
"body": printable(&body),
"url": format!("/requests/{}", entry.id),
"actions": actions,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_known_push_services() {
assert!(allowed_endpoint("https://fcm.googleapis.com/fcm/send/abc").is_ok());
assert!(allowed_endpoint("https://updates.push.services.mozilla.com/wpush/v2/abc").is_ok());
assert!(allowed_endpoint("https://web.push.apple.com/abc").is_ok());
assert!(allowed_endpoint("https://jmt17.google.com/fcm/send/abc").is_ok());
assert!(allowed_endpoint("https://jmt.google.com/abc").is_err());
assert!(allowed_endpoint("https://mail.google.com/abc").is_err());
assert!(allowed_endpoint("http://fcm.googleapis.com/fcm/send/abc").is_err());
assert!(allowed_endpoint("https://evilpush.apple.com/abc").is_err());
assert!(allowed_endpoint("https://fcm.googleapis.com.evil.example/abc").is_err());
assert!(allowed_endpoint("https://broker.example.org/abc").is_err());
}
#[test]
fn passkey_requests_can_only_be_denied_from_notifications() {
let mut entry = PendingInfo {
id: "abc".into(),
requester: "slop-cannon".into(),
op: "deploy".into(),
summary: "deploy river".into(),
detail: "Commits:\n…".into(),
label: None,
sensitive: false,
passkey: false,
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
expires_in: 300,
};
let actions = |e: &PendingInfo| notification(e)["actions"].as_array().unwrap().len();
assert_eq!(actions(&entry), 2);
entry.passkey = true;
assert_eq!(actions(&entry), 1);
assert_eq!(notification(&entry)["actions"][0]["action"], "deny");
}
#[test]
fn creates_and_keeps_a_signing_key() {
let directory = tempfile::tempdir().unwrap();
let first = Push::open(directory.path(), "https://approve.example").unwrap();
let second = Push::open(directory.path(), "https://approve.example").unwrap();
assert_eq!(first.public_key(), second.public_key());
// An uncompressed P-256 point.
assert_eq!(first.public_key().len(), 87);
}
}
+27
View File
@@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/style.css">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="/icon.svg">
<script src="/app.js" defer></script>
</head>
<body>
{% block header -%}
<header>
<nav><a href="/">Pending</a> <a href="/log">Log</a></nav>
<form method="post" action="/auth/logout" class="account">
<span>{{ name }}</span>
<input type="hidden" name="csrf" value="{{ csrf }}">
<button type="submit" class="quiet">Sign out</button>
</form>
</header>
{%- endblock %}
<main>
{% block main %}{% endblock %}
</main>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
{% extends "base.html" %}
{% block title %}Approvals{% endblock %}
{% block main %}
<h1>Pending requests</h1>
<section id="push" hidden>
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
</section>
<div id="pending" data-version="{{ version }}">
{% include "pending.html" %}
</div>
{% endblock %}
+32
View File
@@ -0,0 +1,32 @@
{% extends "base.html" %}
{% import "macros.html" as m %}
{% block title %}Audit log{% endblock %}
{% block main %}
<h1>Audit log</h1>
<form method="get" action="/log" class="filters">
{% call m::select("requester", "Requester", filters.requester, requesters) %}{% endcall %}
{% call m::select("op", "Operation", filters.op, ops) %}{% endcall %}
{% call m::select("outcome", "Outcome", filters.outcome, outcomes) %}{% endcall %}
<label>Search <input type="search" name="text" value="{{ filters.text }}" placeholder="ID, summary or label"></label>
<button type="submit">Filter</button>
<a href="/log">Clear</a>
</form>
{% if histories.is_empty() %}
<p class="empty">No requests match.</p>
{% else %}
<div class="scroll"><table class="log"><thead><tr><th>Time</th><th>Requester</th><th>Request</th><th>Outcome</th><th>Approved by</th></tr></thead><tbody>
{% for h in histories %}
<tr><td>{% call m::time(h.time) %}{% endcall %}</td><td>{{ h.requester }}</td>
<td><a href="/requests/{{ h.id }}">{% if h.summary.is_empty() %}Request {{ self::short(h.id) }}{% else %}{{ h.summary }}{% endif %}</a> <span class="badge">{{ h.op }}</span>
{%- if let Some(label) = h.label %}<div class="label">{{ label }}</div>{% endif %}</td>
<td>{% call m::outcome(h.outcome) %}{% endcall %}</td><td>{% if let Some(by) = h.approved_by %}{{ by }}{% endif %}</td></tr>
{% endfor %}
</tbody></table></div>
{% endif %}
{% if matched > histories.len() %}
<p class="note">Showing the newest {{ histories.len() }} of {{ matched }} matching requests.</p>
{% endif %}
{% if !refused.is_empty() %}
<details><summary>Refused connections ({{ refused.len() }})</summary>{% call m::timeline(refused) %}{% endcall %}</details>
{% endif %}
{% endblock %}
+55
View File
@@ -0,0 +1,55 @@
{# A padlock, marking what needs a passkey #}
{% macro lock() -%}
<svg class="lock" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 7V5a4 4 0 0 1 8 0v2h1v8H3V7zm2 0h4V5a2 2 0 0 0-4 0z"/></svg>
{%- endmacro %}
{% macro card(entry, csrf, open) %}
<article class="request{% if entry.passkey %} needs-passkey{% endif %}" id="r-{{ entry.id }}">
<h2><a href="/requests/{{ entry.id }}">{{ entry.summary }}</a></h2>
<p class="meta">{{ entry.requester }} · {{ entry.op }} · <span class="expires" data-left="{{ entry.expires_in }}">expires in {{ self::left(entry.expires_in) }}</span>
{%- if entry.passkey %} <span class="badge passkey">{% call lock() %}{% endcall %}Needs passkey</span>{% endif %}
{%- if entry.sensitive %} <span class="badge warn">Sensitive</span>{% endif %}</p>
{% 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 %}
<form method="post" action="/requests/{{ entry.id }}" class="answers">
<input type="hidden" name="csrf" value="{{ csrf }}">
{% for decision in entry.offers %}
{% let deny = self::is_deny(decision) %}
<button type="submit" name="decision" value="{{ decision.name() }}" class="{% if deny %}deny{% else %}approve{% endif %}">
{%- if entry.passkey && !deny %}{% call lock() %}{% endcall %}{% endif %}{{ self::answer(decision) }}</button>
{% endfor %}
</form>
{% if entry.passkey %}
<p class="note">Policy wants a fresh passkey for this one: approving sends you to sign in again. Denying doesn't.</p>
{% endif %}
</article>
{% endmacro %}
{% macro time(rfc3339) -%}
<time datetime="{{ rfc3339 }}">{{ rfc3339.replace('T', " ").trim_end_matches('Z') }} UTC</time>
{%- endmacro %}
{% macro outcome(outcome) -%}
<span class="outcome {{ outcome.tone() }}">{{ outcome.name() }}</span>
{%- endmacro %}
{% macro timeline(records) %}
<ol class="timeline">
{% for record in records %}
{% let (text, detail) = self::describe(record) %}
<li>{% call time(record.time) %}{% endcall %} <span>{{ text }}</span>
{%- if let Some(detail) = detail %}<details><summary>Details</summary><pre>{{ detail }}</pre></details>{% endif %}</li>
{% endfor %}
</ol>
{% endmacro %}
{% macro select(name, label, chosen, options) -%}
<label>{{ label }} <select name="{{ name }}"><option value="">Any</option>
{%- for (value, text) in options %}<option value="{{ value }}"{% if value.as_str() == chosen.as_str() %} selected{% endif %}>{{ text }}</option>{% endfor -%}
</select></label>
{%- endmacro %}
+8
View File
@@ -0,0 +1,8 @@
{% extends "base.html" %}
{% block title %}{{ title }}{% endblock %}
{% block header %}{% endblock %}
{% block main %}
<h1>{{ title }}</h1>
<p>{{ text }}</p>
<p><a href="/">Back to the approvals</a></p>
{% endblock %}
+15
View File
@@ -0,0 +1,15 @@
{%- import "macros.html" as m -%}
{% if entries.is_empty() %}
<p class="empty">Nothing is waiting for an answer.</p>
{% endif %}
{% for entry in entries %}
{% call m::card(entry, csrf, false) %}{% endcall %}
{% endfor %}
{% if !leases.is_empty() %}
<h2>Active leases</h2>
<table><thead><tr><th>Requester</th><th>Scope</th><th>Left</th></tr></thead><tbody>
{% for (requester, scope, seconds) in leases %}
<tr><td>{{ requester }}</td><td><code>{{ scope }}</code></td><td>{{ self::left(seconds) }}</td></tr>
{% endfor %}
</tbody></table>
{% endif %}
+20
View File
@@ -0,0 +1,20 @@
{% extends "base.html" %}
{% import "macros.html" as m %}
{% block title %}Approval request{% endblock %}
{% block main %}
<h1>{{ heading }}</h1>
<div id="request" data-version="{{ version }}">
{% if let Some(entry) = entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(past) = past %}
{% if entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
{% endif %}
<h2>History</h2>
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
{% else if entry.is_none() %}
<p class="empty">The audit log has nothing about this request.</p>
{% endif %}
</div>
{% endblock %}
+6 -3
View File
@@ -211,7 +211,7 @@ async fn ask_waits_for_an_approver_and_leases_cover_repeats() {
assert_eq!(listed[0].label.as_deref(), Some("test"));
assert_eq!(listed[0].offers, [Decision::Once, Decision::Lease(300), Decision::Deny]);
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test").unwrap();
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).unwrap();
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true });
@@ -241,8 +241,11 @@ async fn denial_and_expiry() {
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
let mut client = Client::start(&broker, ssh(&["true"])).await;
let id = pending_id(&mut client).await;
assert!(slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test").is_err(), "lease not offered");
slop_broker::approve::approve(&broker, &id, Decision::Deny, "test").unwrap();
assert!(
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).is_err(),
"lease not offered"
);
slop_broker::approve::approve(&broker, &id, Decision::Deny, "test", false).unwrap();
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_)));
let mut client = Client::start(&broker, ssh(&["true"])).await;