From 9933f55242c14f2ddf93317fcfee1a9c133726d6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:48:43 +0100 Subject: [PATCH] [control] Mark's UI decisions: Remote-Name shown with the proof, [ui] logout_url for Sign out, openssl signing files for the manual intermediate step, engine.not_ready, server sentences for the eight generic codes --- crates/control/src/api/handlers.rs | 3 +- crates/control/src/api/mod.rs | 19 ++++-- crates/control/src/api/pki.rs | 50 ++++++++++++++-- crates/control/src/api/views.rs | 2 + crates/control/src/config.rs | 3 + crates/control/src/dev.rs | 1 + crates/control/src/messages.rs | 26 +++++++++ crates/control/src/switch.rs | 10 ++++ crates/control/tests/pki.rs | 93 +++++++++++++++++++++++++++++- crates/core/src/pki.rs | 16 +++++ docs/ui-decisions.md | 15 +++++ 11 files changed, 225 insertions(+), 13 deletions(-) create mode 100644 docs/ui-decisions.md diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index 3670e49..a20a772 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -184,6 +184,7 @@ pub async fn overview( secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(), watch_seconds: c.cfg.watch_secs, share_links_available: c.share_key.is_some() && c.engine_running() != "caddy", + auth_logout_url: c.cfg.ui.as_ref().and_then(|u| u.logout_url.clone()), }); let es = super::pki::engine_view(c); let on_caddy = es.running == "caddy"; @@ -1339,7 +1340,7 @@ impl Modify for Bearer { get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token, mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi, super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request, - super::pki::get_csr, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, + super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine ), components(schemas( diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index f61057b..c63c84f 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -352,7 +352,8 @@ enum UiIdentity { Forged, /// The right proof but no usable `Remote-User`. NoUser, - User(String), + /// The Authelia user name, and the name to show (`Remote-Name` when it is usable). + User(String, String), } fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { @@ -376,7 +377,16 @@ fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { && u.len() <= 64 && u.bytes().all(|c| c.is_ascii_graphic() && c != b':') => { - UiIdentity::User(u.to_owned()) + let display = headers + .get("remote-name") + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|n| { + !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control) + }) + .unwrap_or(u) + .to_owned(); + UiIdentity::User(u.to_owned(), display) } _ => UiIdentity::NoUser, }, @@ -434,7 +444,7 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> Params::new(), )); } - UiIdentity::User(user) => { + UiIdentity::User(user, display) => { // Cookie-based sign-in: every write carries the UI header, browser or not. if write && !ui { return Err(ApiError::new( @@ -450,7 +460,7 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> })?; req.extensions_mut().insert(Actor { token_id: format!("user:{user}"), - name: user, + name: display, }); return Ok(next.run(req).await); } @@ -601,6 +611,7 @@ pub fn router(st: Arc) -> Router { get(pki::get_request).delete(pki::cancel_request), ) .route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr)) + .route("/api/v1/pki-requests/{id}/ext", get(pki::get_ext)) .route( "/api/v1/pki-requests/{id}/certificate", axum::routing::put(pki::put_certificate), diff --git a/crates/control/src/api/pki.rs b/crates/control/src/api/pki.rs index c9297d4..be44cc5 100644 --- a/crates/control/src/api/pki.rs +++ b/crates/control/src/api/pki.rs @@ -86,6 +86,8 @@ pub struct PkiRequestView { pub message: String, /// The command that approves it on the server (manual approval). pub approve_command: Option, + /// Renewals: the base name of the files (`.csr`, `.ext`, `.crt`). + pub file_base: Option, /// Why it failed, when it did. pub problem: Option, } @@ -141,15 +143,24 @@ pub fn request_view(c: &Control, r: &Request) -> PkiRequestView { message: message_text, approve_command: (r.state == "waiting" && manual).then(|| { if r.kind == "intermediate" { - "ianitor-control ca sign --root --csr request.csr --out intermediate.crt; then ianitor-control pki install intermediate.crt".to_owned() + ianitor_core::pki::openssl_sign_command(&file_base(r)) } else { format!("ianitor-control pki approve {}", r.match_code) } }), + file_base: (r.kind == "intermediate").then(|| file_base(r)), problem: r.error.clone(), } } +/// `domi-intermediate-2026-11-07`, from the day the request was made. +pub fn file_base(r: &Request) -> String { + format!( + "domi-intermediate-{}", + rfc3339(r.created_at).get(..10).unwrap_or("request") + ) +} + #[derive(Debug, Clone, Serialize, ToSchema)] pub struct IntermediateView { /// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`. @@ -384,19 +395,19 @@ pub async fn get_csr(State(st): Shared, Path(id): Path) -> Result) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let r = blocking(&st, move |c| { + pki(c)? + .request(&id, now())? + .filter(|r| r.kind == "intermediate") + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response(); + resp.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r))) + { + resp.headers_mut().insert(header::CONTENT_DISPOSITION, v); + } + Ok(resp) +} diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs index ca35911..41c902c 100644 --- a/crates/control/src/api/views.rs +++ b/crates/control/src/api/views.rs @@ -513,6 +513,8 @@ pub struct SiteView { pub secrets: Vec, pub watch_seconds: u64, pub share_links_available: bool, + /// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link. + pub auth_logout_url: Option, } #[derive(Debug, Clone, Serialize, ToSchema)] diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index 59a8df2..2976046 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -321,6 +321,9 @@ pub struct UiConfig { pub proof_credential: Option, /// The built web UI (served at `/`). pub static_dir: Option, + /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". + #[serde(default)] + pub logout_url: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 921bda0..29d191b 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -160,6 +160,7 @@ pub async fn run(args: &[String]) -> Result<(), String> { hostname: None, proof_credential: None, static_dir: Some(PathBuf::from(d)), + logout_url: None, }), engine: None, }; diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index ee9ba0e..020cbea 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -306,6 +306,32 @@ fn template(code: &str) -> &'static str { "engine.switch_failed" => { "{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before." } + "engine.not_ready" => { + "Caddy is not ready: its settings could not be built from the current routes." + } + // The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12). + "repo.duplicate_file" => { + "Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up." + } + "file.syntax" => { + "{file} in the routes repository has a typing mistake. Changes are paused until it is fixed." + } + "file.too_large" => { + "{file} in the routes repository is too large to read. Changes are paused until it is fixed." + } + "site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".", + "site.forward_auth" => { + "The sign-in settings in ianitor.toml cannot be used. Show details to see why." + } + "site.forward_auth.header" => { + "ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name." + } + "site.secret.name" => { + "\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores." + } + "site.acme" => { + "The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why." + } "engine.caddy" => "Caddy is serving. Changes wait until you switch back to Pingora.", "share.engine_caddy" => { "Share links are paused while Caddy serves. They work again after switching back." diff --git a/crates/control/src/switch.rs b/crates/control/src/switch.rs index b7311f6..8e5ff58 100644 --- a/crates/control/src/switch.rs +++ b/crates/control/src/switch.rs @@ -201,6 +201,9 @@ impl Control { if self.engine_cfg().is_none() || self.units.is_none() { return Err(Fail::new(409, "engine.unmanaged", Params::new())); } + if target == "caddy" && !self.fallback_buildable() { + return Err(Fail::new(409, "engine.not_ready", Params::new())); + } if target != "pingora" && target != "caddy" { return Err(Fail::new( 422, @@ -385,6 +388,13 @@ impl Control { Ok(()) } + /// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.) + pub fn fallback_buildable(&self) -> bool { + self.head_model().ok().is_some_and(|(_, _, m)| { + ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_ok() + }) + } + /// Any reason changes wait now: Caddy serving, or a pause. pub fn effective_pause(&self) -> Option { self.engine_pause().or_else(|| self.paused()) diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs index b54d2d4..d1eee6b 100644 --- a/crates/control/tests/pki.rs +++ b/crates/control/tests/pki.rs @@ -50,6 +50,11 @@ mod unix { async fn env_with_pki() -> (Env, Offline) { let (root_pem, root_key) = pki::create_root(now()).unwrap(); + let env = env_with_root(&root_pem).await; + (env, Offline { root_pem, root_key }) + } + + async fn env_with_root(root_pem: &str) -> Env { // Only the root certificate goes next to control; the key stays in this test. let extra = |dir: &Path| { format!( @@ -58,12 +63,12 @@ mod unix { ) }; let mut env = Env::new(EnvSpec::default()).await; - std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap(); + std::fs::write(env.dir.join("offline-root.crt"), root_pem).unwrap(); std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap(); let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join(".")); std::fs::write(env.config_path(), text).unwrap(); env.start_control(None); - (env, Offline { root_pem, root_key }) + env } async fn wait_request(env: &Env, id: &str, want: &str) -> Value { @@ -406,6 +411,90 @@ mod unix { assert!(!err.contains("PRIVATE KEY"), "{err}"); } + /// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl. + /// A root made with openssl signs control's CSR with the extensions file control serves, + /// and control installs the result. + #[tokio::test(flavor = "multi_thread")] + async fn an_intermediate_signed_with_openssl_is_installed() { + let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else { + return; + }; + let off = ianitor_testkit::proc::TempDir::new("openssl-root"); + let run = |args: &[&str]| { + let o = std::process::Command::new(&openssl) + .args(args) + .current_dir(off.join(".")) + .output() + .unwrap(); + assert!( + o.status.success(), + "openssl {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + run(&[ + "req", + "-x509", + "-new", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:P-256", + "-nodes", + "-keyout", + "domi-root.key", + "-out", + "domi-root.crt", + "-days", + "3653", + "-subj", + "/CN=Domi PKI Root/O=Fabrica Domi", + "-addext", + "basicConstraints=critical,CA:TRUE,pathlen:1", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + ]); + let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap(); + let env = env_with_root(&root_pem).await; + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let base = r.json["file_base"].as_str().unwrap().to_owned(); + let cmd = r.json["approve_command"].as_str().unwrap().to_owned(); + assert!(cmd.starts_with("openssl x509 -req"), "{cmd}"); + std::fs::write( + off.join(&format!("{base}.csr")), + r.json["csr_pem"].as_str().unwrap(), + ) + .unwrap(); + let ext = env + .call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None) + .await; + assert_eq!(ext.status, 200, "{}", ext.text); + std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap(); + // Exactly the command control shows. + let args: Vec<&str> = cmd.split_whitespace().skip(1).collect(); + run(&args); + let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap(); + let info = pki::inspect(&signed).unwrap(); + assert_eq!(info.path_len, Some(0)); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": signed})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["state"], "approved"); + } + fn walk(dir: &Path) -> Vec { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs index e7ff8d8..1e2b34e 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -203,6 +203,22 @@ pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result { .map_err(build) } +/// The extensions for signing an intermediate with openssl on the offline machine (the +/// accepted manual step until Custos can sign, docs/pki.md): the same profile as +/// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile `. +pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\ +keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\ +subjectKeyIdentifier = hash\n\ +authorityKeyIdentifier = keyid:always\n"; + +/// The openssl command that signs a renewal on the offline machine (files named after the +/// request). OpenSSL 3 picks a random serial. +pub fn openssl_sign_command(base: &str) -> String { + format!( + "openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt" + ) +} + /// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's /// public key and CN are used; the CN must start with [`INTERMEDIATE_CN`]. pub fn sign_intermediate( diff --git a/docs/ui-decisions.md b/docs/ui-decisions.md new file mode 100644 index 0000000..44c6226 --- /dev/null +++ b/docs/ui-decisions.md @@ -0,0 +1,15 @@ +# Mark's answers to open-questions.md (2026-11-07) + +- Q1 Share link on a host with links off: **keep the 4-click path** (button "Turn on share links", Copy appears when the apply is kept). No `turn_on` API change. Record it in ROADMAP §4 as an accepted 4th click. +- Q2 UI auth (G14): **(a) secret header from edge** on the admin host, from a systemd credential; control requires it, then trusts Remote-User/Remote-Name from Authelia. Keep X-Ianitor-UI against CSRF. Add `site.auth_logout_url` for "Sign out". Unix socket (b) is Phase 4 hardening. +- Q3 Engine switch: **allow with differences listed** under "Show details"; refuse only `engine.not_ready`. Switch waits in the same queue as applies. +- Q4 Share links under Caddy: **off for v1**, said plainly in the engine popover, the share dialog and Settings. Validator Caddy calls via forward_auth before v1.1 (note in ROADMAP). +- Q5 Device certificates without Custos: **server-command fallback** `sudo ianitor-control pki approve `, match code shown in the UI. +- Q6 Manual intermediate signing: **accepted as a §4 exception** while Custos lacks the operation; the offline machine runs openssl. +- Q7 Device certificate lifetime: **1 year**, "renew soon" 30 days before, never past the intermediate's end date. +- Q8 Inline confirmation on "Stop all share links" and on "Revoke" token: **yes**. +- Q9 Stop polling after 15 min in a hidden tab: **yes**. +- Q10 "New tokens expire after: 1 year | Never" choice, default 1 year: **yes**. +- Q11 "Open to anyone" chip on auth = none hosts: **yes**. +- Q12 Add the handoff's sentences for the 8 generic codes to control's messages.rs: yes (orchestrator default; no owner decision needed). +- Q13 Self-host the fonts in packages/ui: yes (orchestrator default; the UI makes no outside requests).