From 950b757ca34baf783251c58968efd2d84db7c95a Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 20:38:58 +0000 Subject: [PATCH 1/2] web: Add a mode without sign-in, for the demo and tests `[web.no_sign_in]` instead of the OIDC settings makes everyone who reaches the web app one approver, so the demo needn't run a sign-in provider and tests can use the app. It only listens on a loopback address, every page says there's no sign-in, the audit log records ` (web, no sign-in)`, and it can't approve requests that need a passkey. The NixOS module has it only as an internal option, for the VM test. The VM test uses it to check a finished deploy's page, the event stream, and answering a request with the session's token. Refs #28 Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 3 +- nix/modules/nixos/broker.nix | 21 +++++-- nix/vm-test.nix | 51 ++++++++++++++++ src/bin/slop-broker.rs | 19 ++++-- src/config.rs | 95 +++++++++++++++++++++++++++-- src/web/assets/style.css | 9 +++ src/web/auth.rs | 12 ++-- src/web/mod.rs | 112 +++++++++++++++++++++++++---------- src/web/page.rs | 11 ++++ templates/base.html | 5 ++ 10 files changed, 286 insertions(+), 52 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index ea1b92e..7130fa9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -177,7 +177,7 @@ What each request runs, and whose code, decides whether it needs an approval fir | `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name | | `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` | | `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` | -| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) | +| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`; `[web.no_sign_in]` goes without, for the demo and tests), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) | | `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it | | `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks..vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs, host side and repository template (`demo/`, `packages..demo` and `demo-box`, and `host.nix`, which `devenv.nix` imports) | | `devenv.nix` | The development environment and its scripts, with the demo's host side (`devenv up`) from `nix/demo/host.nix`; `nix develop` gives a plainer shell from `flake.nix` without them | @@ -566,6 +566,7 @@ none can be read as an option, and `--` comes before the hostname. | `slop-approve` on the broker's box | `approve.sock`, for the `slop-broker-approve` group | The user name | | `slop-approve` on another box | SSH, a key in `sshApprovers` | ` (ssh)` | | The web app | OpenID Connect | ` (web)`, or ` (web, passkey)` | +| The web app without sign-in, for the demo and tests | `[web.no_sign_in]`, only on a loopback address | ` (web, no sign-in)` | - A requester's UID is refused on `approve.sock` even if it's in the group. - All of them call `approve::approve`, which records the decision and audits it. The approver's diff --git a/nix/modules/nixos/broker.nix b/nix/modules/nixos/broker.nix index 2f5efa6..dd29cd9 100644 --- a/nix/modules/nixos/broker.nix +++ b/nix/modules/nixos/broker.nix @@ -127,11 +127,15 @@ let web = if web.enable then { listen = "${if hasInfix ":" web.address then "[${web.address}]" else web.address}:${toString web.port}"; - inherit (web) url issuer group; + inherit (web) url; + state_dir = "/var/lib/slop-broker/web"; + } // (if web.noSignIn == null then { + inherit (web) issuer group; client_id = web.clientId; client_secret = "oidc-secret"; - state_dir = "/var/lib/slop-broker/web"; - } else null; + } else { + no_sign_in.approver = web.noSignIn; + }) else null; secrets = if secrets.enable then { identity = "age-identity"; @@ -190,6 +194,12 @@ in 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."; + noSignIn = mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + internal = true; + description = "For tests only: no sign-in, with everyone who reaches the web app approving as this name."; + }; }; secrets = { @@ -229,7 +239,8 @@ in message = "slop-broker SSH keys must be distinct; use separate keys for requesting and approving."; } { - assertion = web.enable -> (web.url != "" && web.issuer != "" && isRuntimePath web.clientSecretFile); + assertion = web.enable -> (web.url != "" + && (web.noSignIn != null || (web.issuer != "" && isRuntimePath web.clientSecretFile))); message = "slop-broker's web app needs a URL, an issuer and a runtime client secret file."; } { @@ -278,7 +289,7 @@ in LoadCredential = optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++ optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++ - optional web.enable "oidc-secret:${web.clientSecretFile}" ++ + optional (web.enable && web.noSignIn == null) "oidc-secret:${web.clientSecretFile}" ++ optional secrets.enable "age-identity:${secrets.identityFile}"; User = "slop-broker"; diff --git a/nix/vm-test.nix b/nix/vm-test.nix index 417afe7..8e04226 100644 --- a/nix/vm-test.nix +++ b/nix/vm-test.nix @@ -141,6 +141,13 @@ pkgs.testers.runNixOSTest { user = "cache"; inherit keyFile; }; + + # The web app without sign-in, which the test reaches with `curl` + web = { + enable = true; + url = "http://localhost:8095"; + noSignIn = "tester"; + }; }; # The builder only reads the repository, a local copy, so its key is never used @@ -158,6 +165,9 @@ pkgs.testers.runNixOSTest { }; testScript = '' + import json + import re + # Commands as the agent, sending requests over vsock (or `broker`) vsock = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'" @@ -365,5 +375,46 @@ pkgs.testers.runNixOSTest { assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit assert "answered once by laptop (ssh)" in audit, audit assert "finished with exit status 0" in audit and "activated box in" in audit, audit + + # The web app, without sign-in: everyone who reaches it approves as `tester` + + app = "http://localhost:8095" + def page(path): + return machine.succeed(f"curl -sf -c /tmp/cookies -b /tmp/cookies {app}{path}") + + def found(pattern, text): + """The first group of `pattern` in `text`, which must match.""" + match = re.search(pattern, text) + assert match, (pattern, text) + return match.group(1) + + machine.wait_for_open_port(8095) + out = page("/") + assert "No sign-in" in out and "tester" in out and "Sign out" not in out, out + + # A finished deploy's page keeps how each phase ended + records = [json.loads(line) for line in approve("log -n 200 --json").splitlines()] + deploy = next( + r["id"] for r in records + if r["event"] == "request" and r["summary"].startswith("deploy box.system, local.system ") + ) + out = page(f"/requests/{deploy}") + for line in ["evaluated in", "built: 1 derivation in", "copied to box: 2 paths (", "activated box in"]: + assert line in out, (line, out) + + # The main page's event stream starts with its regions + status, out = machine.execute(f"curl -sN --max-time 3 -b /tmp/cookies {app}/events") + assert "event: morph" in out and 'id="pending"' in out and 'id="running"' in out, out + + # Answering a request from its page, which needs the session's token + slop_in_background("slop ssh other -- echo answered on the web", "/tmp/out5") + wait_for_request("ssh other") + request = found(r'/requests/([0-9a-f]{16})', page("/")) + csrf = found(r'name="csrf" value="([0-9a-f]+)"', page(f"/requests/{request}")) + answer = f"curl -sf -o /dev/null -b /tmp/cookies -H 'Origin: {app}' -d decision=once {app}/requests/{request}" + machine.fail(answer + " -d csrf=wrong") + machine.succeed(answer + f" -d csrf={csrf}") + machine.wait_until_succeeds("grep -q 'answered on the web' /tmp/out5") + assert "answered once by tester (web, no sign-in)" in approve("log -n 5"), approve("log -n 5") ''; } diff --git a/src/bin/slop-broker.rs b/src/bin/slop-broker.rs index f7dcfe3..f82edfe 100644 --- a/src/bin/slop-broker.rs +++ b/src/bin/slop-broker.rs @@ -6,7 +6,7 @@ use anyhow::{Context, Result}; use clap::Parser; use nix::sys::signal::{SigHandler, Signal, signal}; -use slop_broker::config::{Config, credential, group_id, user_id}; +use slop_broker::config::{Config, SignIn, credential, group_id, user_id}; use slop_broker::remote::{self, Role}; use slop_broker::server::{self, Broker}; use slop_broker::{approve, web}; @@ -85,10 +85,19 @@ async fn serve(path: &Path) -> Result<()> { 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"); + let secret = match &settings.sign_in { + SignIn::Oidc(oidc) => { + let secret = std::fs::read_to_string(credential(&oidc.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(secret) + } + SignIn::None { approver } => { + eprintln!("<4>the web app has no sign-in: everyone who reaches it approves as {approver}"); + None + } + }; Some((settings.clone(), secret)) } None => None, diff --git a/src/config.rs b/src/config.rs index 9e5c9e5..1794623 100644 --- a/src/config.rs +++ b/src/config.rs @@ -85,13 +85,32 @@ fn default_rules() -> crate::types::RulesPath { /// 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)] +#[serde(try_from = "RawWebConfig")] 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, + pub sign_in: SignIn, + /// How long a session lasts without being used. + pub session: u64, + /// Where sessions, push subscriptions and the push signing key are kept. + pub state_dir: PathBuf, +} +/// How approvers sign in to the web app. +#[derive(Debug, Clone, PartialEq)] +pub enum SignIn { + Oidc(OidcConfig), + /// Not at all: everyone who reaches the app is `approver`, for the demo and tests. Only on a + /// loopback address, and it can't approve requests that need a passkey. + None { + approver: String, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OidcConfig { /// OpenID Connect issuer. pub issuer: String, pub client_id: String, @@ -99,12 +118,55 @@ pub struct WebConfig { 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. +/// `[web]` as written: the OIDC settings, or `[web.no_sign_in]`. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawWebConfig { + listen: std::net::SocketAddr, + url: String, + issuer: Option, + client_id: Option, + client_secret: Option, + group: Option, + no_sign_in: Option, #[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, + session: u64, + state_dir: PathBuf, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct NoSignIn { + approver: String, +} + +impl TryFrom for WebConfig { + type Error = String; + + fn try_from(raw: RawWebConfig) -> Result { + let sign_in = match (raw.no_sign_in, raw.issuer, raw.client_id, raw.client_secret, raw.group) { + (None, Some(issuer), Some(client_id), Some(client_secret), Some(group)) => { + SignIn::Oidc(OidcConfig { issuer, client_id, client_secret, group }) + } + (Some(NoSignIn { approver }), None, None, None, None) => { + if !raw.listen.ip().is_loopback() { + return Err(format!( + "the web app only goes without sign-in on a loopback address, not {}", + raw.listen + )); + } + if approver.trim().is_empty() { + return Err("no_sign_in needs the name of its approver".into()); + } + SignIn::None { approver } + } + (None, ..) => return Err("the web app needs issuer, client_id, client_secret and group".into()), + (Some(_), ..) => return Err("no_sign_in can't have issuer, client_id, client_secret or group".into()), + }; + Ok(WebConfig { listen: raw.listen, url: raw.url, sign_in, session: raw.session, state_dir: raw.state_dir }) + } } fn default_session() -> u64 { @@ -370,6 +432,29 @@ mod tests { use super::*; use crate::policy::OpName; + fn web(text: &str) -> Result { + toml::from_str::(text).map_err(|e| e.message().to_owned()) + } + + #[test] + fn web_signs_in_or_not() { + let common = "url = \"http://localhost:8095\"\nstate_dir = \"/var/lib/web\"\n"; + let oidc = "issuer = \"https://id.example.org\"\nclient_id = \"c\"\nclient_secret = \"s\"\ngroup = \"g\"\n"; + let none = "[no_sign_in]\napprover = \"demo\"\n"; + + let config = web(&format!("listen = \"[::]:8095\"\n{common}{oidc}")).unwrap(); + assert!(matches!(config.sign_in, SignIn::Oidc(ref o) if o.group == "g")); + + let config = web(&format!("listen = \"127.0.0.1:8095\"\n{common}{none}")).unwrap(); + assert_eq!(config.sign_in, SignIn::None { approver: "demo".into() }); + + // Without sign-in only on loopback, and not mixed with OIDC settings + let refused = web(&format!("listen = \"[::]:8095\"\n{common}{none}")).unwrap_err(); + assert!(refused.contains("loopback"), "{refused}"); + assert!(web(&format!("listen = \"[::1]:8095\"\n{common}{oidc}{none}")).is_err()); + assert!(web(&format!("listen = \"[::1]:8095\"\n{common}")).is_err()); + } + /// The layout the NixOS module writes. #[test] fn parses_generated_config() { diff --git a/src/web/assets/style.css b/src/web/assets/style.css index f97ed80..f075723 100644 --- a/src/web/assets/style.css +++ b/src/web/assets/style.css @@ -68,6 +68,15 @@ header { background: var(--surface); } +/* Without sign-in (the demo and tests), on every page */ +.no-sign-in { + margin: 0; + padding: 6px 16px; + background: var(--bad-bg); + color: var(--bad); + font-size: 0.9rem; +} + nav a { margin-right: 16px; } diff --git a/src/web/auth.rs b/src/web/auth.rs index 60075c6..7c07139 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -16,7 +16,7 @@ use openidconnect::{ }; use serde::{Deserialize, Serialize}; -use crate::config::WebConfig; +use crate::config::OidcConfig; use crate::queue::Decision; /// The `groups` claim, which providers such as Pocket ID add for the `groups` scope. @@ -102,7 +102,9 @@ pub struct Identity { } pub struct Oidc { - config: WebConfig, + config: OidcConfig, + /// The web app's URL, for the provider to send approvers back to. + url: String, secret: String, http: reqwest::Client, client: tokio::sync::Mutex>, @@ -113,13 +115,13 @@ pub fn now() -> i64 { } impl Oidc { - pub fn new(config: WebConfig, secret: String) -> Result { + pub fn new(config: OidcConfig, url: String, secret: String) -> Result { // 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) }) + Ok(Oidc { config, url, 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 @@ -147,7 +149,7 @@ impl Oidc { async fn discover(&self) -> Result { 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('/')))?; + let redirect = RedirectUrl::new(format!("{}/auth/callback", self.url.trim_end_matches('/')))?; Ok(Client::from_provider_metadata( metadata, diff --git a/src/web/mod.rs b/src/web/mod.rs index 1229fe4..15e2daa 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -23,7 +23,7 @@ use tower_sessions::{ExpiredDeletion, Expiry, Session, SessionManagerLayer}; use tower_sessions_rusqlite_store::{RusqliteStore, tokio_rusqlite}; use crate::approve; -use crate::config::WebConfig; +use crate::config::{SignIn, WebConfig}; use crate::queue::{Decision, PendingInfo}; use crate::server::Broker; use auth::{Flow, Oidc, Purpose}; @@ -34,10 +34,18 @@ struct Web { broker: Arc, /// The app's origin, which every POST must come from. origin: String, - oidc: Oidc, + approvers: Approvers, push: Arc, } +/// Who approvers are. +enum Approvers { + /// Whoever signs in through the provider. + Oidc(Box), + /// Everyone who reaches the app, as this name (`no_sign_in`). + Fixed(String), +} + /// The signed-in approver, kept in the session. #[derive(Debug, Clone, Serialize, Deserialize)] struct User { @@ -59,9 +67,20 @@ fn origin(url: &str) -> Result { Ok(url.origin().ascii_serialization()) } -pub async fn run(broker: Arc, config: WebConfig, secret: String) -> Result<()> { +/// Serves the web app. `secret` is the OIDC client's, when approvers sign in. +pub async fn run(broker: Arc, config: WebConfig, secret: Option) -> Result<()> { let origin = origin(&config.url)?; - let issuer = url::Url::parse(&config.issuer)?.origin().ascii_serialization(); + let (approvers, issuer) = match config.sign_in.clone() { + SignIn::Oidc(oidc) => { + let issuer = url::Url::parse(&oidc.issuer)?.origin().ascii_serialization(); + let secret = secret.context("no OIDC client secret")?; + (Approvers::Oidc(Box::new(Oidc::new(oidc, config.url.clone(), secret)?)), issuer) + } + SignIn::None { approver } => { + page::set_no_sign_in(); + (Approvers::Fixed(approver), String::new()) + } + }; // 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); @@ -77,7 +96,7 @@ pub async fn run(broker: Arc, config: WebConfig, secret: String) -> Resu .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 }); + let web = Arc::new(Web { approvers, broker: broker.clone(), origin, push }); tokio::spawn(web.push.clone().run(broker)); let app = Router::new() @@ -148,21 +167,41 @@ fn failure(status: StatusCode, message: &str) -> Failure { Failure(status, message.to_owned()) } -async fn user(session: &Session) -> Result, Failure> { - Ok(session.get::(USER).await?) +/// The signed-in approver. Without sign-in, every session is the configured approver. +async fn user(web: &Web, session: &Session) -> Result, Failure> { + if let Some(user) = session.get::(USER).await? { + return Ok(Some(user)); + } + let Approvers::Fixed(name) = &web.approvers else { return Ok(None) }; + + let user = User { subject: format!("no-sign-in:{name}"), name: name.clone(), csrf: new_csrf() }; + session.insert(USER, user.clone()).await?; + Ok(Some(user)) +} + +fn new_csrf() -> String { + hex::encode(rand::random::<[u8; 32]>()) +} + +/// The provider approvers sign in with, if they do. +fn oidc(web: &Web) -> Result<&Oidc, Failure> { + match &web.approvers { + Approvers::Oidc(oidc) => Ok(oidc), + Approvers::Fixed(_) => Err(failure(StatusCode::NOT_FOUND, "this web app has no sign-in")), + } } /// The signed-in approver, or a redirect to sign in and come back to `here`. -async fn signed_in(session: &Session, here: &str) -> Result, Failure> { - Ok(match user(session).await? { +async fn signed_in(web: &Web, session: &Session, here: &str) -> Result, Failure> { + Ok(match user(web, 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(session).await?.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "sign in first")) +async fn api_user(web: &Web, session: &Session) -> Result { + user(web, 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. @@ -189,8 +228,13 @@ fn fingerprint(entry: &PendingInfo) -> String { hex::encode(hash.finalize()) } -fn approver(user: &User, passkey: bool) -> String { - if passkey { format!("{} (web, passkey)", user.name) } else { format!("{} (web)", user.name) } +/// The approver as the audit log names them, like `dev (web, passkey)`. +fn approver(web: &Web, user: &User, passkey: bool) -> String { + match (&web.approvers, passkey) { + (Approvers::Fixed(_), _) => format!("{} (web, no sign-in)", user.name), + (_, true) => format!("{} (web, passkey)", user.name), + (_, false) => format!("{} (web)", user.name), + } } fn pending(web: &Web, id: &str) -> Option { @@ -198,7 +242,7 @@ fn pending(web: &Web, id: &str) -> Option { } async fn index(State(web): State>, session: Session) -> Result { - let user = match signed_in(&session, "/").await? { + let user = match signed_in(&web, &session, "/").await? { Ok(user) => user, Err(redirect) => return Ok(redirect), }; @@ -213,7 +257,7 @@ async fn request_page( session: Session, Path(id): Path, ) -> Result { - let user = match signed_in(&session, &format!("/requests/{id}")).await? { + let user = match signed_in(&web, &session, &format!("/requests/{id}")).await? { Ok(user) => user, Err(redirect) => return Ok(redirect), }; @@ -241,7 +285,7 @@ async fn page_events( session: Session, Query(query): Query, ) -> Result { - api_user(&session).await?; + api_user(&web, &session).await?; Ok(events::stream(web.broker.clone(), session, query.request)) } @@ -260,7 +304,7 @@ async fn answer( Path(id): Path, axum::Form(form): axum::Form, ) -> Result { - let user = api_user(&session).await?; + let user = api_user(&web, &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"); @@ -272,6 +316,12 @@ async fn answer( } if entry.passkey && decision != Decision::Deny { + if let Approvers::Fixed(_) = web.approvers { + return Err(failure( + StatusCode::FORBIDDEN, + "this request needs a passkey, which needs a web app with sign-in", + )); + } if script { return Err(failure(StatusCode::FORBIDDEN, "this request needs a passkey; open it to approve")); } @@ -279,7 +329,7 @@ async fn answer( return start(&web, &session, purpose).await; } - approve::approve(&web.broker, &id, decision, &approver(&user, false), false) + approve::approve(&web.broker, &id, decision, &approver(&web, &user, false), false) .map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?; Ok(if script { StatusCode::NO_CONTENT.into_response() } else { Redirect::to("/").into_response() }) } @@ -295,7 +345,7 @@ async fn log_page( session: Session, Query(filters): Query, ) -> Result { - let user = match signed_in(&session, "/log").await? { + let user = match signed_in(&web, &session, "/log").await? { Ok(user) => user, Err(redirect) => return Ok(redirect), }; @@ -322,13 +372,13 @@ async fn log_page( Ok(page::log(&user.name, &user.csrf, &view).into_response()) } -async fn csrf(session: Session) -> Result { - let user = api_user(&session).await?; +async fn csrf(State(web): State>, session: Session) -> Result { + let user = api_user(&web, &session).await?; Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response()) } async fn push_key(State(web): State>, session: Session) -> Result { - api_user(&session).await?; + api_user(&web, &session).await?; Ok(web.push.public_key().to_owned().into_response()) } @@ -351,7 +401,7 @@ async fn subscribe( headers: HeaderMap, axum::Json(subscription): axum::Json, ) -> Result { - let user = api_user(&session).await?; + let user = api_user(&web, &session).await?; check_post(&web, &headers, &user, None)?; let subscription = Subscription { @@ -382,7 +432,7 @@ async fn unsubscribe( headers: HeaderMap, axum::Json(request): axum::Json, ) -> Result { - let user = api_user(&session).await?; + let user = api_user(&web, &session).await?; check_post(&web, &headers, &user, None)?; web.push.unsubscribe(&request.endpoint, &user.subject)?; Ok(StatusCode::NO_CONTENT.into_response()) @@ -390,7 +440,7 @@ async fn unsubscribe( /// Sends the approver to the sign-in provider, remembering why. async fn start(web: &Web, session: &Session, purpose: Purpose) -> Result { - let (url, flow) = web.oidc.begin(purpose).await?; + let (url, flow) = oidc(web)?.begin(purpose).await?; let mut flows = session.get::>(FLOWS).await?.unwrap_or_default(); flows.retain(|f| auth::now() - f.started < auth::FLOW_LIFETIME as i64); @@ -444,7 +494,8 @@ async fn callback( 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:#}")))?; + let identity = + oidc(&web)?.finish(&flow, code).await.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?; match flow.purpose { Purpose::SignIn { ref next } => { @@ -452,12 +503,11 @@ async fn callback( // 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?; + session.insert(USER, User { subject: identity.subject, name: identity.name, csrf: new_csrf() }).await?; Ok(Redirect::to(next).into_response()) } Purpose::Confirm { ref id, decision, ref shown } => { - let user = api_user(&session).await?; + let user = api_user(&web, &session).await?; auth::confirmed(&flow, &identity, &user.subject) .map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?; @@ -467,7 +517,7 @@ async fn callback( return Err(failure(StatusCode::CONFLICT, "this request changed since you answered it; look again")); } - approve::approve(&web.broker, id, decision, &approver(&user, true), true) + approve::approve(&web.broker, id, decision, &approver(&web, &user, true), true) .map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?; Ok(Redirect::to("/").into_response()) } @@ -485,7 +535,7 @@ async fn logout( headers: HeaderMap, axum::Form(form): axum::Form, ) -> Result { - if let Some(user) = user(&session).await? { + if let Some(user) = session.get::(USER).await? { check_post(&web, &headers, &user, form.csrf.as_deref())?; } session.flush().await?; diff --git a/src/web/page.rs b/src/web/page.rs index d520dc4..380f4c1 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -18,6 +18,17 @@ use crate::runs::Run; /// The broker's version, which signed-in pages show. pub use crate::VERSION; +/// Whether the web app runs without sign-in, which every page says. +static NO_SIGN_IN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub fn set_no_sign_in() { + NO_SIGN_IN.store(true, std::sync::atomic::Ordering::Relaxed); +} + +pub fn no_sign_in() -> bool { + NO_SIGN_IN.load(std::sync::atomic::Ordering::Relaxed) +} + /// HTML escaping, after replacing what [`printable`] replaces. #[derive(Debug, Clone, Copy)] pub struct Printable; diff --git a/templates/base.html b/templates/base.html index 9739293..9e27dc9 100644 --- a/templates/base.html +++ b/templates/base.html @@ -17,10 +17,15 @@ +{% if crate::web::page::no_sign_in() -%} + +{%- endif %} {%- endblock %}
{% block main %}{% endblock %} -- 2.56.0 From eefb04ff48d59abe25d7fd970fb671e0bbf05a86 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 20:38:58 +0000 Subject: [PATCH 2/2] demo: Make sign-in to the web app optional The demo's web app has no sign-in by default, so trying it doesn't need a one-time link and a passkey. `slopDemo.signIn = true;` in `devenv.local.nix` brings back Pocket ID, now in `sign-in.nix`, for trying sign-in and passkeys, which approving `router` needs. Refs #28 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/demo.md | 32 +++++++++------- nix/demo/agent.nix | 4 +- nix/demo/host.nix | 90 ++++++++------------------------------------ nix/demo/sign-in.nix | 90 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 127 insertions(+), 91 deletions(-) create mode 100644 nix/demo/sign-in.nix diff --git a/README.md b/README.md index ea9623f..1adaf02 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ OpenID Connect, passkeys, Web Push). ## Trying it ```sh -devenv up # the broker, its web app, Pocket ID and a box VM for the SSH targets +devenv up # the broker, its web app (without sign-in) and a box VM for the SSH targets demo # in another terminal: the agents' VM, signed in as an agent that can send requests ``` diff --git a/docs/demo.md b/docs/demo.md index 60e1a07..c107d1b 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -31,7 +31,7 @@ flowchart TB shell["devenv shell:
slop-approve, demo-merge"] subgraph host["Host (devenv up)"] - pocket["Pocket ID
localhost:1411"] + pocket["Pocket ID, with sign-in
localhost:1411"] broker["Broker, with the web app
localhost:8095"] daemon["git daemon"] builder["Builder"] @@ -58,7 +58,7 @@ flowchart TB |---|---|---| | Broker, from this checkout (`cargo run`) | Host | `devenv up` (process `slop-broker`) | | Web app | | Part of the broker | -| [Pocket ID](https://pocket-id.org), for approvers to sign in | | `devenv up` (process `pocket-id`) | +| [Pocket ID](https://pocket-id.org), for approvers to sign in, if they do (see [Approving](#approving)) | | `devenv up` with `slopDemo.signIn` (process `pocket-id`) | | Box VM ([`box.nix`](../nix/demo/box.nix)): `sshd` for the targets, the deploy target and the binary cache | `localhost:2222`, as `box`, and as `cache` for the cache | `devenv up` (process `box`) | | Agents' VM ([`agent.nix`](../nix/demo/agent.nix)), signed in as `agent` | Your terminal | `demo` | | The repository, seeded from [`repo/`](../nix/demo/repo) | `.devenv/state/slop-demo/git/repo.git` | `git daemon`, one per connection from the agents' VM | @@ -71,15 +71,16 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio - **Requester:** `agent`, the agents' VM's vsock CID. The VMs have no network beyond their forwarded ports, and only vsock and Git link the agents' VM to the host (see [the repository](#the-repository)). -- **Approvers:** members of your primary group, through `slop-approve` in the devenv shell, and the - Pocket ID user `demo` (in the group `slop-approvers`) through the web app. +- **Approvers:** members of your primary group, through `slop-approve` in the devenv shell, and + `demo` through the web app: everyone who opens it, or with sign-in, the Pocket ID user `demo` (in + the group `slop-approvers`). - **Targets:** the repository's deploy-rs nodes on `master`, `box`, `web`, `router` and `vault`, which all reach the box VM. Only `box` has a profile to deploy. - **Policy:** - The box queries (`slop status`, `slop logs`, `slop failed`) run without asking. - `slop ssh web` asks, and offers leases of 5 minutes or an hour. - - `slop ssh router` asks and needs a passkey (`confirm = "passkey"`), so only the web app can - approve it. + - `slop ssh router` asks and needs a passkey (`confirm = "passkey"`), so only the web app with + sign-in can approve it. - `slop ssh vault` is denied. - `slop secret keys` runs without asking; the other secret requests ask, with a 5-minute lease, except reading, which asks every time. @@ -90,9 +91,13 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio - **Terminal:** `slop-approve` in the devenv shell lists pending requests; answer one with `slop-approve once||deny`. -- **Web app:** `demo-sign-in` prints a one-time link that signs in to Pocket ID as `demo`. Add a - passkey when Pocket ID asks, then sign in to ; the passkey also approves - `router` requests. Web Push works when the broker can reach the browser's push service. +- **Web app:** , without sign-in: everyone who opens it approves as `demo`, + which every page says, and it can't approve requests that need a passkey. Web Push works when + the broker can reach the browser's push service. +- **Sign-in and passkeys:** add `slopDemo.signIn = true;` to `devenv.local.nix` (see + [`sign-in.nix`](../nix/demo/sign-in.nix)) and restart `devenv up`, which then runs Pocket ID too. + `demo-sign-in` prints a one-time link that signs in to Pocket ID as `demo`. Add a passkey when + Pocket ID asks, then sign in to the web app; the passkey also approves `router` requests. A request blocks until it's answered, and `slop ssh` reads stdin to its end before asking. To keep the agent's shell, run requests in the background with stdin closed: @@ -208,11 +213,10 @@ approved commands did; `demo-box ` runs one command there. Its console ## State The VMs keep nothing: `poweroff` (or Ctrl-A X) stops the agents' VM, and each boot starts from -scratch. The host side keeps its state in `.devenv/state/slop-demo` between runs: Pocket ID's -database (so passkeys survive), the keys, the repository and the builder's mirror, the audit log -and the web app's sessions. `demo-reset` -deletes it while `devenv up` isn't running; the next `devenv up` sets Pocket ID up again and seeds -a new repository. The repository is seeded only once, so after changing +scratch. The host side keeps its state in `.devenv/state/slop-demo` between runs: the keys, the +repository and the builder's mirror, the audit log, the web app's sessions, and with sign-in, +Pocket ID's database (so passkeys survive). `demo-reset` deletes it while `devenv up` isn't +running; the next `devenv up` seeds a new repository, and sets Pocket ID up again. The repository is seeded only once, so after changing [`nix/demo/repo`](../nix/demo/repo), reset (or delete `git`, `builder` and the `*-age.*` keys in the state directory) to use the new version. diff --git a/nix/demo/agent.nix b/nix/demo/agent.nix index d0ab94a..354c953 100644 --- a/nix/demo/agent.nix +++ b/nix/demo/agent.nix @@ -19,7 +19,7 @@ let slop status web sshd.service runs without asking (policy: auto) slop logs web sshd.service -n 20 slop ssh web -- uptime asks an approver; leases of 5m or 1h are offered - slop ssh router -- uptime asks too, and approving needs a passkey in the web app + slop ssh router -- uptime asks too, and approving needs a passkey (web app sign-in) slop ssh vault -- true denied by policy slop requests your pending requests and leases slop guide the guide agents get @@ -49,7 +49,7 @@ let asks to use the builder, builds, then asks to push Approve on the host: `slop-approve` in the devenv shell, or the web app at - http://localhost:${toString settings.ports.web} (`demo-sign-in` prints a sign-in link). + http://localhost:${toString settings.ports.web}, which has no sign-in unless it's turned on. A request blocks until it's answered. To keep this shell, run it in the background with stdin closed (`slop ssh` forwards stdin): `slop ssh web -- uptime ${state}/pocket-id.env - fi + mkdir -p ${state}/box ${state}/web ${state}/builder ${run} # The box VM gets the broker's public key and its own host key through its shared directory [ -e ${state}/broker-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo -f ${state}/broker-key @@ -321,57 +304,16 @@ in ln -sf ${preReceive} ${repositories}/repo.git/hooks/pre-receive ''; }; - - # Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client - "slop-demo:pocket-id" = { - description = "Set up the demo's approver and OIDC client in Pocket ID"; - after = [ "devenv:processes:pocket-id" ]; - status = "test -s ${state}/oidc-secret"; - exec = '' - set -eu - umask 077 - ${pocketIdApi} - - user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id) - group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id) - api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null - - api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null - api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null - api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new - mv ${state}/oidc-secret.new ${state}/oidc-secret - ''; - }; }; processes = lib.mkIf (!config.devenv.isTesting) { - pocket-id = { - exec = '' - set -a - . ${state}/pocket-id.env - exec ${pkgs.pocket-id}/bin/pocket-id - ''; - cwd = "${state}/pocket-id"; - env = { - APP_URL = issuer; - HOST = "127.0.0.1"; - PORT = toString settings.ports.pocketId; - ANALYTICS_DISABLED = "true"; - }; - after = [ "slop-demo:keys" ]; - ready = { - http.get = { port = settings.ports.pocketId; path = "/.well-known/openid-configuration"; }; - period = 1; - }; - }; - slop-broker = { exec = '' sed -e "s/@group@/$(id -gn)/" -e "s/@dev@/$(cat ${state}/dev-age.pub)/" ${brokerConfig} > ${state}/broker.toml exec cargo run -q --bin slop-broker -- serve --config ${state}/broker.toml ''; cwd = config.devenv.root; - after = [ "slop-demo:pocket-id" "slop-demo:repo" ]; + after = [ "slop-demo:repo" ] ++ lib.optional config.slopDemo.signIn "slop-demo:pocket-id"; ready = { exec = "test -S ${run}/approve.sock"; period = 1; diff --git a/nix/demo/sign-in.nix b/nix/demo/sign-in.nix new file mode 100644 index 0000000..d05ae47 --- /dev/null +++ b/nix/demo/sign-in.nix @@ -0,0 +1,90 @@ +# Sign-in for the demo's web app, with Pocket ID, a devenv module that `host.nix` imports. Without +# it the web app has no sign-in. Turn it on with `slopDemo.signIn = true;` in `devenv.local.nix` +# to try signing in and passkeys, which approving `router` needs. +{ pkgs, lib, config, ... }: +let + settings = import ./settings.nix; + state = "${config.devenv.state}/slop-demo"; + issuer = "http://localhost:${toString settings.ports.pocketId}"; + appUrl = "http://localhost:${toString settings.ports.web}"; + + # Pocket ID's admin API, with the key `devenv up` made + pocketIdApi = '' + api() { + local method=$1 path=$2 + shift 2 + curl -sS --fail-with-body -X "$method" "${issuer}/api/$path" \ + -H "X-API-Key: $(sed -n 's/^STATIC_API_KEY=//p' ${state}/pocket-id.env)" -H 'Content-Type: application/json' "$@" + } + ''; +in +{ + options.slopDemo.signIn = lib.mkEnableOption "sign-in to the demo's web app, with Pocket ID"; + + config = lib.mkIf (config.slopDemo.signIn && !config.devenv.isTesting) { + scripts.demo-sign-in = { + description = "Print a one-time link that signs in to the demo's Pocket ID as the approver"; + exec = '' + ${pocketIdApi} + user=$(api GET 'users?search=demo' | jq -r '.data[] | select(.username == "demo") | .id') + echo "${issuer}/lc/$(api POST "users/$user/one-time-access-token" -d '{"ttl":"1h"}' | jq -r .token)" + ''; + }; + + tasks = { + "slop-demo:pocket-id-keys" = { + description = "Make Pocket ID's keys for the demo"; + exec = '' + set -eu + umask 077 + mkdir -p ${state}/pocket-id + if [ ! -e ${state}/pocket-id.env ]; then + key() { ${pkgs.openssl}/bin/openssl rand -hex 32; } + printf 'ENCRYPTION_KEY=%s\nSTATIC_API_KEY=%s\n' "$(key)" "$(key)" > ${state}/pocket-id.env + fi + ''; + }; + + # Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client + "slop-demo:pocket-id" = { + description = "Set up the demo's approver and OIDC client in Pocket ID"; + after = [ "devenv:processes:pocket-id" ]; + status = "test -s ${state}/oidc-secret"; + exec = '' + set -eu + umask 077 + ${pocketIdApi} + + user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id) + group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id) + api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null + + api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null + api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null + api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new + mv ${state}/oidc-secret.new ${state}/oidc-secret + ''; + }; + }; + + processes.pocket-id = { + exec = '' + set -a + . ${state}/pocket-id.env + exec ${pkgs.pocket-id}/bin/pocket-id + ''; + cwd = "${state}/pocket-id"; + env = { + APP_URL = issuer; + HOST = "127.0.0.1"; + PORT = toString settings.ports.pocketId; + ANALYTICS_DISABLED = "true"; + }; + after = [ "slop-demo:pocket-id-keys" ]; + ready = { + http.get = { port = settings.ports.pocketId; path = "/.well-known/openid-configuration"; }; + period = 1; + }; + }; + }; +} -- 2.56.0