Files
slop-broker/src/web/mod.rs
T
jackos1998andClaude Opus 5.5 652e80961a web: Ask for the passkey on every sign-in
Signing out only ended the app's session: the next sign-in went
through the provider's still-valid session without a prompt, so
signing out seemed to do nothing. Sign-ins now ask the provider to
authenticate afresh and check the token's auth_time, as passkey
confirmations already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:31:23 +00:00

524 lines
20 KiB
Rust

//! 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 { ref next } => {
auth::fresh(&flow, &identity).map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
// 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() }));
}
}