From 7cb5715580336b420b4e5e7117cc25a00759caf9 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:40:38 +0100 Subject: [PATCH 01/34] [docs] Custos ticket: the CSR-signing operation with match-code approval that Custos does not have yet --- docs/custos-ticket.md | 94 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/custos-ticket.md diff --git a/docs/custos-ticket.md b/docs/custos-ticket.md new file mode 100644 index 0000000..0afeb54 --- /dev/null +++ b/docs/custos-ticket.md @@ -0,0 +1,94 @@ +# Custos ticket: sign an X.509 CSR with the Domi PKI root after a match-code approval + +Status: **written, not filed** (ROADMAP §6 Phase 3, §8.6). Ianitor uses the manual offline +step in [pki.md](pki.md) until this exists. + +## Why + +ROADMAP §1.2: the Domi PKI root key lives offline in Custos; the intermediate on the +server is renewed yearly "through a Custos match-code approval". Custos (desktop 0.8.0, +CustosPublic v0.13.0) has no such operation today: + +- The `sign` op (docs/09_signing.md) signs only `minisign`, `manifest`, `authenticode` and + `approval` payloads. A sign request against `domi-root` is refused on purpose + (apps/desktop/src-tauri/src/signing.rs, test at line 595). +- `domi-root` is the RSA-3072 Household Root for Authenticode. Issuing TLS intermediates + from it would mix code signing and TLS trust; the Domi PKI needs its own root. +- The only server-reachable path is the factor-service sign mailbox + (`POST /api/sign/requests`, `GET /api/sign/requests/{id}`, docs/09_signing.md:42-51), + which carries the existing kinds only. + +## What Ianitor needs + +### 1. A new key: `domi-pki-root` + +- ECDSA P-256 (what rcgen and every TLS client support; no RSA keygen in ring). +- Self-signed CA certificate, about 10 years, `basicConstraints CA:TRUE, pathLenConstraint 1`, + key usage `keyCertSign, cRLSign`, subject `CN=Domi PKI Root, O=Fabrica Domi`. +- Created in Custos, or **imported once** from the file Ianitor's offline CLI made + (`ianitor-control ca init`, see pki.md), after which that file is destroyed. +- Like the other signing keys: in the vault body member `signing`, never an item, never + revealed, copied, shared or exported. The public certificate is readable through the + existing `certificate` op (`custos-provision pub domi-pki-root`). + +### 2. A new sign kind: `x509_csr` + +Request through the existing sign mailbox (same token, same sealing to a one-time X25519 +key, same audit entry): + +```json +{ "op": "sign", "namespace": "domi", "key": "domi-pki-root", "kind": "x509_csr", + "csr": "", + "profile": "intermediate", + "pub": "", + "context": { "service": "ianitor", "host": "", "request_id": "", + "csr_sha256": "" } } +``` + +Answer (sealed, handed out once): `{ "ok": true, "certificate": "", "sha256": "" }` +or `{ "ok": false, "error": "refused | expired | out_of_scope | invalid | no_key | denied | locked" }`. + +Custos must **not** copy the CSR's extensions. It builds the certificate itself from the +`intermediate` profile and takes only the subject public key and the subject CN from the CSR: + +| Field | Value | +|:--|:--| +| Subject | `CN=`; refused unless the CN starts with `Ianitor Domi Intermediate` | +| Validity | now − 5 min to now + 365 days, never past the root's notAfter | +| basicConstraints | critical, `CA:TRUE, pathLenConstraint 0` | +| keyUsage | critical, `keyCertSign, cRLSign, digitalSignature` | +| Serial | 16 random bytes | +| Signature | ECDSA P-256 / SHA-256 | + +It verifies the CSR's own signature (proof of possession) and refuses anything else +(`invalid`). + +### 3. The approval card + +Same flow as release signing (docs/12_hands_off.md §7): a card on the PC, a push to paired +phones, approve with Face ID; 10 minutes, then `expired`. The card shows: + +- "Ianitor on asks for a new Domi intermediate certificate, valid until ." +- The **match code**: Ianitor's own code, so Mark compares one number on two screens. It is + computed on both sides from the CSR, not from the one-time key: + `SHA-256(CSR DER)`, first 3 bytes, each byte mod 100, as three two-digit groups (`47 19 83`). + Ianitor shows it in the UI banner; Custos shows it on the card. (Custos's usual + `match_code(pub)` would also work if Ianitor showed that one instead; either is fine, + but it must be one code, the same on both screens.) +- Test keys may auto-approve as today; `domi-pki-root` always asks. + +### 4. Optional, later: device certificates + +ROADMAP §4 also says "Device cert: … Issue (approve in Custos)". The device certificate is +signed on the server with the intermediate, so Custos only has to approve, not sign: +a kind `approval` request with `context.kind = "domi_device_cert"`, `name`, `match_code`, +answered with the existing signed approval JSON (`domi-approve`), which Ianitor verifies +against the `domi-approve` public key before issuing. No new crypto in Custos. + +## Done when + +- `custos-sign csr --key domi-pki-root --profile intermediate --csr req.pem` (and the + mailbox equivalent) returns a certificate that `openssl verify -CAfile root.pem` accepts, + with `pathlen:0`, after a match-code approval on the phone. +- A CSR with another CN, a bad signature or a request for a CA without pathLen 0 is refused. +- An `x509_csr` request against any other key is `out_of_scope`. -- 2.53.0 From cde0c3ea3b7e750be9a39f476a1cd2a8b7ceb337 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:40:56 +0100 Subject: [PATCH 02/34] [core] Tests first: the Domi CA chains to the root, a leaf cannot sign, expired and wrong-name certs are rejected (red) --- Cargo.lock | 5 + crates/core/Cargo.toml | 7 + crates/core/src/lib.rs | 1 + crates/core/src/pki.rs | 75 +++++++++ crates/core/tests/pki.rs | 317 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 405 insertions(+) create mode 100644 crates/core/src/pki.rs create mode 100644 crates/core/tests/pki.rs diff --git a/Cargo.lock b/Cargo.lock index 76ea7d2..a037d97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1080,13 +1080,18 @@ name = "ianitor-core" version = "0.1.0" dependencies = [ "base64 0.22.1", + "rcgen", "ring", + "rustls-pki-types", + "rustls-webpki", "serde", "serde_json", "thiserror 2.0.21", + "time", "toml", "unicode-normalization", "url", + "x509-parser 0.18.1", ] [[package]] diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 4c526bc..ff25605 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -16,6 +16,13 @@ url.workspace = true ring.workspace = true base64.workspace = true unicode-normalization = "0.1.24" +rcgen = { workspace = true, features = ["x509-parser"] } +x509-parser = { version = "0.18", features = ["verify"] } +time = { version = "0.3", default-features = false } + +[dev-dependencies] +rustls-pki-types.workspace = true +webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "std"] } [lints] workspace = true diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c3536b0..743c483 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,6 +10,7 @@ pub mod compile; pub mod edge_config; +pub mod pki; mod error; mod model; pub mod routes; diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs new file mode 100644 index 0000000..7b85f42 --- /dev/null +++ b/crates/core/src/pki.rs @@ -0,0 +1,75 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA. Interface only; the implementation follows the tests (red commit). + +pub const ROOT_DAYS: u32 = 3653; +pub const INTERMEDIATE_DAYS: u32 = 365; +pub const SERVER_DAYS: u32 = 90; +pub const SERVER_RENEW_DAYS: u32 = 30; +pub const DEVICE_DAYS: u32 = 365; +pub const ROOT_CN: &str = "Domi PKI Root"; +pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; +pub const KEY_KDF_ITERATIONS: u32 = 0; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PkiError { + #[error("not built yet")] + NotBuilt, + #[error("bad certificate")] + BadCertificate(String), + #[error("bad csr")] + BadCsr, + #[error("csr subject")] + CsrSubject, + #[error("bad key")] + BadKey, + #[error("not a ca")] + NotCa, + #[error("key mismatch")] + KeyMismatch, + #[error("issuer expired")] + IssuerExpired, + #[error("wrong password")] + WrongPassword, +} + +#[derive(Debug)] +pub struct KeyPair; +impl KeyPair { + pub fn serialize_pem(&self) -> String { String::new() } + pub fn from_pem(_: &str) -> Result { Err(PkiError::NotBuilt) } + pub fn public_key_der(&self) -> Vec { Vec::new() } +} +pub fn generate_key() -> Result { Err(PkiError::NotBuilt) } +pub fn create_root(_: i64) -> Result<(String, KeyPair), PkiError> { Err(PkiError::NotBuilt) } +pub fn intermediate_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn sign_intermediate(_: &str, _: &KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +#[derive(Debug)] +pub struct Intermediate; +impl Intermediate { + pub fn new(_: &str, _: KeyPair) -> Result { Err(PkiError::NotBuilt) } + pub fn cert_pem(&self) -> &str { "" } + pub fn not_after(&self) -> i64 { 0 } +} +#[derive(Debug)] +pub struct Issued { pub cert_pem: String, pub chain_pem: String, pub key_pem: String } +pub fn issue_server(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +pub fn issue_device(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +#[derive(Debug)] +pub struct CertInfo { pub subject_cn: String, pub not_after: i64, pub is_ca: bool, pub path_len: Option, pub dns_names: Vec } +pub fn inspect(_: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn public_key_der(_: &str) -> Result, PkiError> { Err(PkiError::NotBuilt) } +pub fn issued_by(_: &str, _: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn match_code(_: &[u8]) -> String { String::new() } +pub fn encrypt_key_with(_: &KeyPair, _: &[u8], _: u32) -> Result { Err(PkiError::NotBuilt) } +pub fn decrypt_key(_: &str, _: &[u8]) -> Result { Err(PkiError::NotBuilt) } +#[doc(hidden)] +pub mod testing { + use super::*; + pub fn sign_as(_: &str, _: KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } + pub fn sub_ca(_: &Intermediate, _: &KeyPair, _: i64) -> Result { Err(PkiError::NotBuilt) } + pub fn greedy_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } + pub fn tamper_csr(s: &str) -> String { s.to_owned() } +} diff --git a/crates/core/tests/pki.rs b/crates/core/tests/pki.rs new file mode 100644 index 0000000..df4baf0 --- /dev/null +++ b/crates/core/tests/pki.rs @@ -0,0 +1,317 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA (ROADMAP §6 phase 3, tests first): issued chains validate to the root, a leaf +//! cannot sign, expired and wrong-name certificates are rejected, an intermediate is never +//! made from a CSR's own wishes, and encrypted keys need their password. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::pki::{ + self, DEVICE_DAYS, INTERMEDIATE_DAYS, Intermediate, PkiError, ROOT_DAYS, SERVER_DAYS, +}; +use rustls_pki_types::{CertificateDer, ServerName, UnixTime}; +use webpki::{EndEntityCert, KeyUsage, anchor_from_trusted_cert}; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 86_400; + +fn der(pem: &str) -> CertificateDer<'static> { + use rustls_pki_types::pem::PemObject; + CertificateDer::pem_slice_iter(pem.as_bytes()) + .next() + .unwrap() + .unwrap() +} + +fn all_der(pem: &str) -> Vec> { + use rustls_pki_types::pem::PemObject; + CertificateDer::pem_slice_iter(pem.as_bytes()) + .collect::>() + .unwrap() +} + +fn at(t: i64) -> UnixTime { + UnixTime::since_unix_epoch(std::time::Duration::from_secs(t as u64)) +} + +struct Ca { + root_pem: String, + root_key: pki::KeyPair, + int: Intermediate, +} + +fn ca() -> Ca { + let (root_pem, root_key) = pki::create_root(NOW).unwrap(); + let int_key = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&int_key, pki::INTERMEDIATE_CN).unwrap(); + let int_pem = pki::sign_intermediate(&root_pem, &root_key, &csr, NOW).unwrap(); + let int = Intermediate::new(&int_pem, int_key).unwrap(); + Ca { + root_pem, + root_key, + int, + } +} + +/// Verify `leaf_chain` (leaf first, then intermediates) against `root` at time `t`. +fn verify( + root_pem: &str, + leaf_chain: &str, + t: i64, + usage: KeyUsage, +) -> Result<(), webpki::Error> { + let root = der(root_pem); + let anchor = anchor_from_trusted_cert(&root).unwrap().to_owned(); + let chain = all_der(leaf_chain); + let ee = EndEntityCert::try_from(&chain[0]).unwrap(); + ee.verify_for_usage( + webpki::ALL_VERIFICATION_ALGS, + &[anchor], + &chain[1..], + at(t), + usage, + None, + None, + ) + .map(|_| ()) +} + +#[test] +fn root_is_a_ten_year_ca_with_path_length_one() { + let (root_pem, _) = pki::create_root(NOW).unwrap(); + let info = pki::inspect(&root_pem).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(1)); + assert!(info.path_len.unwrap() >= 1, "ROADMAP §3: pathLenConstraint >= 1"); + assert_eq!(info.subject_cn, pki::ROOT_CN); + let days = (info.not_after - NOW) / DAY; + assert!((ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), "{days}"); + assert!(days >= 3650); +} + +#[test] +fn intermediate_is_one_year_path_length_zero_and_signed_by_the_root() { + let c = ca(); + let info = pki::inspect(c.int.cert_pem()).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(0)); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + assert!(pki::issued_by(c.int.cert_pem(), &c.root_pem).unwrap()); + assert!(!pki::issued_by(&c.root_pem, c.int.cert_pem()).unwrap()); +} + +#[test] +fn server_chain_validates_to_the_root() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap(); + let info = pki::inspect(&leaf.cert_pem).unwrap(); + assert!(!info.is_ca); + assert_eq!(info.dns_names, vec!["wiki.home.test".to_owned()]); + assert_eq!((info.not_after - NOW) / DAY, SERVER_DAYS as i64); + // The key belongs to the certificate. + let k = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + assert_eq!(pki::public_key_der(&leaf.cert_pem).unwrap(), k.public_key_der()); +} + +#[test] +fn device_chain_validates_for_client_auth_only() { + let c = ca(); + let dev = pki::issue_device(&c.int, "Mark's phone", NOW).unwrap(); + verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::client_auth()).unwrap(); + assert!( + verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::server_auth()).is_err(), + "a device certificate cannot serve a site" + ); + let info = pki::inspect(&dev.cert_pem).unwrap(); + assert_eq!(info.subject_cn, "Mark's phone"); + assert_eq!((info.not_after - NOW) / DAY, DEVICE_DAYS as i64); +} + +#[test] +fn a_leaf_cannot_sign() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + // Ianitor refuses to use a leaf as an issuer. + assert!(matches!( + Intermediate::new(&leaf.cert_pem, leaf_key), + Err(PkiError::NotCa) + )); + // And a certificate forged with the leaf key as issuer does not validate. + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + let forged = pki::testing::sign_as(&leaf.cert_pem, leaf_key, "evil.home.test", NOW).unwrap(); + let chain = format!("{forged}{}", leaf.chain_pem); + let e = verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).unwrap_err(); + assert!( + matches!( + e, + webpki::Error::EndEntityUsedAsCa + | webpki::Error::CaUsedAsEndEntity + | webpki::Error::UnknownIssuer + ), + "{e:?}" + ); +} + +#[test] +fn intermediate_cannot_make_another_ca() { + // pathLen 0: a CA below the intermediate is not trusted. + let c = ca(); + let sub_key = pki::generate_key().unwrap(); + let sub = pki::testing::sub_ca(&c.int, &sub_key, NOW).unwrap(); + let leaf = pki::testing::sign_as(&sub, sub_key, "deep.home.test", NOW).unwrap(); + let chain = format!("{leaf}{sub}{}", c.int.cert_pem()); + assert!(verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).is_err()); +} + +#[test] +fn expired_certificates_are_rejected() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let after = NOW + (SERVER_DAYS as i64 + 1) * DAY; + assert!(matches!( + verify(&c.root_pem, &leaf.chain_pem, after, KeyUsage::server_auth()), + Err(webpki::Error::CertExpired { .. }) + )); + let before = NOW - DAY; + assert!(verify(&c.root_pem, &leaf.chain_pem, before, KeyUsage::server_auth()).is_err()); +} + +#[test] +fn wrong_name_is_rejected() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let ee_der = der(&leaf.cert_pem); + let ee = EndEntityCert::try_from(&ee_der).unwrap(); + ee.verify_is_valid_for_subject_name(&ServerName::try_from("wiki.home.test").unwrap()) + .unwrap(); + assert!( + ee.verify_is_valid_for_subject_name(&ServerName::try_from("photos.home.test").unwrap()) + .is_err() + ); + assert!( + ee.verify_is_valid_for_subject_name(&ServerName::try_from("home.test").unwrap()) + .is_err() + ); +} + +#[test] +fn a_certificate_from_another_root_is_rejected() { + let c = ca(); + let other = ca(); + let leaf = pki::issue_server(&other.int, "wiki.home.test", NOW).unwrap(); + // Both CAs have the same names, so webpki finds the issuer by name and then the + // signature check fails. + let e = verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap_err(); + assert!( + matches!( + e, + webpki::Error::UnknownIssuer + | webpki::Error::InvalidSignatureForPublicKey + ), + "{e:?}" + ); +} + +#[test] +fn leaves_never_outlive_the_intermediate() { + let c = ca(); + let late = NOW + (INTERMEDIATE_DAYS as i64 - 10) * DAY; + let leaf = pki::issue_device(&c.int, "tablet", late).unwrap(); + let info = pki::inspect(&leaf.cert_pem).unwrap(); + assert!(info.not_after <= c.int.not_after()); + // An expired intermediate issues nothing. + let gone = NOW + (INTERMEDIATE_DAYS as i64 + 1) * DAY; + assert!(matches!( + pki::issue_server(&c.int, "wiki.home.test", gone), + Err(PkiError::IssuerExpired) + )); +} + +#[test] +fn the_intermediate_ignores_what_the_csr_asks_for() { + let (root_pem, root_key) = pki::create_root(NOW).unwrap(); + let key = pki::generate_key().unwrap(); + // A CSR asking to be a CA with no path limit, for 50 years, for a web name. + let greedy = pki::testing::greedy_csr(&key, pki::INTERMEDIATE_CN).unwrap(); + let pem = pki::sign_intermediate(&root_pem, &root_key, &greedy, NOW).unwrap(); + let info = pki::inspect(&pem).unwrap(); + assert_eq!(info.path_len, Some(0)); + assert!(info.dns_names.is_empty()); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + // The wrong subject is refused. + let wrong = pki::intermediate_csr(&key, "Some Other CA").unwrap(); + assert!(matches!( + pki::sign_intermediate(&root_pem, &root_key, &wrong, NOW), + Err(PkiError::CsrSubject) + )); + // A tampered CSR (signature does not match) is refused. + let csr = pki::intermediate_csr(&key, pki::INTERMEDIATE_CN).unwrap(); + let tampered = pki::testing::tamper_csr(&csr); + assert!(pki::sign_intermediate(&root_pem, &root_key, &tampered, NOW).is_err()); + // Garbage is refused, never a panic. + assert!(pki::sign_intermediate(&root_pem, &root_key, "not a csr", NOW).is_err()); +} + +#[test] +fn intermediate_must_match_its_key_and_be_a_ca() { + let c = ca(); + let other_key = pki::generate_key().unwrap(); + assert!(matches!( + Intermediate::new(c.int.cert_pem(), other_key), + Err(PkiError::KeyMismatch) + )); + let _ = c.root_key; +} + +#[test] +fn match_code_is_three_two_digit_groups_and_stable() { + let a = pki::match_code(b"some csr"); + assert_eq!(a, pki::match_code(b"some csr")); + assert_ne!(a, pki::match_code(b"other csr")); + let parts: Vec<&str> = a.split(' ').collect(); + assert_eq!(parts.len(), 3); + assert!(parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))); +} + +#[test] +fn encrypted_key_needs_its_password() { + let key = pki::generate_key().unwrap(); + let sealed = pki::encrypt_key_with(&key, b"correct horse battery", 1000).unwrap(); + // Armoured so that the pre-commit hook would block it like any private key. + // (Split so that this file does not match the hook itself.) + assert!(sealed.starts_with(concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----\n"))); + // The plain key is not inside. + assert!(!sealed.contains(&key.serialize_pem())); + let back = pki::decrypt_key(&sealed, b"correct horse battery").unwrap(); + assert_eq!(back.public_key_der(), key.public_key_der()); + assert!(matches!( + pki::decrypt_key(&sealed, b"wrong"), + Err(PkiError::WrongPassword) + )); + // A changed byte is caught. + let mut bad = sealed.clone().into_bytes(); + let i = bad.len() / 2; + bad[i] = if bad[i] == b'A' { b'B' } else { b'A' }; + assert!(pki::decrypt_key(&String::from_utf8(bad).unwrap(), b"correct horse battery").is_err()); + assert!(pki::decrypt_key("garbage", b"x").is_err()); + // Default strength. + assert!(pki::KEY_KDF_ITERATIONS >= 600_000); +} + +#[test] +fn hostile_pem_input_is_an_error_not_a_panic() { + for bad in [ + "", + "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", + "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n", + "\u{0}\u{1}", + ] { + assert!(pki::inspect(bad).is_err()); + assert!(pki::issued_by(bad, bad).is_err()); + assert!(pki::public_key_der(bad).is_err()); + } +} -- 2.53.0 From dc23bfe842a7033f86480f96d81ed3ed87a9ec50 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:41:29 +0100 Subject: [PATCH 03/34] [core] Domi CA: offline root (10 y, pathLen 1), intermediate from a CSR (1 y, pathLen 0), server (90 d) and device (1 y) leaves, encrypted keys, match codes --- crates/core/src/lib.rs | 2 +- crates/core/src/pki.rs | 743 ++++++++++++++++++++++++++++++++++++--- crates/core/tests/pki.rs | 80 ++++- 3 files changed, 763 insertions(+), 62 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 743c483..3d96ada 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,9 +10,9 @@ pub mod compile; pub mod edge_config; -pub mod pki; mod error; mod model; +pub mod pki; pub mod routes; pub mod share; pub mod time; diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs index 7b85f42..f9f04e1 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -2,74 +2,733 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -//! The Domi CA. Interface only; the implementation follows the tests (red commit). +//! The Domi CA (ROADMAP §1.1, §1.2, §1.8, §3): a small CA on rcgen. Pure: the caller passes +//! the time in and does every file read and write. Keys are ECDSA P-256 everywhere. +//! +//! ```text +//! Domi PKI Root 10 years, pathLen 1 created offline, never on the server +//! └ Ianitor Domi Intermediate 1 year, pathLen 0 key encrypted at rest on the server +//! ├ 90 days, serverAuth tls = "domi" hosts +//! └ 1 year, clientAuth mTLS for hosts with device_certs +//! ``` +//! +//! Lifetimes (decided in phase 3): +//! - Server certificates: 90 days, renewed by control when 30 days are left. Control renews +//! them by itself, so a short life costs nothing and bounds the damage of a key read from the +//! certificate directory; 30 days of slack survive a long control outage. +//! - Device certificates: 1 year. Installing one is a deliberate, manual step on a phone or a +//! laptop (ROADMAP §4 accepts a 4th click for it), so it should not come round more than +//! once a year; revocation (the allow list edge and Caddy check) covers a lost device. +//! - No certificate is ever issued past its issuer's `notAfter`. +//! +//! The intermediate is never made from what a CSR asks for: only its public key and its +//! subject CN are taken; every extension comes from the profile here. +use std::fmt; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; +use rcgen::{ + BasicConstraints, CertificateParams, CertificateSigningRequestParams, DistinguishedName, + DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256, + SerialNumber, +}; +use ring::rand::{SecureRandom, SystemRandom}; +use time::OffsetDateTime; + +/// Root: about 10 years. pub const ROOT_DAYS: u32 = 3653; +/// Intermediate: about 1 year. pub const INTERMEDIATE_DAYS: u32 = 365; +/// Server (tls = "domi") certificates. pub const SERVER_DAYS: u32 = 90; +/// Renew a server certificate when fewer than this many days are left. pub const SERVER_RENEW_DAYS: u32 = 30; +/// Device (mTLS client) certificates. pub const DEVICE_DAYS: u32 = 365; +/// Subject CN of the root. pub const ROOT_CN: &str = "Domi PKI Root"; +/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this. pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; -pub const KEY_KDF_ITERATIONS: u32 = 0; +/// Organisation on every certificate. +pub const ORG: &str = "Fabrica Domi"; +/// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure). +pub const KEY_KDF_ITERATIONS: u32 = 600_000; +/// Backdating of `notBefore`, for clocks that run a little late. +const BACKDATE_SECS: i64 = 300; +const DAY: i64 = 86_400; +// Split so that this file does not match the pre-commit hook itself. +const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); +const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----"); +const KEY_MAGIC: &[u8; 4] = b"IEK1"; +const KEY_AAD: &[u8] = b"ianitor encrypted key v1"; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PkiError { - #[error("not built yet")] - NotBuilt, - #[error("bad certificate")] + #[error("the certificate cannot be read: {0}")] BadCertificate(String), - #[error("bad csr")] + #[error("the certificate signing request cannot be read or its signature is wrong")] BadCsr, - #[error("csr subject")] + #[error("the request's subject must start with \"{INTERMEDIATE_CN}\"")] CsrSubject, - #[error("bad key")] + #[error("the private key cannot be read")] BadKey, - #[error("not a ca")] + #[error("the certificate is not a CA certificate")] NotCa, - #[error("key mismatch")] + #[error("the private key does not belong to the certificate")] KeyMismatch, - #[error("issuer expired")] + #[error("the issuing certificate has expired or is not valid yet")] IssuerExpired, - #[error("wrong password")] + #[error("the name cannot be used in a certificate: {0}")] + BadName(String), + #[error("the encrypted key cannot be read")] + BadSealedKey, + #[error("the password does not open the encrypted key")] WrongPassword, + #[error("no randomness available")] + Random, + #[error("the certificate could not be made: {0}")] + Build(String), +} + +fn build(e: rcgen::Error) -> PkiError { + PkiError::Build(e.to_string()) +} + +/// An ECDSA P-256 key pair. Never printed. +pub struct KeyPair(rcgen::KeyPair); + +impl fmt::Debug for KeyPair { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("KeyPair(…)") + } } -#[derive(Debug)] -pub struct KeyPair; impl KeyPair { - pub fn serialize_pem(&self) -> String { String::new() } - pub fn from_pem(_: &str) -> Result { Err(PkiError::NotBuilt) } - pub fn public_key_der(&self) -> Vec { Vec::new() } + /// PKCS#8 PEM. Callers write it only to files with mode 0600 (or encrypt it). + pub fn serialize_pem(&self) -> String { + self.0.serialize_pem() + } + + pub fn serialize_der(&self) -> Vec { + self.0.serialize_der() + } + + pub fn from_pem(pem: &str) -> Result { + rcgen::KeyPair::from_pem(pem) + .map(KeyPair) + .map_err(|_| PkiError::BadKey) + } + + pub fn from_der(der: &[u8]) -> Result { + rcgen::KeyPair::try_from(der) + .map(KeyPair) + .map_err(|_| PkiError::BadKey) + } + + /// SubjectPublicKeyInfo DER. + pub fn public_key_der(&self) -> Vec { + use rcgen::PublicKeyData as _; + self.0.subject_public_key_info() + } } -pub fn generate_key() -> Result { Err(PkiError::NotBuilt) } -pub fn create_root(_: i64) -> Result<(String, KeyPair), PkiError> { Err(PkiError::NotBuilt) } -pub fn intermediate_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } -pub fn sign_intermediate(_: &str, _: &KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } -#[derive(Debug)] -pub struct Intermediate; + +pub fn generate_key() -> Result { + rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) + .map(KeyPair) + .map_err(build) +} + +fn random() -> Result<[u8; N], PkiError> { + let mut b = [0u8; N]; + SystemRandom::new() + .fill(&mut b) + .map_err(|_| PkiError::Random)?; + Ok(b) +} + +fn serial() -> Result { + let mut b = random::<16>()?; + // Positive and never shortened by DER (leading byte 0x01..=0x7f). + b[0] = (b[0] & 0x7f) | 0x01; + Ok(SerialNumber::from_slice(&b)) +} + +fn time(unix: i64) -> Result { + OffsetDateTime::from_unix_timestamp(unix).map_err(|e| PkiError::Build(e.to_string())) +} + +fn dn(cn: &str) -> DistinguishedName { + let mut d = DistinguishedName::new(); + d.push(DnType::CommonName, cn); + d.push(DnType::OrganizationName, ORG); + d +} + +/// A certificate name a person typed: 1 to 64 printable characters, no control characters. +fn check_display_name(name: &str) -> Result<(), PkiError> { + let n = name.chars().count(); + if n == 0 || n > 64 || name.chars().any(char::is_control) || name.trim() != name { + return Err(PkiError::BadName( + "use 1 to 64 visible characters, no leading or trailing spaces".into(), + )); + } + Ok(()) +} + +// ------------------------------------------------------------------ root (offline) + +/// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline +/// machine only (`ianitor-control ca init`); control never calls this on the server. +pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> { + let key = generate_key()?; + let mut p = CertificateParams::default(); + p.distinguished_name = dn(ROOT_CN); + p.is_ca = IsCa::Ca(BasicConstraints::Constrained(1)); + p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time(now + i64::from(ROOT_DAYS) * DAY)?; + p.serial_number = Some(serial()?); + let cert = p.self_signed(&key.0).map_err(build)?; + Ok((cert.pem(), key)) +} + +/// A CSR for a new intermediate key (made by control on the server). +pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result { + let mut p = CertificateParams::default(); + p.distinguished_name = dn(cn); + p.serialize_request(&key.0) + .map_err(build)? + .pem() + .map_err(build) +} + +/// 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( + root_cert_pem: &str, + root_key: &KeyPair, + csr_pem: &str, + now: i64, +) -> Result { + let root = inspect(root_cert_pem)?; + if !root.is_ca { + return Err(PkiError::NotCa); + } + if public_key_der(root_cert_pem)? != root_key.public_key_der() { + return Err(PkiError::KeyMismatch); + } + if now < root.not_before || now >= root.not_after { + return Err(PkiError::IssuerExpired); + } + let csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(|_| PkiError::BadCsr)?; + let cn = csr + .params + .distinguished_name + .get(&DnType::CommonName) + .and_then(dn_text) + .ok_or(PkiError::CsrSubject)?; + if !cn.starts_with(INTERMEDIATE_CN) + || cn.chars().count() > 64 + || cn.chars().any(char::is_control) + { + return Err(PkiError::CsrSubject); + } + let mut p = CertificateParams::default(); + p.distinguished_name = dn(&cn); + p.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); + p.key_usages = vec![ + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::CrlSign, + KeyUsagePurpose::DigitalSignature, + ]; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time((now + i64::from(INTERMEDIATE_DAYS) * DAY).min(root.not_after))?; + p.serial_number = Some(serial()?); + p.use_authority_key_identifier_extension = true; + let fresh = CertificateSigningRequestParams { + params: p, + public_key: csr.public_key, + }; + let issuer = Issuer::from_ca_cert_pem(root_cert_pem, &root_key.0).map_err(build)?; + Ok(fresh.signed_by(&issuer).map_err(build)?.pem()) +} + +fn dn_text(v: &rcgen::DnValue) -> Option { + match v { + rcgen::DnValue::Utf8String(s) => Some(s.clone()), + rcgen::DnValue::PrintableString(s) => Some(s.as_str().to_owned()), + _ => None, + } +} + +// ------------------------------------------------------------------ the intermediate + +/// The intermediate as control holds it: its certificate and its key, checked to belong +/// together and to be a CA. +pub struct Intermediate { + cert_pem: String, + key: KeyPair, + info: CertInfo, +} + +impl fmt::Debug for Intermediate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Intermediate") + .field("subject", &self.info.subject_cn) + .field("not_after", &self.info.not_after) + .finish() + } +} + impl Intermediate { - pub fn new(_: &str, _: KeyPair) -> Result { Err(PkiError::NotBuilt) } - pub fn cert_pem(&self) -> &str { "" } - pub fn not_after(&self) -> i64 { 0 } + pub fn new(cert_pem: &str, key: KeyPair) -> Result { + let first = first_pem(cert_pem)?; + let info = inspect(&first)?; + if !info.is_ca { + return Err(PkiError::NotCa); + } + if public_key_der(&first)? != key.public_key_der() { + return Err(PkiError::KeyMismatch); + } + Ok(Intermediate { + cert_pem: first, + key, + info, + }) + } + + pub fn cert_pem(&self) -> &str { + &self.cert_pem + } + + pub fn not_after(&self) -> i64 { + self.info.not_after + } + + pub fn info(&self) -> &CertInfo { + &self.info + } + + pub fn key(&self) -> &KeyPair { + &self.key + } + + fn issue(&self, mut p: CertificateParams, days: u32, now: i64) -> Result { + if now < self.info.not_before || now >= self.info.not_after { + return Err(PkiError::IssuerExpired); + } + let key = generate_key()?; + p.is_ca = IsCa::ExplicitNoCa; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time((now + i64::from(days) * DAY).min(self.info.not_after))?; + p.serial_number = Some(serial()?); + p.use_authority_key_identifier_extension = true; + let issuer = Issuer::from_ca_cert_pem(&self.cert_pem, &self.key.0).map_err(build)?; + let cert = p.signed_by(&key.0, &issuer).map_err(build)?; + let cert_pem = cert.pem(); + let info = inspect(&cert_pem)?; + Ok(Issued { + chain_pem: format!("{cert_pem}{}", self.cert_pem), + key_pem: key.serialize_pem(), + key, + serial_hex: info.serial_hex.clone(), + sha256_hex: info.sha256_hex.clone(), + not_before: info.not_before, + not_after: info.not_after, + cert_pem, + }) + } } -#[derive(Debug)] -pub struct Issued { pub cert_pem: String, pub chain_pem: String, pub key_pem: String } -pub fn issue_server(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } -pub fn issue_device(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } -#[derive(Debug)] -pub struct CertInfo { pub subject_cn: String, pub not_after: i64, pub is_ca: bool, pub path_len: Option, pub dns_names: Vec } -pub fn inspect(_: &str) -> Result { Err(PkiError::NotBuilt) } -pub fn public_key_der(_: &str) -> Result, PkiError> { Err(PkiError::NotBuilt) } -pub fn issued_by(_: &str, _: &str) -> Result { Err(PkiError::NotBuilt) } -pub fn match_code(_: &[u8]) -> String { String::new() } -pub fn encrypt_key_with(_: &KeyPair, _: &[u8], _: u32) -> Result { Err(PkiError::NotBuilt) } -pub fn decrypt_key(_: &str, _: &[u8]) -> Result { Err(PkiError::NotBuilt) } + +/// A freshly issued leaf. +pub struct Issued { + /// The leaf alone. + pub cert_pem: String, + /// Leaf, then the intermediate (what a server or a device presents). + pub chain_pem: String, + /// PKCS#8 PEM of the leaf's key. + pub key_pem: String, + pub key: KeyPair, + pub serial_hex: String, + /// SHA-256 of the leaf's DER, lowercase hex. + pub sha256_hex: String, + pub not_before: i64, + pub not_after: i64, +} + +impl fmt::Debug for Issued { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Issued") + .field("serial", &self.serial_hex) + .field("not_after", &self.not_after) + .finish() + } +} + +/// A server certificate for one hostname (`tls = "domi"`). The hostname must already be +/// validated by the schema; it is checked again here. +pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result { + let mut p = CertificateParams::new(vec![hostname.to_owned()]) + .map_err(|e| PkiError::BadName(e.to_string()))?; + p.distinguished_name = dn(hostname); + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + int.issue(p, SERVER_DAYS, now) +} + +/// A device certificate (mTLS client) for a named device. +pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result { + check_display_name(name)?; + let mut p = CertificateParams::default(); + let mut d = DistinguishedName::new(); + d.push(DnType::CommonName, name); + d.push(DnType::OrganizationName, ORG); + d.push(DnType::OrganizationalUnitName, "Domi devices"); + p.distinguished_name = d; + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + int.issue(p, DEVICE_DAYS, now) +} + +// ------------------------------------------------------------------ reading certificates + +/// What Ianitor needs to know about a certificate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CertInfo { + pub subject_cn: String, + pub issuer_cn: String, + pub not_before: i64, + pub not_after: i64, + pub is_ca: bool, + pub path_len: Option, + pub dns_names: Vec, + pub serial_hex: String, + pub sha256_hex: String, +} + +fn ders(pem: &str) -> Result>, PkiError> { + let mut out = Vec::new(); + for p in x509_parser::pem::Pem::iter_from_buffer(pem.as_bytes()) { + let p = p.map_err(|e| PkiError::BadCertificate(e.to_string()))?; + if p.label != "CERTIFICATE" { + return Err(PkiError::BadCertificate(format!( + "unexpected PEM block {}", + p.label + ))); + } + out.push(p.contents); + } + if out.is_empty() { + return Err(PkiError::BadCertificate("no certificate in it".into())); + } + Ok(out) +} + +/// The DER of every certificate in a PEM chain, in order. +pub fn chain_der(pem: &str) -> Result>, PkiError> { + ders(pem) +} + +/// The first certificate of a PEM chain, as PEM. +pub fn first_pem(pem: &str) -> Result { + let first = ders(pem)? + .into_iter() + .next() + .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; + Ok(der_to_pem(&first)) +} + +pub fn der_to_pem(der: &[u8]) -> String { + let b = STANDARD.encode(der); + let mut s = String::from("-----BEGIN CERTIFICATE-----\n"); + for chunk in b.as_bytes().chunks(64) { + s.push_str(&String::from_utf8_lossy(chunk)); + s.push('\n'); + } + s.push_str("-----END CERTIFICATE-----\n"); + s +} + +fn parse(der: &[u8]) -> Result, PkiError> { + let (rest, c) = x509_parser::parse_x509_certificate(der) + .map_err(|e| PkiError::BadCertificate(e.to_string()))?; + if !rest.is_empty() { + return Err(PkiError::BadCertificate("trailing bytes".into())); + } + Ok(c) +} + +fn cn_of(name: &x509_parser::x509::X509Name<'_>) -> String { + name.iter_common_name() + .next() + .and_then(|c| c.as_str().ok()) + .unwrap_or_default() + .to_owned() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// SHA-256 of a DER blob, lowercase hex. +pub fn sha256_hex(der: &[u8]) -> String { + hex(ring::digest::digest(&ring::digest::SHA256, der).as_ref()) +} + +/// Read the first certificate of a PEM chain. +pub fn inspect(pem: &str) -> Result { + let der = ders(pem)? + .into_iter() + .next() + .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; + inspect_der(&der) +} + +pub fn inspect_der(der: &[u8]) -> Result { + let c = parse(der)?; + let bc = c + .basic_constraints() + .map_err(|e| PkiError::BadCertificate(e.to_string()))?; + let (is_ca, path_len) = match bc { + Some(b) => (b.value.ca, b.value.path_len_constraint), + None => (false, None), + }; + let dns_names = match c + .subject_alternative_name() + .map_err(|e| PkiError::BadCertificate(e.to_string()))? + { + Some(san) => san + .value + .general_names + .iter() + .filter_map(|g| match g { + x509_parser::extensions::GeneralName::DNSName(n) => Some((*n).to_owned()), + _ => None, + }) + .collect(), + None => Vec::new(), + }; + Ok(CertInfo { + subject_cn: cn_of(c.subject()), + issuer_cn: cn_of(c.issuer()), + not_before: c.validity().not_before.timestamp(), + not_after: c.validity().not_after.timestamp(), + is_ca, + path_len, + dns_names, + serial_hex: hex(c.raw_serial()), + sha256_hex: sha256_hex(der), + }) +} + +/// SubjectPublicKeyInfo DER of the first certificate. +pub fn public_key_der(pem: &str) -> Result, PkiError> { + let der = ders(pem)? + .into_iter() + .next() + .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; + let c = parse(&der)?; + Ok(c.public_key().raw.to_vec()) +} + +/// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and +/// does its issuer name match? A CA flag on the issuer is required. +pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result { + let cd = ders(child_pem)? + .into_iter() + .next() + .ok_or(PkiError::BadCertificate(String::new()))?; + let id = ders(issuer_pem)? + .into_iter() + .next() + .ok_or(PkiError::BadCertificate(String::new()))?; + let child = parse(&cd)?; + let issuer = parse(&id)?; + let ca = matches!(issuer.basic_constraints(), Ok(Some(b)) if b.value.ca); + Ok(ca + && child.issuer() == issuer.subject() + && child.verify_signature(Some(issuer.public_key())).is_ok()) +} + +// ------------------------------------------------------------------ match codes + +/// The code both screens show for one request: SHA-256 of the request, first three bytes, +/// each mod 100, as `47 19 83` (see docs/custos-ticket.md). +pub fn match_code(request: &[u8]) -> String { + let d = ring::digest::digest(&ring::digest::SHA256, request); + let b = d.as_ref(); + format!( + "{:02} {:02} {:02}", + b.first().copied().unwrap_or(0) % 100, + b.get(1).copied().unwrap_or(0) % 100, + b.get(2).copied().unwrap_or(0) % 100 + ) +} + +/// DER of the first PEM block of a CSR (for the match code). +pub fn csr_der(csr_pem: &str) -> Result, PkiError> { + for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { + let p = p.map_err(|_| PkiError::BadCsr)?; + if p.label == "CERTIFICATE REQUEST" { + return Ok(p.contents); + } + } + Err(PkiError::BadCsr) +} + +// ------------------------------------------------------------------ encrypted keys + +fn derive( + password: &[u8], + salt: &[u8], + iterations: u32, +) -> Result { + let n = std::num::NonZeroU32::new(iterations).ok_or(PkiError::BadSealedKey)?; + let mut k = [0u8; 32]; + ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, n, salt, password, &mut k); + let unbound = ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, &k) + .map_err(|_| PkiError::BadSealedKey)?; + Ok(ring::aead::LessSafeKey::new(unbound)) +} + +/// Encrypt a key with a password: PBKDF2-HMAC-SHA256 ([`KEY_KDF_ITERATIONS`]) and +/// AES-256-GCM, armoured as `IANITOR ENCRYPTED PRIVATE KEY` (so the pre-commit hook blocks it). +pub fn encrypt_key(key: &KeyPair, password: &[u8]) -> Result { + encrypt_key_with(key, password, KEY_KDF_ITERATIONS) +} + +/// [`encrypt_key`] with another iteration count (tests). +pub fn encrypt_key_with( + key: &KeyPair, + password: &[u8], + iterations: u32, +) -> Result { + if password.is_empty() { + return Err(PkiError::WrongPassword); + } + let salt = random::<16>()?; + let nonce = random::<12>()?; + let k = derive(password, &salt, iterations)?; + let mut data = key.serialize_der(); + k.seal_in_place_append_tag( + ring::aead::Nonce::assume_unique_for_key(nonce), + ring::aead::Aad::from(KEY_AAD), + &mut data, + ) + .map_err(|_| PkiError::BadSealedKey)?; + let mut blob = Vec::with_capacity(36 + data.len()); + blob.extend_from_slice(KEY_MAGIC); + blob.extend_from_slice(&iterations.to_be_bytes()); + blob.extend_from_slice(&salt); + blob.extend_from_slice(&nonce); + blob.extend_from_slice(&data); + let b = STANDARD.encode(blob); + let mut s = format!("{ARMOR_BEGIN}\n"); + for chunk in b.as_bytes().chunks(64) { + s.push_str(&String::from_utf8_lossy(chunk)); + s.push('\n'); + } + s.push_str(ARMOR_END); + s.push('\n'); + Ok(s) +} + +/// Open a key made by [`encrypt_key`]. +pub fn decrypt_key(sealed: &str, password: &[u8]) -> Result { + let body = sealed + .trim() + .strip_prefix(ARMOR_BEGIN) + .and_then(|r| r.strip_suffix(ARMOR_END)) + .ok_or(PkiError::BadSealedKey)?; + let b64: String = body.chars().filter(|c| !c.is_ascii_whitespace()).collect(); + let blob = STANDARD.decode(b64).map_err(|_| PkiError::BadSealedKey)?; + if blob.len() < 4 + 4 + 16 + 12 + 16 || &blob[..4] != KEY_MAGIC { + return Err(PkiError::BadSealedKey); + } + let iterations = u32::from_be_bytes([blob[4], blob[5], blob[6], blob[7]]); + if !(1..=10_000_000).contains(&iterations) { + return Err(PkiError::BadSealedKey); + } + let salt = &blob[8..24]; + let mut nonce = [0u8; 12]; + nonce.copy_from_slice(&blob[24..36]); + let mut data = blob[36..].to_vec(); + let k = derive(password, salt, iterations)?; + let plain = k + .open_in_place( + ring::aead::Nonce::assume_unique_for_key(nonce), + ring::aead::Aad::from(KEY_AAD), + &mut data, + ) + .map_err(|_| PkiError::WrongPassword)?; + KeyPair::from_der(plain) +} + +// ------------------------------------------------------------------ for tests + +/// Helpers for tests that need certificates Ianitor itself would never make. #[doc(hidden)] pub mod testing { use super::*; - pub fn sign_as(_: &str, _: KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } - pub fn sub_ca(_: &Intermediate, _: &KeyPair, _: i64) -> Result { Err(PkiError::NotBuilt) } - pub fn greedy_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } - pub fn tamper_csr(s: &str) -> String { s.to_owned() } + + /// A server certificate for `name`, signed with `key` as if the first certificate of + /// `issuer_pem` were a CA (for "a leaf cannot sign"). + pub fn sign_as( + issuer_pem: &str, + key: KeyPair, + name: &str, + now: i64, + ) -> Result { + let leaf_key = generate_key()?; + let mut p = CertificateParams::new(vec![name.to_owned()]).map_err(build)?; + p.distinguished_name = dn(name); + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time(now + 30 * DAY)?; + let issuer = Issuer::from_ca_cert_pem(&first_pem(issuer_pem)?, key.0).map_err(build)?; + Ok(p.signed_by(&leaf_key.0, &issuer).map_err(build)?.pem()) + } + + /// A CA below the intermediate (which pathLen 0 forbids). + pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result { + let mut p = CertificateParams::default(); + p.distinguished_name = dn("Sub CA"); + p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + p.key_usages = vec![KeyUsagePurpose::KeyCertSign]; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time(now + 30 * DAY)?; + let issuer = Issuer::from_ca_cert_pem(int.cert_pem(), &int.key.0).map_err(build)?; + Ok(p.signed_by(&key.0, &issuer).map_err(build)?.pem()) + } + + /// A CSR that asks for far too much. + pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result { + let mut p = CertificateParams::new(vec!["www.example.com".to_owned()]).map_err(build)?; + p.distinguished_name = dn(cn); + p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + p.not_after = time(4_000_000_000)?; + p.serialize_request(&key.0) + .map_err(build)? + .pem() + .map_err(build) + } + + /// Flip one byte inside the CSR's signed part. + pub fn tamper_csr(csr_pem: &str) -> String { + let Ok(mut der) = csr_der(csr_pem) else { + return csr_pem.to_owned(); + }; + if let Some(b) = der.get_mut(40) { + *b ^= 0x01; + } + let b = STANDARD.encode(der); + let mut s = String::from("-----BEGIN CERTIFICATE REQUEST-----\n"); + for chunk in b.as_bytes().chunks(64) { + s.push_str(&String::from_utf8_lossy(chunk)); + s.push('\n'); + } + s.push_str("-----END CERTIFICATE REQUEST-----\n"); + s + } } diff --git a/crates/core/tests/pki.rs b/crates/core/tests/pki.rs index df4baf0..7fbbb73 100644 --- a/crates/core/tests/pki.rs +++ b/crates/core/tests/pki.rs @@ -56,12 +56,7 @@ fn ca() -> Ca { } /// Verify `leaf_chain` (leaf first, then intermediates) against `root` at time `t`. -fn verify( - root_pem: &str, - leaf_chain: &str, - t: i64, - usage: KeyUsage, -) -> Result<(), webpki::Error> { +fn verify(root_pem: &str, leaf_chain: &str, t: i64, usage: KeyUsage) -> Result<(), webpki::Error> { let root = der(root_pem); let anchor = anchor_from_trusted_cert(&root).unwrap().to_owned(); let chain = all_der(leaf_chain); @@ -84,10 +79,16 @@ fn root_is_a_ten_year_ca_with_path_length_one() { let info = pki::inspect(&root_pem).unwrap(); assert!(info.is_ca); assert_eq!(info.path_len, Some(1)); - assert!(info.path_len.unwrap() >= 1, "ROADMAP §3: pathLenConstraint >= 1"); + assert!( + info.path_len.unwrap() >= 1, + "ROADMAP §3: pathLenConstraint >= 1" + ); assert_eq!(info.subject_cn, pki::ROOT_CN); let days = (info.not_after - NOW) / DAY; - assert!((ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), "{days}"); + assert!( + (ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), + "{days}" + ); assert!(days >= 3650); } @@ -106,23 +107,44 @@ fn intermediate_is_one_year_path_length_zero_and_signed_by_the_root() { fn server_chain_validates_to_the_root() { let c = ca(); let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); - verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap(); + verify( + &c.root_pem, + &leaf.chain_pem, + NOW + DAY, + KeyUsage::server_auth(), + ) + .unwrap(); let info = pki::inspect(&leaf.cert_pem).unwrap(); assert!(!info.is_ca); assert_eq!(info.dns_names, vec!["wiki.home.test".to_owned()]); assert_eq!((info.not_after - NOW) / DAY, SERVER_DAYS as i64); // The key belongs to the certificate. let k = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); - assert_eq!(pki::public_key_der(&leaf.cert_pem).unwrap(), k.public_key_der()); + assert_eq!( + pki::public_key_der(&leaf.cert_pem).unwrap(), + k.public_key_der() + ); } #[test] fn device_chain_validates_for_client_auth_only() { let c = ca(); let dev = pki::issue_device(&c.int, "Mark's phone", NOW).unwrap(); - verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::client_auth()).unwrap(); + verify( + &c.root_pem, + &dev.chain_pem, + NOW + DAY, + KeyUsage::client_auth(), + ) + .unwrap(); assert!( - verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::server_auth()).is_err(), + verify( + &c.root_pem, + &dev.chain_pem, + NOW + DAY, + KeyUsage::server_auth() + ) + .is_err(), "a device certificate cannot serve a site" ); let info = pki::inspect(&dev.cert_pem).unwrap(); @@ -177,7 +199,15 @@ fn expired_certificates_are_rejected() { Err(webpki::Error::CertExpired { .. }) )); let before = NOW - DAY; - assert!(verify(&c.root_pem, &leaf.chain_pem, before, KeyUsage::server_auth()).is_err()); + assert!( + verify( + &c.root_pem, + &leaf.chain_pem, + before, + KeyUsage::server_auth() + ) + .is_err() + ); } #[test] @@ -205,12 +235,17 @@ fn a_certificate_from_another_root_is_rejected() { let leaf = pki::issue_server(&other.int, "wiki.home.test", NOW).unwrap(); // Both CAs have the same names, so webpki finds the issuer by name and then the // signature check fails. - let e = verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap_err(); + let e = verify( + &c.root_pem, + &leaf.chain_pem, + NOW + DAY, + KeyUsage::server_auth(), + ) + .unwrap_err(); assert!( matches!( e, - webpki::Error::UnknownIssuer - | webpki::Error::InvalidSignatureForPublicKey + webpki::Error::UnknownIssuer | webpki::Error::InvalidSignatureForPublicKey ), "{e:?}" ); @@ -274,7 +309,11 @@ fn match_code_is_three_two_digit_groups_and_stable() { assert_ne!(a, pki::match_code(b"other csr")); let parts: Vec<&str> = a.split(' ').collect(); assert_eq!(parts.len(), 3); - assert!(parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))); + assert!( + parts + .iter() + .all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + ); } #[test] @@ -283,7 +322,10 @@ fn encrypted_key_needs_its_password() { let sealed = pki::encrypt_key_with(&key, b"correct horse battery", 1000).unwrap(); // Armoured so that the pre-commit hook would block it like any private key. // (Split so that this file does not match the hook itself.) - assert!(sealed.starts_with(concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----\n"))); + assert!(sealed.starts_with(concat!( + "-----BEGIN IANITOR ENCRYPTED ", + "PRIVATE KEY-----\n" + ))); // The plain key is not inside. assert!(!sealed.contains(&key.serialize_pem())); let back = pki::decrypt_key(&sealed, b"correct horse battery").unwrap(); @@ -299,7 +341,7 @@ fn encrypted_key_needs_its_password() { assert!(pki::decrypt_key(&String::from_utf8(bad).unwrap(), b"correct horse battery").is_err()); assert!(pki::decrypt_key("garbage", b"x").is_err()); // Default strength. - assert!(pki::KEY_KDF_ITERATIONS >= 600_000); + const { assert!(pki::KEY_KDF_ITERATIONS >= 600_000) }; } #[test] -- 2.53.0 From 18da3f5d5a16041cb78432c2748e5cf6139b0488 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:46:07 +0100 Subject: [PATCH 04/34] [core] Device certificates: device_certs host field; edge config v3 and Caddy client_authentication with a CA bundle and an allow list, 403 without a certificate --- crates/core/src/compile/caddy.rs | 43 ++++++++++-- crates/core/src/compile/edge.rs | 15 ++++- crates/core/src/compile/mod.rs | 5 ++ crates/core/src/edge_config.rs | 17 ++++- crates/core/src/model.rs | 2 + crates/core/src/validate.rs | 3 + crates/core/tests/compile.rs | 65 +++++++++++++++++++ .../routes/hosts/status.example.org.toml | 1 + crates/core/tests/golden/caddy.json | 46 +++++++++++++ crates/core/tests/golden/edge.json | 15 +++-- crates/core/tests/schema.rs | 3 + 11 files changed, 201 insertions(+), 14 deletions(-) diff --git a/crates/core/src/compile/caddy.rs b/crates/core/src/compile/caddy.rs index 2066cf7..5c90e97 100644 --- a/crates/core/src/compile/caddy.rs +++ b/crates/core/src/compile/caddy.rs @@ -10,7 +10,7 @@ use serde_json::{Map, Value, json}; -use super::{CompileOptions, join, strip_headers}; +use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers}; use crate::{ AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode, Upstream, @@ -52,13 +52,23 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { routes.push(not_found()); let domi: Vec<&Host> = hosts.iter().filter(|h| h.tls == TlsMode::Domi).collect(); - let mut policies: Vec = domi + // One policy per host that needs one: a Domi certificate, device certificates, or both. + let mut policies: Vec = hosts .iter() + .filter(|h| h.tls == TlsMode::Domi || h.device_certs) .map(|h| { - json!({ - "match": { "sni": [h.hostname.as_str()] }, - "certificate_selection": { "any_tag": [cert_tag(h)] } - }) + let mut p = Map::new(); + p.insert("match".into(), json!({ "sni": [h.hostname.as_str()] })); + if h.tls == TlsMode::Domi { + p.insert( + "certificate_selection".into(), + json!({ "any_tag": [cert_tag(h)] }), + ); + } + if h.device_certs { + p.insert("client_authentication".into(), client_auth(o)); + } + Value::Object(p) }) .collect(); policies.push(json!({})); @@ -203,6 +213,14 @@ fn logging(file: &str) -> Value { fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value { let mut steps = Vec::new(); + if h.device_certs { + // No client certificate on this connection: 403, like edge. A certificate that is not + // trusted or not on the allow list never gets this far (the handshake fails). + steps.push(json!({ + "match": [{ "vars": { "{http.request.tls.client.fingerprint}": [""] } }], + "handle": [{ "handler": "static_response", "status_code": 403 }] + })); + } if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) { // Client-sent identity headers never reach the auth server or the upstream. steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] })); @@ -339,3 +357,16 @@ fn forward_auth(fa: &ForwardAuth) -> Value { ); Value::Object(rp) } + +/// Device certificates: optional in the handshake (a missing one is a 403 in the route, as in +/// edge), but one that is presented must chain to the Domi CA bundle and be on the allow list. +fn client_auth(o: &CompileOptions) -> Value { + json!({ + "ca": { "provider": "file", "pem_files": [join(&o.cert_dir, DEVICE_CA_FILE)] }, + "verifiers": [{ + "verifier": "leaf", + "leaf_certs_loaders": [{ "loader": "file", "files": [join(&o.cert_dir, DEVICE_ALLOW_FILE)] }] + }], + "mode": "verify_if_given" + }) +} diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index 65a80c3..fca4b7f 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -4,10 +4,10 @@ //! Model → [`EdgeConfig`] for the Pingora data plane. -use super::{CompileOptions, join, strip_headers}; +use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers}; use crate::edge_config::{ - EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck, - EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, + EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeDeviceCerts, EdgeForwardAuth, EdgeHeaderOp, + EdgeHealthCheck, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, }; use crate::{AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream}; @@ -26,6 +26,14 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { directory: site.acme.directory.clone(), email: site.acme.email.clone(), }), + device_certs: model + .hosts() + .iter() + .any(|h| h.device_certs) + .then(|| EdgeDeviceCerts { + ca: join(&o.cert_dir, DEVICE_CA_FILE), + allow: join(&o.cert_dir, DEVICE_ALLOW_FILE), + }), forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth { upstream: upstream(&fa.upstream), path_and_query: fa.path_and_query.clone(), @@ -55,6 +63,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { }), access_log: h.access_log == AccessLog::Truncated, share_links: h.share_links, + device_certs: h.device_certs, }) .collect(), } diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs index 8c4e74e..cff8cae 100644 --- a/crates/core/src/compile/mod.rs +++ b/crates/core/src/compile/mod.rs @@ -17,6 +17,11 @@ mod caddy; mod edge; +/// In the certificate directory: the CA bundle for device certificates (written by control). +pub const DEVICE_CA_FILE: &str = "domi-devices-ca.pem"; +/// In the certificate directory: every allowed (issued, not revoked) device certificate. +pub const DEVICE_ALLOW_FILE: &str = "domi-devices.pem"; + use std::net::SocketAddr; use crate::Model; diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index fdece67..0ce05bc 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// Bumped on any incompatible change; edge refuses other versions. -pub const EDGE_CONFIG_VERSION: u32 = 2; +pub const EDGE_CONFIG_VERSION: u32 = 3; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -29,6 +29,8 @@ pub struct EdgeConfig { pub access_log: String, pub acme: Option, pub forward_auth: Option, + /// Device certificates (mTLS); present when any host has `device_certs`. + pub device_certs: Option, /// Sorted by hostname. pub hosts: Vec, } @@ -106,4 +108,17 @@ pub struct EdgeHost { /// Share-link tokens (see `ianitor_core::share`) let visitors in on this host without /// forward-auth. Checked against the key credential and the revocation file. pub share_links: bool, + /// Only visitors with an allowed Domi device certificate get in (403 otherwise). + pub device_certs: bool, +} + +/// Where edge finds what it needs to check device certificates. Both files are written by +/// control: the CA bundle (the Domi intermediates that issue device certificates) and the +/// allow list (every device certificate that is issued and not revoked, PEM). A certificate +/// that chains to the bundle but is not on the list is refused in the handshake. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EdgeDeviceCerts { + pub ca: String, + pub allow: String, } diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 72e43c2..847ec88 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -171,6 +171,8 @@ pub struct Host { pub health_check: Option, pub share_links: bool, pub access_log: AccessLog, + /// Visitors must present a Domi device certificate (mTLS) that is on the allow list. + pub device_certs: bool, } /// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`). diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index d00e3f3..b56a9f1 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -121,6 +121,8 @@ struct RawHost { #[serde(default)] share_links: bool, #[serde(default)] + device_certs: bool, + #[serde(default)] access_log: RawAccessLog, health_check: Option, #[serde(default)] @@ -517,6 +519,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec websockets: raw.websockets, health_check, share_links: raw.share_links, + device_certs: raw.device_certs, access_log: match raw.access_log { RawAccessLog::Off => AccessLog::Off, RawAccessLog::Truncated => AccessLog::Truncated, diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs index ee55f92..59a5c7a 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -277,3 +277,68 @@ fn websocket_refusal_in_caddy_matches_any_upgrade_token() { "token-aware Upgrade matcher" ); } + +#[test] +fn device_cert_hosts_check_client_certificates_in_both_engines() { + let m = model(false); + let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap(); + let dc = edge.device_certs.expect("a host needs device certificates"); + assert_eq!(dc.ca, "/var/lib/ianitor/certs/domi-devices-ca.pem"); + assert_eq!(dc.allow, "/var/lib/ianitor/certs/domi-devices.pem"); + let on: Vec<&str> = edge + .hosts + .iter() + .filter(|h| h.device_certs) + .map(|h| h.hostname.as_str()) + .collect(); + assert_eq!(on, ["status.example.org"]); + + let v: serde_json::Value = + serde_json::from_str(&compile::caddy(&m, &options()).unwrap()).unwrap(); + let https = &v["apps"]["http"]["servers"]["ianitor_https"]; + let policies = https["tls_connection_policies"].as_array().unwrap(); + let with_auth: Vec<&serde_json::Value> = policies + .iter() + .filter(|p| p.get("client_authentication").is_some()) + .collect(); + assert_eq!( + with_auth.len(), + 1, + "only the device host asks for a certificate" + ); + assert_eq!(with_auth[0]["match"]["sni"][0], "status.example.org"); + assert_eq!( + with_auth[0]["client_authentication"]["mode"], + "verify_if_given" + ); + let routes = https["routes"].as_array().unwrap(); + let status = routes + .iter() + .find(|r| r["match"][0]["host"][0] == "status.example.org") + .unwrap(); + let first = &status["handle"][0]["routes"][0]; + assert_eq!( + first["handle"][0]["status_code"], 403, + "no certificate: 403 first" + ); + + // Without a device host, neither engine asks for client certificates. + let plain = ianitor_core::load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[SourceFile { + name: "hosts/a.test.toml", + contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + }], + ) + .unwrap(); + let e: EdgeConfig = serde_json::from_str(&compile::edge(&plain, &options()).unwrap()).unwrap(); + assert!(e.device_certs.is_none()); + assert!( + !compile::caddy(&plain, &options()) + .unwrap() + .contains("client_authentication") + ); +} diff --git a/crates/core/tests/fixtures/routes/hosts/status.example.org.toml b/crates/core/tests/fixtures/routes/hosts/status.example.org.toml index 5af5e95..71f3e9c 100644 --- a/crates/core/tests/fixtures/routes/hosts/status.example.org.toml +++ b/crates/core/tests/fixtures/routes/hosts/status.example.org.toml @@ -1,2 +1,3 @@ hostname = "status.example.org" upstreams = ["http://[::1]:3001"] +device_certs = true diff --git a/crates/core/tests/golden/caddy.json b/crates/core/tests/golden/caddy.json index 2da0745..7add4d3 100644 --- a/crates/core/tests/golden/caddy.json +++ b/crates/core/tests/golden/caddy.json @@ -145,6 +145,23 @@ { "handler": "subroute", "routes": [ + { + "handle": [ + { + "handler": "static_response", + "status_code": 403 + } + ], + "match": [ + { + "vars": { + "{http.request.tls.client.fingerprint}": [ + "" + ] + } + } + ] + }, { "handle": [ { @@ -465,6 +482,35 @@ } ], "tls_connection_policies": [ + { + "client_authentication": { + "ca": { + "pem_files": [ + "/var/lib/ianitor/certs/domi-devices-ca.pem" + ], + "provider": "file" + }, + "mode": "verify_if_given", + "verifiers": [ + { + "leaf_certs_loaders": [ + { + "files": [ + "/var/lib/ianitor/certs/domi-devices.pem" + ], + "loader": "file" + } + ], + "verifier": "leaf" + } + ] + }, + "match": { + "sni": [ + "status.example.org" + ] + } + }, { "certificate_selection": { "any_tag": [ diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json index d673595..c37e01a 100644 --- a/crates/core/tests/golden/edge.json +++ b/crates/core/tests/golden/edge.json @@ -1,5 +1,5 @@ { - "version": 2, + "version": 3, "http_listen": "0.0.0.0:80", "https_listen": "0.0.0.0:443", "https_port": 443, @@ -30,6 +30,10 @@ "Remote-Name" ] }, + "device_certs": { + "ca": "/var/lib/ianitor/certs/domi-devices-ca.pem", + "allow": "/var/lib/ianitor/certs/domi-devices.pem" + }, "hosts": [ { "hostname": "photos.example.org", @@ -83,7 +87,8 @@ "interval_secs": 15 }, "access_log": true, - "share_links": false + "share_links": false, + "device_certs": false }, { "hostname": "status.example.org", @@ -103,7 +108,8 @@ "response_headers": [], "health_check": null, "access_log": false, - "share_links": false + "share_links": false, + "device_certs": true }, { "hostname": "wiki.home.test", @@ -134,7 +140,8 @@ "response_headers": [], "health_check": null, "access_log": false, - "share_links": false + "share_links": false, + "device_certs": false } ] } diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index 53636d1..ec808af 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -68,6 +68,7 @@ fn minimal_host_gets_documented_defaults() { assert_eq!(h.auth, AuthMode::None); assert!(h.websockets, "websockets default on, like Caddy"); assert!(!h.share_links); + assert!(!h.device_certs, "device certificates are opt-in"); assert_eq!(h.access_log, AccessLog::Off); assert!(h.health_check.is_none()); assert!(h.request_headers.is_empty() && h.response_headers.is_empty()); @@ -85,6 +86,7 @@ auth = "forward-auth" websockets = false share_links = true access_log = "truncated" +device_certs = true [health_check] path = "/healthz" @@ -110,6 +112,7 @@ value = "max-age=31536000" assert_eq!(h.auth, AuthMode::ForwardAuth); assert!(!h.websockets); assert!(h.share_links); + assert!(h.device_certs); assert_eq!(h.access_log, AccessLog::Truncated); let hc = h.health_check.as_ref().unwrap(); assert_eq!(hc.path, "/healthz"); -- 2.53.0 From 4054427b624566b6b068aee5bbfc1da52351f1ee Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:46:08 +0100 Subject: [PATCH 05/34] [edge] Tests first: a Domi device cert is accepted for mTLS, a self-signed one with the same subject, an unlisted one and none are not (red) --- Cargo.lock | 1 + crates/edge/Cargo.toml | 1 + crates/edge/tests/common/mod.rs | 6 + crates/edge/tests/device_certs.rs | 239 ++++++++++++++++++++++++++++++ tests/support/src/client.rs | 46 ++++++ 5 files changed, 293 insertions(+) create mode 100644 crates/edge/tests/device_certs.rs diff --git a/Cargo.lock b/Cargo.lock index a037d97..f2954be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1124,6 +1124,7 @@ dependencies = [ "instant-acme", "log", "pingora", + "rcgen", "ring", "rustls", "rustls-pki-types", diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index 2b7e192..0f3aa5f 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -36,6 +36,7 @@ form_urlencoded = "1.2" [dev-dependencies] ianitor-testkit.workspace = true ring.workspace = true +rcgen.workspace = true [lints] workspace = true diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index 7ba05b6..12f418b 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -108,6 +108,8 @@ pub struct EdgeSpec<'a> { pub extra_args: Vec, /// Fixed HTTP port (e.g. one Pebble was told to validate against). pub http_port: Option, + /// Extra files written into the edge directory before it starts (path relative to it). + pub files: Vec<(String, Vec)>, } impl Default for EdgeSpec<'_> { @@ -119,6 +121,7 @@ impl Default for EdgeSpec<'_> { log_level: "info", extra_args: Vec::new(), http_port: None, + files: Vec::new(), } } } @@ -165,6 +168,9 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { } let ca = TestCa::new("Ianitor Test CA"); std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap(); + for (path, value) in &spec.files { + std::fs::write(dir.join(path), value).unwrap(); + } for (name, value) in &spec.secrets { std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap(); } diff --git a/crates/edge/tests/device_certs.rs b/crates/edge/tests/device_certs.rs new file mode 100644 index 0000000..55f24de --- /dev/null +++ b/crates/edge/tests/device_certs.rs @@ -0,0 +1,239 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Device certificates (ROADMAP §6 phase 3, tests first): on a host with `device_certs`, a +//! Domi device certificate on the allow list gets in; a self-signed certificate with the same +//! subject, a Domi certificate that is not (or no longer) on the list, and no certificate at +//! all do not. Hosts without `device_certs` never ask for a certificate. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux (Pingora runner); run it in WSL2, see CLAUDE.md", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use crate::common::{Edge, EdgeSpec, host_file, start}; + use ianitor_core::pki::{self, Intermediate}; + use ianitor_testkit::client::{self, ClientCert, Req}; + use ianitor_testkit::upstream::Echo; + + fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 + } + + struct Pki { + int: Intermediate, + } + + fn pki() -> Pki { + let (root, root_key) = pki::create_root(now()).unwrap(); + let k = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); + let int_pem = pki::sign_intermediate(&root, &root_key, &csr, now()).unwrap(); + Pki { + int: Intermediate::new(&int_pem, k).unwrap(), + } + } + + fn device(p: &Pki, name: &str) -> (ClientCert, String) { + let d = pki::issue_device(&p.int, name, now()).unwrap(); + ( + ClientCert { + chain_pem: d.chain_pem, + key_pem: d.key_pem, + tls12_only: false, + }, + d.cert_pem, + ) + } + + /// Same subject as a Domi device certificate, but self-signed. + fn self_signed(name: &str) -> ClientCert { + use rcgen::{ + CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, KeyPair, + }; + let key = KeyPair::generate().unwrap(); + let mut p = CertificateParams::default(); + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, name); + dn.push(DnType::OrganizationName, pki::ORG); + dn.push(DnType::OrganizationalUnitName, "Domi devices"); + p.distinguished_name = dn; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + let cert = p.self_signed(&key).unwrap(); + ClientCert { + chain_pem: cert.pem(), + key_pem: key.serialize_pem(), + tls12_only: false, + } + } + + fn tls12(c: &ClientCert) -> ClientCert { + ClientCert { + tls12_only: true, + ..c.clone() + } + } + + async fn setup(echo: &Echo, p: &Pki, allowed: &[&str]) -> Edge { + let up = format!("upstreams = [\"{}\"]\n", echo.url()); + start(EdgeSpec { + hosts: vec![ + host_file("locked.test", &format!("{up}device_certs = true\n")), + host_file("open.test", &up), + ], + files: vec![ + ( + "certs/domi-devices-ca.pem".into(), + p.int.cert_pem().as_bytes().to_vec(), + ), + ( + "certs/domi-devices.pem".into(), + allowed.concat().into_bytes(), + ), + ], + ..Default::default() + }) + } + + #[tokio::test(flavor = "multi_thread")] + async fn domi_device_cert_is_accepted_and_a_self_signed_one_with_the_same_subject_is_not() { + let echo = Echo::start("app").await; + let p = pki(); + let (phone, phone_pem) = device(&p, "Mark's phone"); + let edge = setup(&echo, &p, &[&phone_pem]).await; + let req = Req::get("locked.test", "/"); + + for c in [phone.clone(), tls12(&phone)] { + let r = client::https_with_cert(edge.https, "locked.test", edge.roots(), &c, &req) + .await + .unwrap_or_else(|e| panic!("tls12 {}: {e}\n{}", c.tls12_only, edge.stderr())); + assert_eq!(r.status, 200, "{}", edge.stderr()); + } + + echo.clear(); + let fake = self_signed("Mark's phone"); + for c in [fake.clone(), tls12(&fake)] { + let r = + client::https_with_cert(edge.https, "locked.test", edge.roots(), &c, &req).await; + assert!( + r.is_err(), + "self-signed lookalike got in (tls12 {}): {r:?}", + c.tls12_only + ); + } + assert!(echo.requests().is_empty(), "nothing reached the upstream"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn no_certificate_is_a_403_and_never_reaches_the_upstream() { + let echo = Echo::start("app").await; + let p = pki(); + let (_, phone_pem) = device(&p, "phone"); + let edge = setup(&echo, &p, &[&phone_pem]).await; + let r = client::https( + edge.https, + "locked.test", + edge.roots(), + &Req::get("locked.test", "/"), + ) + .await + .unwrap(); + assert_eq!(r.status, 403); + assert!(echo.requests().is_empty()); + // The Host header cannot move a certificate-less connection onto the locked host. + let r = client::https( + edge.https, + "open.test", + edge.roots(), + &Req::get("locked.test", "/"), + ) + .await + .unwrap(); + assert_ne!(r.status, 200); + assert!(echo.requests().is_empty()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_domi_cert_not_on_the_allow_list_is_refused_and_revocation_takes_effect_on_reload() { + let echo = Echo::start("app").await; + let p = pki(); + let (phone, phone_pem) = device(&p, "phone"); + let (laptop, _) = device(&p, "laptop"); + let edge = setup(&echo, &p, &[&phone_pem]).await; + let req = Req::get("locked.test", "/"); + let r = + client::https_with_cert(edge.https, "locked.test", edge.roots(), &laptop, &req).await; + assert!(r.is_err(), "unlisted device got in: {r:?}"); + let r = + client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await; + assert_eq!(r.unwrap().status, 200); + + // Revoke the phone: control rewrites the list and reloads edge. + std::fs::write(edge.dir.join("certs/domi-devices.pem"), "").unwrap(); + let r = edge.admin("POST", "/v1/reload", None).await; + assert_eq!(r.status, 200, "{}\n{}", r.text, edge.stderr()); + let r = + client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await; + assert!(r.is_err(), "revoked device got in: {r:?}"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn hosts_without_device_certs_never_ask_for_one() { + let echo = Echo::start("app").await; + let p = pki(); + let (_, phone_pem) = device(&p, "phone"); + let edge = setup(&echo, &p, &[&phone_pem]).await; + // A client holding an untrusted certificate is not asked for it on the open host, + // so the handshake succeeds. + let fake = self_signed("someone"); + for c in [fake.clone(), tls12(&fake)] { + let r = client::https_with_cert( + edge.https, + "open.test", + edge.roots(), + &c, + &Req::get("open.test", "/"), + ) + .await + .unwrap_or_else(|e| panic!("tls12 {}: {e}\n{}", c.tls12_only, edge.stderr())); + assert_eq!(r.status, 200); + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_missing_allow_list_refuses_the_config() { + // edge never serves a device host it cannot check. + let echo = Echo::start("app").await; + let mut e = crate::common::spawn(EdgeSpec { + hosts: vec![host_file( + "locked.test", + &format!("upstreams = [\"{}\"]\ndevice_certs = true\n", echo.url()), + )], + ..Default::default() + }); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while e.exited().is_none() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + assert!( + e.exited().is_some_and(|s| !s.success()), + "edge must refuse to start: {}", + e.stderr() + ); + } +} diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index f3de227..acc2914 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -265,3 +265,49 @@ pub async fn websocket( .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "websocket timed out"))? } + +/// A client identity for mTLS: a PEM chain (leaf first) and its PEM private key. +#[derive(Debug, Clone)] +pub struct ClientCert { + pub chain_pem: String, + pub key_pem: String, + /// Offer only TLS 1.2 (client certificates take a different path there). + pub tls12_only: bool, +} + +/// One request over a fresh TLS connection that presents `cert` if the server asks for one. +pub async fn https_with_cert( + addr: SocketAddr, + sni: &str, + roots: Arc, + cert: &ClientCert, + req: &Req, +) -> io::Result { + use rustls_pki_types::pem::PemObject; + use rustls_pki_types::{CertificateDer, PrivateKeyDer}; + crate::tls::install_crypto(); + let chain: Vec> = + CertificateDer::pem_slice_iter(cert.chain_pem.as_bytes()) + .collect::>() + .map_err(other)?; + let key = PrivateKeyDer::from_pem_slice(cert.key_pem.as_bytes()).map_err(other)?; + let versions: &[&rustls::SupportedProtocolVersion] = if cert.tls12_only { + &[&rustls::version::TLS12] + } else { + rustls::DEFAULT_VERSIONS + }; + let mut cfg = rustls::ClientConfig::builder_with_protocol_versions(versions) + .with_root_certificates(roots) + .with_client_auth_cert(chain, key) + .map_err(other)?; + cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; + let connector = TlsConnector::from(Arc::new(cfg)); + tokio::time::timeout(TIMEOUT, async { + let tcp = TcpStream::connect(addr).await?; + let name = ServerName::try_from(sni.to_owned()).map_err(other)?; + let s = connector.connect(name, tcp).await?; + send(s, req).await + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} -- 2.53.0 From 3d8f524d001bc8d98efb1ae5c19fd16dc03b0c20 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:49:32 +0100 Subject: [PATCH 06/34] [edge] Device certificates: mTLS on hosts with device_certs only (asked per SNI), chain to the Domi CA bundle and the allow list in the handshake, checked again per request; 403 without one --- crates/edge/src/lib.rs | 1 + crates/edge/src/proxy.rs | 20 ++++ crates/edge/src/runtime.rs | 35 +++++++ crates/edge/src/shared.rs | 6 ++ crates/edge/src/tls.rs | 207 ++++++++++++++++++++++++++++++++++++- 5 files changed, 265 insertions(+), 4 deletions(-) diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 66d4ea5..7d714bb 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -126,6 +126,7 @@ pub fn server(shared: Arc, opts: &Options) -> Result reason: e.to_string(), })?; tls.set_cert_resolver(shared.certs.clone()); + tls.set_client_cert_verifier(shared.devices.clone()); tls.enable_h2(); https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 6b07927..112677b 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -137,6 +137,13 @@ impl ProxyHttp for EdgeProxy { }; ctx.host = Some(host.clone()); + if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) { + // No certificate on this connection (one that is presented but not allowed never + // gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream. + respond_empty(session, 403).await?; + return Ok(true); + } + let mut shared_access = false; if !host.cfg.share_links { share::strip_any_token(session)?; @@ -412,6 +419,19 @@ impl EdgeProxy { } } +/// Did this connection present a device certificate that the current config allows? The +/// handshake already checked the chain and the list; this checks again against the runtime +/// serving the request, so a revocation also ends requests on connections made before it. +fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool { + let Some(trust) = rt.device_trust.as_ref() else { + return false; + }; + session + .digest() + .and_then(|d| d.ssl_digest.as_ref()) + .is_some_and(|s| !s.cert_digest.is_empty() && trust.allows(&s.cert_digest)) +} + pub fn contains(hay: &[u8], needle: &[u8]) -> bool { !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) } diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 952da7d..a5d1c07 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -118,6 +118,8 @@ pub struct Runtime { pub file_cert_expiry: HashMap, /// Loaded when any host has share links. pub share_key: Option>, + /// Loaded when any host has `device_certs`. + pub device_trust: Option>, /// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was /// built from a parsed config. pub sha256: String, @@ -400,6 +402,38 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result = cfg + .hosts + .iter() + .filter(|h| h.device_certs) + .map(|h| h.hostname.clone()) + .collect(); + let device_trust = match (&cfg.device_certs, device_hosts.is_empty()) { + (_, true) => None, + (None, false) => { + return Err(EdgeError::Config { + path: PathBuf::from(""), + message: "a host needs device certificates but the config names no CA bundle" + .into(), + }); + } + (Some(dc), false) => { + let read = |p: &str| { + std::fs::read(p).map_err(|source| EdgeError::Read { + path: PathBuf::from(p), + source, + }) + }; + let trust = + crate::tls::DeviceTrust::new(&read(&dc.ca)?, &read(&dc.allow)?, device_hosts) + .map_err(|message| EdgeError::Config { + path: PathBuf::from(&dc.ca), + message, + })?; + Some(Arc::new(trust)) + } + }; + let forward_auth = match &cfg.forward_auth { Some(fa) => Some(ForwardAuthRt { upstream: upstream(&fa.upstream)?, @@ -438,6 +472,7 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result, pub certs: Arc, + /// The listener's device-certificate check; its trust follows the runtime. + pub devices: Arc, generation: AtomicU64, changed: tokio::sync::watch::Sender, trial: Mutex>, @@ -133,10 +135,13 @@ impl Shared { }; let certs = Arc::new(CertStore::default()); certs.replace_files(rt.file_certs.clone()); + let devices = Arc::new(crate::tls::DeviceVerifier::default()); + devices.replace(rt.device_trust.clone()); let (changed, _) = tokio::sync::watch::channel(1); let s = Arc::new(Shared { current: ArcSwap::from_pointee(rt), certs, + devices, generation: AtomicU64::new(1), changed, trial: Mutex::new(None), @@ -182,6 +187,7 @@ impl Shared { fn install(&self, rt: Arc) { self.certs.replace_files(rt.file_certs.clone()); + self.devices.replace(rt.device_trust.clone()); self.current.store(rt); self.generation.fetch_add(1, Ordering::SeqCst); self.notify(); diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 68e17f5..30a2809 100644 --- a/crates/edge/src/tls.rs +++ b/crates/edge/src/tls.rs @@ -5,10 +5,11 @@ //! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals) //! without touching connections in flight. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use arc_swap::ArcSwap; +use rustls::server::danger::ClientCertVerifier; use rustls::server::{ClientHello, ResolvesServerCert}; use rustls::sign::CertifiedKey; use rustls_pki_types::pem::PemObject; @@ -48,10 +49,14 @@ impl ResolvesServerCert for CertStore { fn resolve(&self, hello: ClientHello<'_>) -> Option> { // No SNI or an unknown name: no certificate, the handshake fails (as with Caddy). let name = hello.server_name()?.to_ascii_lowercase(); - if let Some(k) = self.files.load().get(&name) { - return Some(k.clone()); + let found = match self.files.load().get(&name) { + Some(k) => Some(k.clone()), + None => self.certs.load().get(&name).cloned(), + }; + if found.is_some() { + set_hello_sni(&name); } - self.certs.load().get(&name).cloned() + found } } @@ -77,3 +82,197 @@ pub fn not_after(cert_pem: &[u8]) -> Option { let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?; Some(cert.validity().not_after.timestamp()) } + +// ------------------------------------------------------------------ device certificates + +thread_local! { + /// The server name of the handshake this thread is working on, set by + /// [`CertStore::resolve`]. rustls calls the certificate resolver and then, in the same + /// call on the same thread, asks the client verifier whether to request a certificate; + /// this is how a request goes out only for hosts with `device_certs` (rustls's verifier + /// has no per-name hook). Taken (cleared) when read. + static HELLO_SNI: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn set_hello_sni(name: &str) { + HELLO_SNI.with(|s| *s.borrow_mut() = Some(name.to_owned())); +} + +fn take_hello_sni() -> Option { + HELLO_SNI.with(|s| s.borrow_mut().take()) +} + +/// What one config says about device certificates. +pub struct DeviceTrust { + inner: Arc, + /// SHA-256 of every allowed device certificate (DER). + allow: HashSet<[u8; 32]>, + /// Hosts that ask for a device certificate. + hosts: HashSet, +} + +impl std::fmt::Debug for DeviceTrust { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DeviceTrust") + .field("allowed", &self.allow.len()) + .field("hosts", &self.hosts) + .finish() + } +} + +pub fn sha256(der: &[u8]) -> [u8; 32] { + let d = ring::digest::digest(&ring::digest::SHA256, der); + let mut out = [0u8; 32]; + out.copy_from_slice(d.as_ref()); + out +} + +impl DeviceTrust { + /// From the CA bundle and allow list control wrote (PEM). An empty allow list is valid + /// (no device gets in); an empty or unreadable CA bundle is not. + pub fn new(ca_pem: &[u8], allow_pem: &[u8], hosts: HashSet) -> Result { + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca_pem) { + let c = c.map_err(|e| format!("cannot parse the device CA bundle: {e}"))?; + roots + .add(c) + .map_err(|e| format!("the device CA bundle has an unusable certificate: {e}"))?; + } + if roots.is_empty() { + return Err("the device CA bundle has no certificate".into()); + } + let mut allow = HashSet::new(); + for c in CertificateDer::pem_slice_iter(allow_pem) { + let c = c.map_err(|e| format!("cannot parse the device allow list: {e}"))?; + allow.insert(sha256(c.as_ref())); + } + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let inner = + rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider) + .allow_unauthenticated() + .build() + .map_err(|e| format!("cannot build the device certificate check: {e}"))?; + Ok(DeviceTrust { + inner, + allow, + hosts, + }) + } + + pub fn allows(&self, cert_sha256: &[u8]) -> bool { + <[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d)) + } +} + +/// The listener's client verifier. Lives as long as the process; each config brings its own +/// [`DeviceTrust`] (none when no host needs device certificates). +#[derive(Debug)] +pub struct DeviceVerifier { + trust: ArcSwap>>, + /// CA names for the certificate request. rustls wants a borrowed slice, so each new set + /// is leaked once; it changes only when the intermediate does (about once a year). + hints: std::sync::RwLock<&'static [rustls::DistinguishedName]>, +} + +impl Default for DeviceVerifier { + fn default() -> Self { + DeviceVerifier { + trust: ArcSwap::from_pointee(None), + hints: std::sync::RwLock::new(&[]), + } + } +} + +impl DeviceVerifier { + pub fn replace(&self, t: Option>) { + if let Some(t) = &t { + let new = t.inner.root_hint_subjects(); + if let Ok(mut h) = self.hints.write() + && !same_names(&h, new) + { + *h = Box::leak(new.to_vec().into_boxed_slice()); + } + } + self.trust.store(Arc::new(t)); + } + + pub fn current(&self) -> Option> { + self.trust.load().as_ref().clone() + } +} + +fn no_devices() -> rustls::Error { + rustls::Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure) +} + +impl ClientCertVerifier for DeviceVerifier { + fn offer_client_auth(&self) -> bool { + let Some(t) = self.current() else { + let _ = take_hello_sni(); + return false; + }; + match take_hello_sni() { + Some(name) => t.hosts.contains(&name), + // Called once per connection before the hello is read: say yes, so rustls keeps + // what it needs in case the host asks; the real answer comes after the hello. + None => true, + } + } + + fn client_auth_mandatory(&self) -> bool { + // A missing certificate is a 403 from the proxy, like Caddy's route, not a failed + // handshake. + false + } + + fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] { + // So a browser offers only Domi device certificates in its picker. + self.hints.read().map(|h| *h).unwrap_or(&[]) + } + + fn verify_client_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + now: rustls_pki_types::UnixTime, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_client_cert(end_entity, intermediates, now)?; + if !t.allows(&sha256(end_entity.as_ref())) { + return Err(rustls::Error::InvalidCertificate( + rustls::CertificateError::Revoked, + )); + } + Ok(rustls::server::danger::ClientCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_tls12_signature(message, cert, dss) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_tls13_signature(message, cert, dss) + } + + fn supported_verify_schemes(&self) -> Vec { + rustls::crypto::ring::default_provider() + .signature_verification_algorithms + .supported_schemes() + } +} + +fn same_names(a: &[rustls::DistinguishedName], b: &[rustls::DistinguishedName]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.as_ref() == y.as_ref()) +} -- 2.53.0 From a5190acc3ba433e507d33817ee8008331825ddeb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:55:37 +0100 Subject: [PATCH 07/34] [edge] Device certificates as Caddy does them: no certificate on a device host fails the handshake, a Host other than the SNI name is 421; diff corpus gains six device cases --- Cargo.lock | 1 + crates/edge/src/lib.rs | 9 +- crates/edge/src/proxy.rs | 19 ++++ crates/edge/src/tls.rs | 27 ++++- crates/edge/tests/device_certs.rs | 12 +-- tests/diff/Cargo.toml | 1 + tests/diff/src/lib.rs | 160 +++++++++++++++++++++++++++++- 7 files changed, 213 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f2954be..0cd06e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1102,6 +1102,7 @@ dependencies = [ "ianitor-core", "ianitor-edge", "ianitor-testkit", + "rcgen", "rustls", "serde_json", "tokio", diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 7d714bb..c4da774 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -121,10 +121,11 @@ pub fn server(shared: Arc, opts: &Options) -> Result connector: Connector::new(None), }, ); - let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen { - address: rt.cfg.https_listen.clone(), - reason: e.to_string(), - })?; + let mut tls = + TlsSettings::with_callbacks(Box::new(tls::SniRecorder)).map_err(|e| EdgeError::Listen { + address: rt.cfg.https_listen.clone(), + reason: e.to_string(), + })?; tls.set_cert_resolver(shared.certs.clone()); tls.set_client_cert_verifier(shared.devices.clone()); tls.enable_h2(); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 112677b..a69f400 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -131,6 +131,13 @@ impl ProxyHttp for EdgeProxy { let rt = self.shared.current(); ctx.rt = Some(rt.clone()); ctx.host_header = host_header(session.req_header()); + if rt.device_trust.is_some() && sni_mismatch(session, &hostname(&ctx.host_header)) { + // Like Caddy once client certificates are configured: a request for another host + // than the one the TLS connection was opened for is refused, so a connection + // that was never asked for a certificate cannot reach a device host. + respond_empty(session, 421).await?; + return Ok(true); + } let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else { respond_empty(session, 404).await?; return Ok(true); @@ -419,6 +426,18 @@ impl EdgeProxy { } } +/// Was this TLS connection opened (by SNI) for another host than the request names? +fn sni_mismatch(session: &Session, host: &str) -> bool { + let Some(s) = session.digest().and_then(|d| d.ssl_digest.as_ref()) else { + return false; + }; + match s.extension.get::() { + Some(crate::tls::ConnSni(Some(sni))) => sni != host, + // TLS without a recorded name: refuse rather than guess. + _ => true, + } +} + /// Did this connection present a device certificate that the current config allows? The /// handshake already checked the chain and the list; this checks again against the runtime /// serving the request, so a revocation also ends requests on connections made before it. diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 30a2809..51e345c 100644 --- a/crates/edge/src/tls.rs +++ b/crates/edge/src/tls.rs @@ -220,9 +220,10 @@ impl ClientCertVerifier for DeviceVerifier { } fn client_auth_mandatory(&self) -> bool { - // A missing certificate is a 403 from the proxy, like Caddy's route, not a failed - // handshake. - false + // Only asked when a certificate was requested, i.e. on a device host: there a + // handshake without one fails, as with Caddy (its allow-list check refuses an empty + // certificate list in the handshake too). + self.current().is_some() } fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] { @@ -276,3 +277,23 @@ impl ClientCertVerifier for DeviceVerifier { fn same_names(a: &[rustls::DistinguishedName], b: &[rustls::DistinguishedName]) -> bool { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.as_ref() == y.as_ref()) } + +/// The server name a TLS connection was opened for, kept in the connection's digest so the +/// proxy can compare it with the `Host` header. +#[derive(Debug, Clone)] +pub struct ConnSni(pub Option); + +/// Records [`ConnSni`] when a handshake completes. +pub struct SniRecorder; + +#[async_trait::async_trait] +impl pingora::listeners::TlsAccept for SniRecorder { + async fn handshake_complete_callback( + &self, + tls: &pingora::protocols::tls::TlsRef, + ) -> Option> { + Some(Arc::new(ConnSni( + tls.server_name().map(|s| s.to_ascii_lowercase()), + ))) + } +} diff --git a/crates/edge/tests/device_certs.rs b/crates/edge/tests/device_certs.rs index 55f24de..29eb9a9 100644 --- a/crates/edge/tests/device_certs.rs +++ b/crates/edge/tests/device_certs.rs @@ -140,7 +140,7 @@ mod unix { } #[tokio::test(flavor = "multi_thread")] - async fn no_certificate_is_a_403_and_never_reaches_the_upstream() { + async fn no_certificate_is_refused_and_never_reaches_the_upstream() { let echo = Echo::start("app").await; let p = pki(); let (_, phone_pem) = device(&p, "phone"); @@ -151,11 +151,11 @@ mod unix { edge.roots(), &Req::get("locked.test", "/"), ) - .await - .unwrap(); - assert_eq!(r.status, 403); + .await; + assert!(r.is_err(), "no certificate got in: {r:?}"); assert!(echo.requests().is_empty()); - // The Host header cannot move a certificate-less connection onto the locked host. + // The Host header cannot move a certificate-less connection onto the locked host: + // 421, as Caddy answers once client certificates are configured. let r = client::https( edge.https, "open.test", @@ -164,7 +164,7 @@ mod unix { ) .await .unwrap(); - assert_ne!(r.status, 200); + assert_eq!(r.status, 421); assert!(echo.requests().is_empty()); } diff --git a/tests/diff/Cargo.toml b/tests/diff/Cargo.toml index bb43b75..be876f6 100644 --- a/tests/diff/Cargo.toml +++ b/tests/diff/Cargo.toml @@ -14,6 +14,7 @@ ianitor-testkit.workspace = true tokio.workspace = true serde_json.workspace = true rustls.workspace = true +rcgen.workspace = true [dev-dependencies] ianitor-control = { path = "../../crates/control" } diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index debfd83..022efbf 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -113,6 +113,10 @@ impl Env { "rr.test", &format!("upstreams = [\"{}\", \"{}\"]\n", rr_a.url(), rr_b.url()), ), + host( + "device.test", + &format!("upstreams = [\"{}\"]\ndevice_certs = true\n", app.url()), + ), ]; let sources: Vec = hosts .iter() @@ -145,6 +149,17 @@ impl Env { std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap(); } std::fs::write(dir.join("creds/api_key"), format!("{SECRET}\n")).unwrap(); + let d = devices(); + std::fs::write( + dir.join(&format!("certs/{}", compile::DEVICE_CA_FILE)), + &d.ca_pem, + ) + .unwrap(); + std::fs::write( + dir.join(&format!("certs/{}", compile::DEVICE_ALLOW_FILE)), + &d.allow_pem, + ) + .unwrap(); Env { dir, ca, @@ -294,6 +309,12 @@ pub enum Action { sni: &'static str, req: Req, }, + /// HTTPS presenting a client certificate when asked. + HttpsDevice { + sni: &'static str, + req: Req, + who: Device, + }, Http { req: Req, }, @@ -578,6 +599,34 @@ pub fn corpus() -> Vec { ), https("round robin 1", "rr.test", Req::get("rr.test", "/")), https("round robin 2", "rr.test", Req::get("rr.test", "/")), + device("no device certificate", "device.test", Device::None), + device( + "Domi device certificate on the allow list", + "device.test", + Device::Allowed, + ), + device( + "Domi device certificate not on the allow list", + "device.test", + Device::Unlisted, + ), + device( + "self-signed certificate with a device's subject", + "device.test", + Device::SelfSigned, + ), + device( + "client certificate on a host that does not ask for one", + "plain.test", + Device::SelfSigned, + ), + Case { + name: "Host header naming the device host on another connection", + action: Action::Https { + sni: "plain.test", + req: Req::get("device.test", "/"), + }, + }, ] } @@ -644,6 +693,22 @@ pub async fn run_case(case: &Case, t: &Target, roots: Arc) -> Obs Action::Https { sni, req } => client::https(t.https, sni, roots, req) .await .map_or_else(failed, |r| observe(&r, t)), + Action::HttpsDevice { sni, req, who } => { + let answer = match who { + Device::None => client::https(t.https, sni, roots, req).await, + _ => client::https_with_cert(t.https, sni, roots, &devices().cert(*who), req).await, + }; + match answer { + Ok(r) => observe(&r, t), + // The two TLS stacks word their alerts differently; a refused handshake is + // what is compared (495, nginx's "SSL certificate error", as a marker). + Err(_) => Observation { + status: 495, + headers: BTreeMap::new(), + body: "handshake refused".into(), + }, + } + } Action::Http { req } => client::http(t.http, req) .await .map_or_else(failed, |r| observe(&r, t)), @@ -764,9 +829,9 @@ pub const KNOWN_DIVERGENCES: &[Divergence] = &[ rule: Rule::Status { case: "absolute-form target, other host", ianitor: 400, - caddy: 404, + caddy: 421, }, - reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target (404 here)", + reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target, which is not the SNI name (421 once a host checks device certificates; 404 without)", }, Divergence { id: "KD-9", @@ -908,7 +973,9 @@ fn short(o: &Observation) -> Observation { /// The host a case is about (its SNI, or the Host header of plain-HTTP cases). pub fn case_host(case: &Case) -> String { match &case.action { - Action::Https { sni, .. } | Action::Websocket { sni, .. } => (*sni).to_owned(), + Action::Https { sni, .. } + | Action::HttpsDevice { sni, .. } + | Action::Websocket { sni, .. } => (*sni).to_owned(), Action::Http { req } => req .headers .iter() @@ -1008,3 +1075,90 @@ fn differences(i: &Observation, c: &Observation) -> Vec { } out } + +/// Which client certificate a device case presents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Device { + /// No client certificate at all. + None, + /// Issued by the Domi intermediate and on the allow list. + Allowed, + /// Issued by the Domi intermediate, not on the allow list (revoked or never listed). + Unlisted, + /// Self-signed, with the same subject as the allowed one. + SelfSigned, +} + +fn device(name: &'static str, host: &'static str, who: Device) -> Case { + Case { + name, + action: Action::HttpsDevice { + sni: host, + req: Req::get(host, "/"), + who, + }, + } +} + +/// One Domi PKI per test process, shared by every [`Env`] (each writes its files). +pub struct DevicePki { + pub ca_pem: String, + pub allow_pem: String, + allowed: client::ClientCert, + unlisted: client::ClientCert, + self_signed: client::ClientCert, +} + +impl DevicePki { + pub fn cert(&self, who: Device) -> client::ClientCert { + match who { + Device::Allowed => self.allowed.clone(), + Device::Unlisted => self.unlisted.clone(), + Device::SelfSigned | Device::None => self.self_signed.clone(), + } + } +} + +pub fn devices() -> &'static DevicePki { + use ianitor_core::pki; + static PKI: std::sync::OnceLock = std::sync::OnceLock::new(); + PKI.get_or_init(|| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + let (root, root_key) = pki::create_root(now).unwrap(); + let k = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); + let int_pem = pki::sign_intermediate(&root, &root_key, &csr, now).unwrap(); + let int = pki::Intermediate::new(&int_pem, k).unwrap(); + let cc = |i: pki::Issued| client::ClientCert { + chain_pem: i.chain_pem, + key_pem: i.key_pem, + tls12_only: false, + }; + let phone = pki::issue_device(&int, "phone", now).unwrap(); + let allow_pem = phone.cert_pem.clone(); + let unlisted = pki::issue_device(&int, "laptop", now).unwrap(); + let fake_key = rcgen::KeyPair::generate().unwrap(); + let mut p = rcgen::CertificateParams::default(); + let mut dn = rcgen::DistinguishedName::new(); + dn.push(rcgen::DnType::CommonName, "phone"); + dn.push(rcgen::DnType::OrganizationName, pki::ORG); + dn.push(rcgen::DnType::OrganizationalUnitName, "Domi devices"); + p.distinguished_name = dn; + p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; + let fake = p.self_signed(&fake_key).unwrap(); + DevicePki { + ca_pem: int.cert_pem().to_owned(), + allow_pem, + allowed: cc(phone), + unlisted: cc(unlisted), + self_signed: client::ClientCert { + chain_pem: fake.pem(), + key_pem: fake_key.serialize_pem(), + tls12_only: false, + }, + } + }) +} -- 2.53.0 From 211b851c3e561a0c168c84058ccaba8cdf0a5a5f Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:11:05 +0100 Subject: [PATCH 08/34] [control] Tests first: Domi CA flows through the API (offline-signed intermediate, domi host chains, device approval by code, one-time install, revocation, no root key) and UI sign-in that refuses a forged Remote-User (red) --- Cargo.lock | 482 ++++++++++++- crates/control/Cargo.toml | 7 +- crates/control/src/config.rs | 80 +++ crates/control/src/dev.rs | 3 + crates/control/src/edgelink.rs | 7 + crates/control/src/engine.rs | 49 +- crates/control/src/lib.rs | 3 + crates/control/src/messages.rs | 82 +++ crates/control/src/pki.rs | 1058 ++++++++++++++++++++++++++++ crates/control/src/pki_ctl.rs | 207 ++++++ crates/control/src/switch.rs | 400 +++++++++++ crates/control/tests/common/mod.rs | 7 +- crates/control/tests/pki.rs | 421 +++++++++++ crates/control/tests/ui_auth.rs | 194 +++++ crates/core/src/pki.rs | 9 + tests/diff/tests/apply_sequence.rs | 3 + tests/support/src/more.rs | 3 + 17 files changed, 3005 insertions(+), 10 deletions(-) create mode 100644 crates/control/src/pki.rs create mode 100644 crates/control/src/pki_ctl.rs create mode 100644 crates/control/src/switch.rs create mode 100644 crates/control/tests/pki.rs create mode 100644 crates/control/tests/ui_auth.rs diff --git a/Cargo.lock b/Cargo.lock index 0cd06e5..1a4ccad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,41 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ctutils", + "ghash", +] + [[package]] name = "ahash" version = "0.8.12" @@ -281,6 +316,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bit-vec" version = "0.9.1" @@ -302,7 +343,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -314,6 +355,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "brotli" version = "3.5.0" @@ -352,6 +411,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.11.1" @@ -376,6 +444,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -385,6 +464,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clap" version = "4.6.7" @@ -434,6 +524,24 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cms" +version = "0.3.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e99ff55bfffd019bf15e3f0d5edef2ca1e3af5ade276ed100e3c0c3455050c2" +dependencies = [ + "const-oid", + "der", + "spki", + "x509-cert", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -459,6 +567,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-random" version = "0.1.18" @@ -505,6 +619,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -514,6 +634,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.4" @@ -554,6 +683,33 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "daemonix" version = "0.1.0" @@ -591,6 +747,19 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "der-parser" version = "9.0.0" @@ -619,6 +788,17 @@ dependencies = [ "rusticata-macros", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -636,17 +816,38 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "des" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a" +dependencies = [ + "cipher", +] + [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -706,6 +907,12 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.11" @@ -879,6 +1086,16 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval", ] [[package]] @@ -947,6 +1164,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -992,6 +1218,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -1064,8 +1299,11 @@ dependencies = [ "ianitor-edge", "ianitor-testkit", "log", + "p12-keystore", + "qrcode", "rcgen", "ring", + "rpassword", "rustls", "serde", "serde_json", @@ -1281,6 +1519,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "instant-acme" version = "0.8.5" @@ -1613,6 +1861,29 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "p12-keystore" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2ed4fa0ec7ec58b657d4184680c57da9e203e97771d29a566028869a5193e0" +dependencies = [ + "cbc", + "cms", + "der", + "des", + "hex", + "hmac", + "pkcs12", + "pkcs5", + "pkcs8", + "rand 0.10.3", + "rc2", + "sha1 0.11.0", + "sha2", + "thiserror 2.0.21", + "x509-parser 0.18.1", +] + [[package]] name = "parking" version = "2.2.1" @@ -1642,6 +1913,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + [[package]] name = "pem" version = "4.0.0" @@ -1652,6 +1933,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1942,12 +2232,64 @@ dependencies = [ "tokio", ] +[[package]] +name = "pkcs12" +version = "0.2.0-rc.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca" +dependencies = [ + "cms", + "const-oid", + "der", + "digest 0.11.3", + "spki", + "x509-cert", + "zeroize", +] + +[[package]] +name = "pkcs5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" +dependencies = [ + "aes", + "aes-gcm", + "cbc", + "der", + "pbkdf2", + "scrypt", + "sha2", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.1", + "universal-hash", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1994,6 +2336,12 @@ dependencies = [ "yansi", ] +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quote" version = "1.0.47" @@ -2036,6 +2384,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -2074,6 +2433,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rc2" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe" +dependencies = [ + "cipher", +] + [[package]] name = "rcgen" version = "0.14.10" @@ -2159,6 +2533,27 @@ dependencies = [ "serde", ] +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rust_decimal" version = "1.43.0" @@ -2295,6 +2690,16 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" +dependencies = [ + "cfg-if", + "cipher", +] + [[package]] name = "same-file" version = "1.0.6" @@ -2319,6 +2724,18 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0" +dependencies = [ + "cfg-if", + "pbkdf2", + "salsa20", + "sha2", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -2473,8 +2890,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2531,6 +2970,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2931,7 +3380,7 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "sha1", + "sha1 0.10.7", "thiserror 2.0.21", ] @@ -2962,6 +3411,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -3203,6 +3662,17 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid", + "der", + "spki", +] + [[package]] name = "x509-parser" version = "0.16.0" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3929d18..d2a3801 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -29,11 +29,16 @@ ring.workspace = true base64.workspace = true http.workspace = true bytes.workspace = true -# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3). rcgen.workspace = true +# Device certificate install files (PKCS#12) and their QR codes. +p12-keystore = "0.4" +qrcode = { version = "0.14", default-features = false, features = ["svg"] } +# The offline root CLI asks for its passphrase without echo. +rpassword = "7" [dev-dependencies] ianitor-testkit.workspace = true +p12-keystore = "0.4" ianitor-edge.workspace = true rustls.workspace = true diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index a35e23a..59a8df2 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -48,6 +48,16 @@ pub struct Config { pub compile: Compile, /// Different facts for the Caddy output (only tests need this: both engines side by side). pub compile_caddy: Option, + /// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already + /// and the certificate screens say the CA is not set up. + #[serde(default)] + pub pki: Option, + /// The web UI behind edge (sign-in through Authelia, see docs/api.md). + #[serde(default)] + pub ui: Option, + /// Switching between Pingora and the Caddy fallback at runtime. + #[serde(default)] + pub engine: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -280,3 +290,73 @@ fn empty_model() -> Option { ) .ok() } + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PkiConfig { + /// The Domi root certificate (public; may be a Nix store path). The root key is never on + /// the server. + pub root_cert: PathBuf, + /// Credential with the password that encrypts the intermediate and device keys at rest. + #[serde(default = "default_pki_password")] + pub password_credential: String, + /// How requests are approved: `manual` (`ianitor-control pki approve ` on the + /// server) until Custos can (docs/custos-ticket.md). + #[serde(default = "default_approval")] + pub approval: String, + /// PBKDF2 iterations for the keys control encrypts (only tests lower it). + #[serde(default = "default_kdf")] + pub kdf_iterations: u32, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UiConfig { + /// The admin host edge serves the UI on (a host in the routes repository with + /// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to + /// `allowed_hosts`; used for device install links. + pub hostname: Option, + /// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin + /// host. With it, a request carrying the proof is identified by its `Remote-User`. + pub proof_credential: Option, + /// The built web UI (served at `/`). + pub static_dir: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EngineConfig { + /// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit). + pub file: PathBuf, + /// `systemctl` (through the polkit rule for exactly the two units) or `none`. + #[serde(default = "default_units")] + pub units: String, + #[serde(default = "default_systemctl")] + pub systemctl: PathBuf, + #[serde(default = "default_edge_unit")] + pub edge_unit: String, + #[serde(default = "default_caddy_unit")] + pub caddy_unit: String, +} + +fn default_pki_password() -> String { + "pki-password".into() +} +fn default_approval() -> String { + "manual".into() +} +fn default_kdf() -> u32 { + ianitor_core::pki::KEY_KDF_ITERATIONS +} +fn default_units() -> String { + "systemctl".into() +} +fn default_systemctl() -> PathBuf { + PathBuf::from("systemctl") +} +fn default_edge_unit() -> String { + "ianitor-edge.service".into() +} +fn default_caddy_unit() -> String { + "caddy-fallback.service".into() +} diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 70930e6..22f43c3 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -174,6 +174,9 @@ pub async fn run(args: &[String]) -> Result<(), String> { caddy_admin: None, }, compile_caddy: None, + pki: None, + ui: None, + engine: None, }; cfg.check().map_err(|e| e.to_string())?; Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) diff --git a/crates/control/src/edgelink.rs b/crates/control/src/edgelink.rs index 5485e57..045e1f7 100644 --- a/crates/control/src/edgelink.rs +++ b/crates/control/src/edgelink.rs @@ -174,6 +174,13 @@ impl EdgeLink { Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned()) } + /// Re-read the device CA bundle and allow list (works during a trial too). + pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> { + self.call("POST", "/v1/device-certs/reload", None) + .await + .map(|_| ()) + } + pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> { self.call("POST", "/v1/share-revocations/reload", None) .await diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 19ccbeb..573484d 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -141,6 +141,12 @@ pub struct Control { pub tokens: Tokens, pub shares: Shares, pub share_key: Option, + /// The Domi CA, when `[pki]` is configured. + pub pki: Option, + /// Which engine serves (see `switch`). + pub engine: Mutex, + /// How control starts and stops the engines; `None` without `[engine]`. + pub units: Option>, records: Mutex>, queue: Mutex>, wake: Notify, @@ -151,7 +157,7 @@ pub struct Control { /// False while the pause is only in memory (paused.json could not be written). pause_saved: std::sync::atomic::AtomicBool, /// Serialises applies with share-revocation writes and recovery. - apply_lock: tokio::sync::Mutex<()>, + pub(crate) apply_lock: tokio::sync::Mutex<()>, } const MAX_RECORDS: usize = 1000; @@ -207,6 +213,21 @@ impl Control { if share_key.is_none() { log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made"); } + let keys = crate::pki::root_key_files(&cfg.state_dir); + if let Some(k) = keys.first() { + return Err(format!( + "{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.", + k.display() + )); + } + let pki = match &cfg.pki { + Some(p) => Some(crate::pki::Pki::open( + p, + &cfg.state_dir, + cfg.credential(&p.password_credential), + )?), + None => None, + }; let records: Vec = read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default(); let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default(); @@ -217,6 +238,19 @@ impl Control { repo, edge, share_key, + pki, + engine: Mutex::new(crate::switch::EngineState { + running: cfg + .engine + .as_ref() + .map(|e| crate::switch::read_engine_file(&e.file)) + .unwrap_or_else(|| "pingora".into()), + state: "running".into(), + since: now(), + target: None, + last_error: None, + }), + units: crate::switch::units_for(cfg.engine.as_ref()), records: Mutex::new(records), queue: Mutex::new(VecDeque::new()), wake: Notify::new(), @@ -228,6 +262,11 @@ impl Control { apply_lock: tokio::sync::Mutex::new(()), cfg, }); + if let Ok((_, _, m)) = c.head_model() + && let Err(f) = c.pki_prepare(&m) + { + log::error!(target: "ianitor::pki", "{}", f.reason.message); + } c.recover().await?; Ok(c) } @@ -390,6 +429,9 @@ impl Control { /// `in_worker` is false when a request is first checked: a change that the worker may /// still let through (after it retried the files) is queued rather than refused. fn paused_for(&self, change: &Change, in_worker: bool) -> Option { + if let Some(e) = self.engine_pause() { + return Some(e); + } let p = self.paused()?; if !in_worker && p.code == "control.files_unwritten" { return None; @@ -863,6 +905,11 @@ impl Control { Ok(x) => x, Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()), }; + // Domi certificates for the hosts of the new tree, before anything is committed (new + // files only: a certificate edge serves now is never replaced by a worse one). + if let Err(f) = self.pki_prepare(&plan.model) { + return self.finish(&id, "failed", Some(f.reason), Vec::new()); + } self.update(&id, |r| { r.step("compile", "done"); r.step("write", "running"); diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 683a167..3740c9c 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -14,9 +14,12 @@ pub mod engine; pub mod hostspec; pub mod logger; pub mod messages; +pub mod pki; +pub mod pki_ctl; pub mod records; pub mod repo; pub mod shares; +pub mod switch; pub mod tokens; pub mod util; diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index 945f222..ee9ba0e 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -228,6 +228,88 @@ fn template(code: &str) -> &'static str { "health.unavailable" => { "Ianitor cannot read health from {engine} right now. Traffic is not affected." } + // 3.6 PKI + "pki.waiting" => { + "Open Custos on your phone. Approve only if it shows the same code: {code}." + } + "pki.waiting.manual" => { + "Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches." + } + "pki.renew.manual" => { + "Sign this request on the offline machine (ianitor-control ca sign), check that it shows the code {code}, then install the certificate." + } + "pki.denied" => "The request was turned down. Nothing was issued.", + "pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.", + "pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.", + "pki.device_name_taken" => { + "A device with this name already has a certificate or an open request. Use another name, or revoke the old one first." + } + "pki.device_name" => "Give the device a name of 1 to 64 characters.", + "pki.device_kind" => "Choose phone, computer or app.", + "pki.issued" => "{name} has a certificate.", + "pki.bundle_used" => { + "This download was already used or has expired. Make a new one from the device's row." + } + "pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.", + "pki.renew_urgent" => { + "The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working." + } + "pki.intermediate_expired" => { + "The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed." + } + "pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.", + "pki.not_configured" => { + "The Domi certificate authority is not set up on this server. See docs/pki.md." + } + "pki.no_password" => { + "The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued." + } + "pki.wrong_password" => { + "The password for the Domi certificate keys does not open them. Check the pki-password credential." + } + "pki.no_intermediate" => { + "There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates." + } + "pki.not_our_root" => { + "This certificate was not signed by the Domi root this server trusts." + } + "pki.wrong_key" => { + "This certificate was made for another request. Sign the request shown here, then try again." + } + "pki.bad_certificate" => { + "This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now." + } + "pki.request_not_found" => "There is no such request.", + "pki.request_closed" => "This request is closed. Start a new one.", + "pki.wrong_code" => "That code does not match the request.", + "pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.", + "pki.device_not_found" => "There is no such device.", + "pki.device_not_valid" => { + "This device's certificate is revoked or expired, so it cannot be installed. Issue a new one." + } + "pki.revoked" => { + "Revoked. {name} can no longer reach hosts that need a device certificate." + } + // UI sign-in + "ui.no_proof" => { + "This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused." + } + "ui.no_user" => "The sign-in did not say who you are. Sign in again.", + // engine switch + "engine.unmanaged" => { + "This server does not let Ianitor switch engines (no engine settings in control.toml)." + } + "engine.same" => "{engine} is already serving.", + "engine.switching" => "A switch is already running. Wait for it to finish.", + "engine.busy" => "A change is being applied. Switch when it has finished.", + "engine.switched" => "{engine} is serving now.", + "engine.switch_failed" => { + "{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before." + } + "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." + } "internal" => "Something went wrong inside Ianitor control. Show details for more.", _ => "Something went wrong.", } diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs new file mode 100644 index 0000000..d68c990 --- /dev/null +++ b/crates/control/src/pki.rs @@ -0,0 +1,1058 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA on the server (ROADMAP §1.2, §3): the intermediate, the server certificates +//! of `tls = "domi"` hosts, device certificates and their install files, and the requests +//! that need an approval. +//! +//! Files, under `/pki/` (mode 0700): +//! +//! ```text +//! intermediate.crt the current intermediate (public) +//! intermediate.key its key, encrypted (IANITOR ENCRYPTED PRIVATE KEY, password from +//! the `pki-password` credential); never in plain text on disk +//! previous.crt the one before, while it is still valid (device CA bundle) +//! pending-.key the new key of an open renewal, encrypted the same way +//! requests.json approval requests (devices, renewals) +//! devices.json issued device certificates +//! devices/.key a device's key, encrypted, kept to make its install file again +//! approvals/.approve written by `ianitor-control pki approve` (the manual approval) +//! approvals/.deny written by `ianitor-control pki deny` +//! approvals/.crt the signed intermediate, from `pki install` or the API +//! ``` +//! +//! The root key is never here: control only reads the root *certificate* named in +//! control.toml, and refuses to start if a root key file appears in its state directory. +//! +//! Approvals: ROADMAP §4 says "approve in Custos". Custos has no such operation yet +//! (docs/custos-ticket.md), so until it does a request is approved on the server with the +//! match code the UI shows: `ianitor-control pki approve 47 19 83`. The intermediate is +//! signed offline (docs/pki.md). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use ianitor_core::pki::{self, Intermediate, PkiError}; +use serde::{Deserialize, Serialize}; + +use crate::config::PkiConfig; +use crate::util::{hex, random, read_json, remove_if_exists, write_atomic, write_json}; + +/// How long a device request waits for its approval. +pub const DEVICE_REQUEST_SECS: u64 = 600; +/// How long a renewal waits for the offline signature. +pub const RENEWAL_REQUEST_SECS: u64 = 7 * 86_400; +/// How long a device install link works. +pub const BUNDLE_SECS: u64 = 600; +/// Banner thresholds. +pub const DUE_DAYS: i64 = 30; +pub const URGENT_DAYS: i64 = 7; +/// Most open requests at once. +const MAX_OPEN: usize = 20; +/// Most devices with certificates (active or not) kept in the list. +const MAX_DEVICES: usize = 500; +/// Device kinds the UI offers. +pub const DEVICE_KINDS: [&str; 3] = ["phone", "computer", "app"]; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PkiFail { + /// A refusal with a stable code for the API (`pki.*`). + #[error("{0}")] + Code(&'static str), + #[error("{0}")] + Internal(String), +} + +impl From for PkiFail { + fn from(e: PkiError) -> Self { + PkiFail::Internal(e.to_string()) + } +} + +fn io(e: impl std::fmt::Display) -> PkiFail { + PkiFail::Internal(e.to_string()) +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Request { + pub id: String, + /// `device` or `intermediate`. + pub kind: String, + /// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`. + pub state: String, + pub match_code: String, + pub created_at: u64, + pub expires_at: u64, + #[serde(default)] + pub approved_at: Option, + /// Device requests: the name and kind asked for, and the device made. + #[serde(default)] + pub name: Option, + #[serde(default)] + pub device_kind: Option, + #[serde(default)] + pub device_id: Option, + /// Renewals: the CSR to sign offline. + #[serde(default)] + pub csr_pem: Option, + /// Renewals: when the new intermediate expires, once installed. + #[serde(default)] + pub not_after: Option, + /// Why it failed (plain English, no secrets). + #[serde(default)] + pub error: Option, + /// Who asked (token name or signed-in user). + #[serde(default)] + pub actor: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Device { + pub id: String, + pub name: String, + pub kind: String, + pub serial: String, + pub sha256: String, + pub cert_pem: String, + pub created_at: u64, + pub not_after: i64, + #[serde(default)] + pub revoked_at: Option, + /// Which intermediate issued it (its SHA-256). + pub issuer_sha256: String, +} + +impl Device { + pub fn state(&self, now: u64) -> &'static str { + if self.revoked_at.is_some() { + "revoked" + } else if self.not_after <= now as i64 { + "expired" + } else { + "valid" + } + } +} + +/// A one-time install file waiting to be downloaded. +struct Bundle { + device_id: String, + password: String, + expires_at: u64, +} + +/// What the main screen shows about the intermediate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IntermediateStatus { + /// `ok`, `due`, `urgent`, `expired` or `missing` (no intermediate yet). + pub state: &'static str, + pub subject: Option, + pub not_after: Option, + pub days_left: Option, + pub renewal: Option, +} + +/// What changed in one poll. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Changes { + pub devices: bool, + pub intermediate: bool, +} + +pub struct Pki { + dir: PathBuf, + root_pem: String, + password: Option>, + kdf_iterations: u32, + lock: Mutex<()>, + current: Mutex>>, + bundles: Mutex>, +} + +impl std::fmt::Debug for Pki { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Pki").field("dir", &self.dir).finish() + } +} + +fn id(prefix: &str) -> Result { + Ok(format!("{prefix}{}", hex(&random::<6>().map_err(io)?))) +} + +/// `47 19 83` from random bytes (device requests have no CSR to hash). +fn random_code() -> Result { + let b = random::<3>().map_err(io)?; + Ok(format!( + "{:02} {:02} {:02}", + b[0] % 100, + b[1] % 100, + b[2] % 100 + )) +} + +/// Digits only: `47 19 83`, `471983` and `47-19-83` are the same code. +pub fn normalise_code(c: &str) -> String { + c.chars().filter(char::is_ascii_digit).collect() +} + +/// A readable one-time password for an install file: 4 groups of 4 from 30 letters and +/// digits without look-alikes (about 78 bits). +fn bundle_password() -> Result { + const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + let b = random::<16>().map_err(io)?; + let mut s = String::new(); + for (i, x) in b.iter().enumerate() { + if i > 0 && i % 4 == 0 { + s.push('-'); + } + s.push(char::from(ALPHABET[(*x as usize) % ALPHABET.len()])); + } + Ok(s) +} + +/// Is there anything that looks like a root CA key in `dir` (recursively, shallow)? Control +/// refuses to run with one in its state directory (ROADMAP §1.2: the root is never on the +/// server). +pub fn root_key_files(dir: &Path) -> Vec { + let mut found = Vec::new(); + let mut stack = vec![(dir.to_path_buf(), 0)]; + while let Some((d, depth)) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + if p.is_dir() { + if depth < 3 { + stack.push((p, depth + 1)); + } + } else if name.starts_with("root") && (name.ends_with(".key") || name.contains("key")) { + found.push(p); + } + } + } + found +} + +impl Pki { + /// Open the CA state. The root certificate must be a CA and self-signed; the password + /// credential may be missing (then nothing can be issued, and the UI says why). + pub fn open( + cfg: &PkiConfig, + state_dir: &Path, + password: Option>, + ) -> Result { + let keys = root_key_files(state_dir); + if !keys.is_empty() { + return Err(format!( + "{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.", + keys[0].display() + )); + } + let root_pem = std::fs::read_to_string(&cfg.root_cert).map_err(|e| { + format!( + "cannot read the Domi root certificate {}: {e}", + cfg.root_cert.display() + ) + })?; + let info = + pki::inspect(&root_pem).map_err(|e| format!("{}: {e}", cfg.root_cert.display()))?; + if !info.is_ca || !pki::issued_by(&root_pem, &root_pem).unwrap_or(false) { + return Err(format!( + "{} is not a self-signed CA certificate", + cfg.root_cert.display() + )); + } + if root_pem.contains("PRIVATE KEY") { + return Err(format!( + "{} contains a private key; give control the root certificate only", + cfg.root_cert.display() + )); + } + let dir = state_dir.join("pki"); + for d in [dir.clone(), dir.join("devices"), dir.join("approvals")] { + std::fs::create_dir_all(&d) + .map_err(|e| format!("cannot create {}: {e}", d.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = if d.ends_with("approvals") { + 0o700 + } else { + 0o700 + }; + let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)); + } + } + Ok(Pki { + dir, + root_pem: pki::first_pem(&root_pem).map_err(|e| e.to_string())?, + password: password.filter(|p| !p.is_empty()), + kdf_iterations: cfg.kdf_iterations, + lock: Mutex::new(()), + current: Mutex::new(None), + bundles: Mutex::new(HashMap::new()), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn root_pem(&self) -> &str { + &self.root_pem + } + + fn password(&self) -> Result<&[u8], PkiFail> { + self.password + .as_deref() + .ok_or(PkiFail::Code("pki.no_password")) + } + + fn seal(&self, key: &pki::KeyPair) -> Result { + Ok(pki::encrypt_key_with( + key, + self.password()?, + self.kdf_iterations, + )?) + } + + fn open_key(&self, path: &Path) -> Result { + let sealed = std::fs::read_to_string(path).map_err(io)?; + pki::decrypt_key(&sealed, self.password()?).map_err(|e| match e { + PkiError::WrongPassword => PkiFail::Code("pki.wrong_password"), + other => PkiFail::Internal(other.to_string()), + }) + } + + fn guard(&self) -> Result, PkiFail> { + self.lock.lock().map_err(|_| io("pki lock")) + } + + fn requests(&self) -> Result, PkiFail> { + Ok(read_json(&self.dir.join("requests.json")) + .map_err(io)? + .unwrap_or_default()) + } + + fn save_requests(&self, r: &[Request]) -> Result<(), PkiFail> { + write_json(&self.dir.join("requests.json"), &r).map_err(io) + } + + pub fn devices(&self) -> Result, PkiFail> { + Ok(read_json(&self.dir.join("devices.json")) + .map_err(io)? + .unwrap_or_default()) + } + + fn save_devices(&self, d: &[Device]) -> Result<(), PkiFail> { + write_json(&self.dir.join("devices.json"), &d).map_err(io) + } + + // -------------------------------------------------------------- the intermediate + + /// The current intermediate, unlocked once and kept in memory. `None` before the first + /// one is installed. + pub fn intermediate(&self) -> Result>, PkiFail> { + if let Some(i) = self.current.lock().map_err(|_| io("pki"))?.as_ref() { + return Ok(Some(i.clone())); + } + let crt = self.dir.join("intermediate.crt"); + if !crt.exists() { + return Ok(None); + } + let pem = std::fs::read_to_string(&crt).map_err(io)?; + let key = self.open_key(&self.dir.join("intermediate.key"))?; + let int = Arc::new(Intermediate::new(&pem, key)?); + if !pki::issued_by(int.cert_pem(), &self.root_pem)? { + return Err(PkiFail::Code("pki.not_our_root")); + } + *self.current.lock().map_err(|_| io("pki"))? = Some(int.clone()); + Ok(Some(int)) + } + + /// The intermediate's public certificate, readable without the password. + fn intermediate_info(&self) -> Option { + let pem = std::fs::read_to_string(self.dir.join("intermediate.crt")).ok()?; + pki::inspect(&pem).ok() + } + + pub fn status(&self, now: u64) -> IntermediateStatus { + let renewal = self.requests().ok().and_then(|rs| { + rs.into_iter() + .rev() + .find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now) + }); + match self.intermediate_info() { + None => IntermediateStatus { + state: "missing", + subject: None, + not_after: None, + days_left: None, + renewal, + }, + Some(i) => { + let left = (i.not_after - now as i64).div_euclid(86_400); + let state = if i.not_after <= now as i64 { + "expired" + } else if left <= URGENT_DAYS { + "urgent" + } else if left <= DUE_DAYS { + "due" + } else { + "ok" + }; + IntermediateStatus { + state, + subject: Some(i.subject_cn), + not_after: Some(i.not_after), + days_left: Some(left.max(0)), + renewal, + } + } + } + } + + /// Start a renewal (or the first intermediate): a new key, encrypted at rest, and a CSR + /// to be signed by the root. An open renewal is returned again rather than replaced. + pub fn request_renewal(&self, now: u64, actor: &str) -> Result { + let _g = self.guard()?; + self.password()?; + let mut rs = self.requests()?; + if let Some(r) = rs + .iter() + .rev() + .find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now) + { + return Ok(r.clone()); + } + let key = pki::generate_key()?; + let (y, m, _) = ymd(now); + let cn = format!("{} {y:04}-{m:02}", pki::INTERMEDIATE_CN); + let csr = pki::intermediate_csr(&key, &cn)?; + let code = pki::match_code(&pki::csr_der(&csr)?); + let rid = id("pr_")?; + write_atomic( + &self.dir.join(format!("pending-{rid}.key")), + self.seal(&key)?.as_bytes(), + 0o600, + ) + .map_err(io)?; + let r = Request { + id: rid, + kind: "intermediate".into(), + state: "waiting".into(), + match_code: code, + created_at: now, + expires_at: now + RENEWAL_REQUEST_SECS, + approved_at: None, + name: None, + device_kind: None, + device_id: None, + csr_pem: Some(csr), + not_after: None, + error: None, + actor: actor.to_owned(), + }; + prune(&mut rs, now); + rs.push(r.clone()); + self.save_requests(&rs)?; + Ok(r) + } + + /// Install a signed intermediate for an open renewal (from `pki install` or the API). + /// Checks: signed by our root, a CA with path length 0, for the pending key, valid now. + pub fn install_intermediate( + &self, + request_id: &str, + cert_pem: &str, + now: u64, + ) -> Result { + let _g = self.guard()?; + let mut rs = self.requests()?; + let r = rs + .iter_mut() + .find(|r| r.id == request_id && r.kind == "intermediate") + .ok_or(PkiFail::Code("pki.request_not_found"))?; + if r.state != "waiting" || r.expires_at <= now { + return Err(PkiFail::Code("pki.request_closed")); + } + let first = pki::first_pem(cert_pem).map_err(|_| PkiFail::Code("pki.bad_certificate"))?; + let info = pki::inspect(&first).map_err(|_| PkiFail::Code("pki.bad_certificate"))?; + if !pki::issued_by(&first, &self.root_pem).unwrap_or(false) { + return Err(PkiFail::Code("pki.not_our_root")); + } + if !info.is_ca + || info.path_len != Some(0) + || !info.subject_cn.starts_with(pki::INTERMEDIATE_CN) + { + return Err(PkiFail::Code("pki.bad_certificate")); + } + if info.not_before > now as i64 + 300 || info.not_after <= now as i64 { + return Err(PkiFail::Code("pki.bad_certificate")); + } + let pending = self.dir.join(format!("pending-{request_id}.key")); + let key = self.open_key(&pending)?; + let int = Intermediate::new(&first, key).map_err(|e| match e { + PkiError::KeyMismatch => PkiFail::Code("pki.wrong_key"), + other => PkiFail::Internal(other.to_string()), + })?; + // Keep the old one for the device CA bundle while it is valid. + let crt = self.dir.join("intermediate.crt"); + if let Ok(old) = std::fs::read_to_string(&crt) { + write_atomic(&self.dir.join("previous.crt"), old.as_bytes(), 0o644).map_err(io)?; + } + let sealed = std::fs::read(&pending).map_err(io)?; + write_atomic(&self.dir.join("intermediate.key"), &sealed, 0o600).map_err(io)?; + write_atomic(&crt, first.as_bytes(), 0o644).map_err(io)?; + remove_if_exists(&pending).map_err(io)?; + *self.current.lock().map_err(|_| io("pki"))? = Some(Arc::new(int)); + r.state = "approved".into(); + r.approved_at = Some(now); + r.not_after = Some(info.not_after); + let out = r.clone(); + self.save_requests(&rs)?; + Ok(out) + } + + // -------------------------------------------------------------- server certificates + + /// Make sure every `tls = "domi"` host has a certificate from the current intermediate + /// with at least [`pki::SERVER_RENEW_DAYS`] left. Returns the hosts that got a new one. + /// Files: `/.crt` (leaf + intermediate, 0644), `.key` (0640). + pub fn ensure_host_certs( + &self, + hosts: &[String], + cert_dir: &Path, + now: u64, + ) -> Result, PkiFail> { + if hosts.is_empty() { + return Ok(Vec::new()); + } + let int = self + .intermediate()? + .ok_or(PkiFail::Code("pki.no_intermediate"))?; + let mut issued = Vec::new(); + for h in hosts { + let crt = cert_dir.join(format!("{h}.crt")); + let key = cert_dir.join(format!("{h}.key")); + let fine = std::fs::read_to_string(&crt).ok().is_some_and(|pem| { + pki::inspect(&pem).is_ok_and(|i| { + i.dns_names.iter().any(|n| n == h) + && i.not_after - now as i64 > i64::from(pki::SERVER_RENEW_DAYS) * 86_400 + && i.not_before <= now as i64 + 300 + }) && pki::issued_by(&pem, int.cert_pem()).unwrap_or(false) + }) && key.exists(); + if fine { + continue; + } + let leaf = pki::issue_server(&int, h, now as i64).map_err(|e| match e { + PkiError::IssuerExpired => PkiFail::Code("pki.intermediate_expired"), + other => PkiFail::Internal(other.to_string()), + })?; + // Key first: a certificate never points at a key that is not there yet. + write_atomic(&key, leaf.key_pem.as_bytes(), 0o640).map_err(io)?; + write_atomic(&crt, leaf.chain_pem.as_bytes(), 0o644).map_err(io)?; + issued.push(h.clone()); + } + Ok(issued) + } + + /// Write the device CA bundle and allow list into the certificate directory (what both + /// engines read). Returns whether either changed. + pub fn write_device_files(&self, cert_dir: &Path, now: u64) -> Result { + let mut ca = String::new(); + for f in ["intermediate.crt", "previous.crt"] { + if let Ok(pem) = std::fs::read_to_string(self.dir.join(f)) + && pki::inspect(&pem).is_ok_and(|i| i.not_after > now as i64) + { + ca.push_str(&pem); + } + } + if ca.is_empty() { + // Edge and Caddy refuse an empty bundle; the root keeps the bundle parseable + // while no intermediate exists, and the empty allow list still lets no one in. + ca.push_str(&self.root_pem); + } + let allow: String = self + .devices()? + .iter() + .filter(|d| d.state(now) == "valid") + .map(|d| d.cert_pem.as_str()) + .collect(); + let mut changed = false; + for (name, text) in [ + (ianitor_core::compile::DEVICE_CA_FILE, ca), + (ianitor_core::compile::DEVICE_ALLOW_FILE, allow), + ] { + let p = cert_dir.join(name); + if std::fs::read_to_string(&p).ok().as_deref() != Some(text.as_str()) { + write_atomic(&p, text.as_bytes(), 0o644).map_err(io)?; + changed = true; + } + } + Ok(changed) + } + + // -------------------------------------------------------------- devices + + pub fn request_device( + &self, + name: &str, + kind: &str, + now: u64, + actor: &str, + ) -> Result { + let _g = self.guard()?; + let name = name.trim(); + if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) { + return Err(PkiFail::Code("pki.device_name")); + } + if !DEVICE_KINDS.contains(&kind) { + return Err(PkiFail::Code("pki.device_kind")); + } + if self.intermediate_info().is_none() { + return Err(PkiFail::Code("pki.no_intermediate")); + } + self.password()?; + let taken = |n: &str| n.to_lowercase() == name.to_lowercase(); + if self + .devices()? + .iter() + .any(|d| d.state(now) == "valid" && taken(&d.name)) + { + return Err(PkiFail::Code("pki.device_name_taken")); + } + let mut rs = self.requests()?; + prune(&mut rs, now); + if rs.iter().any(|r| { + r.kind == "device" && r.state == "waiting" && r.name.as_deref().is_some_and(taken) + }) { + return Err(PkiFail::Code("pki.device_name_taken")); + } + if rs.iter().filter(|r| r.state == "waiting").count() >= MAX_OPEN { + return Err(PkiFail::Code("pki.too_many_requests")); + } + // A code no other open request has, so `pki approve ` is never ambiguous. + let mut code = random_code()?; + while rs + .iter() + .any(|r| r.state == "waiting" && normalise_code(&r.match_code) == normalise_code(&code)) + { + code = random_code()?; + } + let r = Request { + id: id("pr_")?, + kind: "device".into(), + state: "waiting".into(), + match_code: code, + created_at: now, + expires_at: now + DEVICE_REQUEST_SECS, + approved_at: None, + name: Some(name.to_owned()), + device_kind: Some(kind.to_owned()), + device_id: None, + csr_pem: None, + not_after: None, + error: None, + actor: actor.to_owned(), + }; + rs.push(r.clone()); + self.save_requests(&rs)?; + Ok(r) + } + + pub fn request(&self, id: &str, now: u64) -> Result, PkiFail> { + Ok(self + .requests()? + .into_iter() + .find(|r| r.id == id) + .map(|mut r| { + if r.state == "waiting" && r.expires_at <= now { + r.state = "expired".into(); + } + r + })) + } + + pub fn cancel(&self, id: &str) -> Result, PkiFail> { + let _g = self.guard()?; + let mut rs = self.requests()?; + let Some(r) = rs.iter_mut().find(|r| r.id == id) else { + return Ok(None); + }; + if r.state == "waiting" { + r.state = "cancelled".into(); + if r.kind == "intermediate" { + remove_if_exists(&self.dir.join(format!("pending-{id}.key"))).map_err(io)?; + } + } + let out = r.clone(); + self.save_requests(&rs)?; + Ok(Some(out)) + } + + /// Act on approvals and expiries. Called every couple of seconds by control. + pub fn poll(&self, now: u64) -> Result { + let mut changes = Changes::default(); + let approvals = self.dir.join("approvals"); + let ids: Vec = { + let mut v = Vec::new(); + if let Ok(rd) = std::fs::read_dir(&approvals) { + for e in rd.flatten() { + v.push(e.file_name().to_string_lossy().into_owned()); + } + } + v + }; + for f in ids { + let path = approvals.join(&f); + let Some((rid, what)) = f.rsplit_once('.') else { + let _ = remove_if_exists(&path); + continue; + }; + let rid = rid.to_owned(); + match what { + "approve" => { + let code = std::fs::read_to_string(&path).unwrap_or_default(); + let _ = remove_if_exists(&path); + if let Err(e) = self.approve_device(&rid, code.trim(), now) { + log::warn!(target: "ianitor::pki", "approval for {rid} not used: {e}"); + } else { + changes.devices = true; + } + } + "deny" => { + let _ = remove_if_exists(&path); + self.close(&rid, "denied", None)?; + } + "crt" => { + let pem = std::fs::read_to_string(&path).unwrap_or_default(); + let _ = remove_if_exists(&path); + match self.install_intermediate(&rid, &pem, now) { + Ok(_) => changes.intermediate = true, + Err(e) => { + log::warn!(target: "ianitor::pki", "intermediate for {rid} not installed: {e}"); + } + } + } + _ => { + let _ = remove_if_exists(&path); + } + } + } + // Expire what waited too long. + let _g = self.guard()?; + let mut rs = self.requests()?; + let mut dirty = false; + for r in rs.iter_mut() { + if r.state == "waiting" && r.expires_at <= now { + r.state = "expired".into(); + dirty = true; + if r.kind == "intermediate" { + let _ = remove_if_exists(&self.dir.join(format!("pending-{}.key", r.id))); + } + } + } + if dirty { + self.save_requests(&rs)?; + } + Ok(changes) + } + + fn close(&self, rid: &str, state: &str, error: Option) -> Result<(), PkiFail> { + let _g = self.guard()?; + let mut rs = self.requests()?; + if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") { + r.state = state.into(); + r.error = error; + if r.kind == "intermediate" { + let _ = remove_if_exists(&self.dir.join(format!("pending-{rid}.key"))); + } + self.save_requests(&rs)?; + } + Ok(()) + } + + /// Issue the device certificate of an approved request. The code must match. + fn approve_device(&self, rid: &str, code: &str, now: u64) -> Result { + let int = self + .intermediate()? + .ok_or(PkiFail::Code("pki.no_intermediate"))?; + let _g = self.guard()?; + let mut rs = self.requests()?; + let r = rs + .iter_mut() + .find(|r| r.id == rid && r.kind == "device") + .ok_or(PkiFail::Code("pki.request_not_found"))?; + if r.state != "waiting" || r.expires_at <= now { + return Err(PkiFail::Code("pki.request_closed")); + } + if normalise_code(code) != normalise_code(&r.match_code) { + return Err(PkiFail::Code("pki.wrong_code")); + } + let name = r.name.clone().unwrap_or_default(); + let kind = r.device_kind.clone().unwrap_or_else(|| "app".into()); + let leaf = match pki::issue_device(&int, &name, now as i64) { + Ok(l) => l, + Err(e) => { + r.state = "failed".into(); + r.error = Some(e.to_string()); + self.save_requests(&rs)?; + return Err(e.into()); + } + }; + let did = id("dv_")?; + write_atomic( + &self.dir.join(format!("devices/{did}.key")), + self.seal(&leaf.key)?.as_bytes(), + 0o600, + ) + .map_err(io)?; + let d = Device { + id: did.clone(), + name, + kind, + serial: leaf.serial_hex.clone(), + sha256: leaf.sha256_hex.clone(), + cert_pem: leaf.cert_pem.clone(), + created_at: now, + not_after: leaf.not_after, + revoked_at: None, + issuer_sha256: int.info().sha256_hex.clone(), + }; + let mut ds = self.devices()?; + ds.push(d.clone()); + // Keep the list bounded: forget the oldest revoked or expired ones first. + while ds.len() > MAX_DEVICES { + match ds.iter().position(|x| x.state(now) != "valid") { + Some(i) => { + let gone = ds.remove(i); + let _ = remove_if_exists(&self.dir.join(format!("devices/{}.key", gone.id))); + } + None => break, + } + } + self.save_devices(&ds)?; + r.state = "approved".into(); + r.approved_at = Some(now); + r.device_id = Some(did); + self.save_requests(&rs)?; + Ok(d) + } + + pub fn revoke(&self, device_id: &str, now: u64) -> Result, PkiFail> { + let _g = self.guard()?; + let mut ds = self.devices()?; + let Some(d) = ds.iter_mut().find(|d| d.id == device_id) else { + return Ok(None); + }; + if d.revoked_at.is_none() { + d.revoked_at = Some(now); + } + let out = d.clone(); + self.save_devices(&ds)?; + // The key is no longer needed: no new install file for a revoked device. + remove_if_exists(&self.dir.join(format!("devices/{device_id}.key"))).map_err(io)?; + if let Ok(mut b) = self.bundles.lock() { + b.retain(|_, x| x.device_id != device_id); + } + Ok(Some(out)) + } + + // -------------------------------------------------------------- install files + + /// A one-time install link for a device: `(token, password, expires_at)`. + pub fn make_bundle(&self, device_id: &str, now: u64) -> Result<(String, String, u64), PkiFail> { + let d = self + .devices()? + .into_iter() + .find(|d| d.id == device_id) + .ok_or(PkiFail::Code("pki.device_not_found"))?; + if d.state(now) != "valid" { + return Err(PkiFail::Code("pki.device_not_valid")); + } + if !self.dir.join(format!("devices/{device_id}.key")).exists() { + return Err(PkiFail::Code("pki.device_not_valid")); + } + let token = hex(&random::<32>().map_err(io)?); + let password = bundle_password()?; + let expires_at = now + BUNDLE_SECS; + let mut b = self.bundles.lock().map_err(|_| io("bundles"))?; + b.retain(|_, x| x.expires_at > now); + // One open link per device: a new one replaces the old. + b.retain(|_, x| x.device_id != device_id); + if b.len() >= 100 { + return Err(PkiFail::Code("pki.too_many_requests")); + } + b.insert( + token.clone(), + Bundle { + device_id: device_id.to_owned(), + password: password.clone(), + expires_at, + }, + ); + Ok((token, password, expires_at)) + } + + /// Hand out an install file once: the PKCS#12 bytes and the device name. The token is + /// gone afterwards, whatever happens. + pub fn take_bundle(&self, token: &str, now: u64) -> Result<(Vec, String), PkiFail> { + let b = { + let mut m = self.bundles.lock().map_err(|_| io("bundles"))?; + m.remove(token) + }; + let b = b.ok_or(PkiFail::Code("pki.bundle_used"))?; + if b.expires_at <= now { + return Err(PkiFail::Code("pki.bundle_used")); + } + let d = self + .devices()? + .into_iter() + .find(|d| d.id == b.device_id && d.state(now) == "valid") + .ok_or(PkiFail::Code("pki.device_not_valid"))?; + let key = self.open_key(&self.dir.join(format!("devices/{}.key", d.id)))?; + let issuer = if self + .intermediate_info() + .is_some_and(|i| i.sha256_hex == d.issuer_sha256) + { + std::fs::read_to_string(self.dir.join("intermediate.crt")).map_err(io)? + } else { + std::fs::read_to_string(self.dir.join("previous.crt")).map_err(io)? + }; + let p12 = pkcs12(&d, &key, &issuer, &self.root_pem, &b.password)?; + Ok((p12, d.name)) + } +} + +/// A PKCS#12 file with the device key and its chain (leaf, intermediate, root), encrypted +/// with AES-256 (PBES2) and a SHA-256 MAC. +fn pkcs12( + d: &Device, + key: &pki::KeyPair, + issuer_pem: &str, + root_pem: &str, + password: &str, +) -> Result, PkiFail> { + use p12_keystore::{ + Certificate, EncryptionAlgorithm, KeyStore, KeyStoreEntry, MacAlgorithm, PrivateKey, + PrivateKeyChain, + }; + let mut certs = Vec::new(); + for pem in [d.cert_pem.as_str(), issuer_pem, root_pem] { + for der in pki::chain_der(pem)? { + certs.push(Certificate::from_der(&der).map_err(io)?); + } + } + let local_id = ring::digest::digest(&ring::digest::SHA256, d.cert_pem.as_bytes()); + let chain = PrivateKeyChain::new( + &local_id.as_ref()[..20], + PrivateKey::from_der(&key.serialize_der()).map_err(io)?, + certs, + ); + let mut ks = KeyStore::new(); + ks.add_entry(&d.name, KeyStoreEntry::PrivateKeyChain(chain)); + ks.writer(password) + .encryption_algorithm(EncryptionAlgorithm::PbeWithHmacSha256AndAes256) + .encryption_iterations(10_000) + .mac_algorithm(MacAlgorithm::HmacSha256) + .mac_iterations(10_000) + .write() + .map_err(io) +} + +/// A QR code (SVG) for a URL, for the install dialog. +pub fn qr_svg(data: &str) -> Result { + let code = qrcode::QrCode::with_error_correction_level(data, qrcode::EcLevel::M).map_err(io)?; + Ok(code + .render::>() + .min_dimensions(240, 240) + .quiet_zone(true) + .build()) +} + +/// Forget closed requests beyond the newest 200. +fn prune(rs: &mut Vec, _now: u64) { + let closed = rs.iter().filter(|r| r.state != "waiting").count(); + if closed > 200 { + let mut drop = closed - 200; + rs.retain(|r| { + if drop > 0 && r.state != "waiting" { + drop -= 1; + false + } else { + true + } + }); + } +} + +fn ymd(unix: u64) -> (i64, u32, u32) { + // Reuse core's calendar via its RFC 3339 text. + let s = ianitor_core::time::rfc3339(unix); + let y = s.get(0..4).and_then(|v| v.parse().ok()).unwrap_or(1970); + let m = s.get(5..7).and_then(|v| v.parse().ok()).unwrap_or(1); + let d = s.get(8..10).and_then(|v| v.parse().ok()).unwrap_or(1); + (y, m, d) +} + +// ------------------------------------------------------------------ the manual approval CLI + +/// `ianitor-control pki approve `: write an approval for the open device request with +/// this code. Run on the server by Mark, as the user control runs as. +pub fn cli_approve(state_dir: &Path, code: &str, deny: bool, now: u64) -> Result { + let dir = state_dir.join("pki"); + let rs: Vec = read_json(&dir.join("requests.json"))?.unwrap_or_default(); + let want = normalise_code(code); + if want.len() != 6 { + return Err("the code has six digits, like 47 19 83".into()); + } + let r = rs + .into_iter() + .find(|r| { + r.kind == "device" + && r.state == "waiting" + && r.expires_at > now + && normalise_code(&r.match_code) == want + }) + .ok_or("no open device request has this code (it may have expired)")?; + let file = dir.join("approvals").join(format!( + "{}.{}", + r.id, + if deny { "deny" } else { "approve" } + )); + write_atomic(&file, want.as_bytes(), 0o600).map_err(|e| e.to_string())?; + Ok(r) +} + +/// `ianitor-control pki install `: hand a signed intermediate to the open renewal +/// whose key it carries. +pub fn cli_install(state_dir: &Path, cert_pem: &str, now: u64) -> Result { + let dir = state_dir.join("pki"); + let rs: Vec = read_json(&dir.join("requests.json"))?.unwrap_or_default(); + let spki = pki::public_key_der(cert_pem).map_err(|e| e.to_string())?; + let r = rs + .into_iter() + .find(|r| { + r.kind == "intermediate" + && r.state == "waiting" + && r.expires_at > now + && r + .csr_pem + .as_deref() + .and_then(|c| pki::csr_public_key_der(c).ok()) + .is_some_and(|k| k == spki) + }) + .ok_or("no open renewal matches this certificate's key (was it signed from the current request?)")?; + let file = dir.join("approvals").join(format!("{}.crt", r.id)); + write_atomic(&file, cert_pem.as_bytes(), 0o600).map_err(|e| e.to_string())?; + Ok(r) +} + +pub fn requests_path(state_dir: &Path) -> PathBuf { + state_dir.join("pki/requests.json") +} diff --git a/crates/control/src/pki_ctl.rs b/crates/control/src/pki_ctl.rs new file mode 100644 index 0000000..d4ec263 --- /dev/null +++ b/crates/control/src/pki_ctl.rs @@ -0,0 +1,207 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied, +//! the device files both engines read, and what happens after an approval, a renewal or a +//! revocation. + +// A refusal is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use ianitor_core::TlsMode; + +use crate::engine::{Control, Fail}; +use crate::messages::{self, Params}; +use crate::pki::PkiFail; +use crate::util::now; + +/// The HTTP status for a PKI refusal. +pub fn status_of(code: &str) -> u16 { + match code { + "pki.request_not_found" | "pki.device_not_found" => 404, + "pki.bundle_used" => 410, + "pki.bad_certificate" + | "pki.not_our_root" + | "pki.wrong_key" + | "pki.device_name" + | "pki.device_kind" + | "pki.wrong_code" => 422, + "pki.too_many_requests" => 429, + _ => 409, + } +} + +pub fn pki_fail(e: PkiFail) -> Fail { + match e { + PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()), + PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d), + } +} + +impl Control { + pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> { + self.pki + .as_ref() + .ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new())) + } + + /// Every certificate directory a compiler output points at. + fn cert_dirs(&self) -> Vec<&Path> { + let mut v = vec![Path::new(&self.cfg.compile.cert_dir)]; + let c = Path::new(&self.cfg.caddy_compile().cert_dir); + if c != v[0] { + v.push(c); + } + v + } + + /// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the + /// device files when a host needs them. Without `[pki]` nothing is issued (the files are + /// expected to be there, as in phase 2). Returns whether a file changed. + pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result { + let Some(p) = &self.pki else { + return Ok(false); + }; + let t = now(); + let domi: Vec = model + .hosts() + .iter() + .filter(|h| h.tls == TlsMode::Domi) + .map(|h| h.hostname.to_string()) + .collect(); + let devices = model.hosts().iter().any(|h| h.device_certs); + let mut changed = false; + for dir in self.cert_dirs() { + let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| { + let mut f = pki_fail(e); + // The apply's reason names a host so the UI can point at it. + if let Some(h) = domi.first() { + f.reason.hostname = Some(h.clone()); + } + f + })?; + if !issued.is_empty() { + log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", ")); + changed = true; + } + if devices || dir.join(ianitor_core::compile::DEVICE_CA_FILE).exists() { + changed |= p.write_device_files(dir, t).map_err(pki_fail)?; + } + } + Ok(changed) + } + + /// Every couple of seconds: act on approvals; once an hour: renew server certificates. + pub async fn pki_poller(self: Arc) { + if self.pki.is_none() { + return; + } + let mut last_renewal_check = now(); + loop { + tokio::time::sleep(Duration::from_secs(2)).await; + let me = self.clone(); + let polled = tokio::task::spawn_blocking(move || match &me.pki { + Some(p) => p.poll(now()), + None => Ok(Default::default()), + }) + .await; + let changes = match polled { + Ok(Ok(c)) => c, + Ok(Err(e)) => { + log::error!(target: "ianitor::pki", "{e}"); + continue; + } + Err(e) => { + log::error!(target: "ianitor::pki", "pki poll crashed: {e}"); + continue; + } + }; + let t = now(); + if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 { + last_renewal_check = t; + self.refresh_certificates(changes.intermediate).await; + } + if changes.devices { + self.devices_changed().await; + } + } + } + + /// Issue what the current tree needs (after a new intermediate: everything) and reload + /// the engine that serves, under the apply lock so no trial is running. + pub async fn refresh_certificates(&self, new_intermediate: bool) { + let _lock = self.apply_lock.lock().await; + let Ok((_, _, model)) = self.head_model() else { + return; + }; + match self.pki_prepare(&model) { + Ok(changed) if changed || new_intermediate => { + if new_intermediate { + log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued"); + } + self.reload_serving_engine().await; + } + Ok(_) => {} + Err(f) => { + log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message); + } + } + } + + /// The device files changed (issue or revoke): rewrite them and tell the engine at once. + pub async fn devices_changed(&self) { + let Some(p) = &self.pki else { return }; + let t = now(); + let mut changed = false; + for dir in self.cert_dirs() { + match p.write_device_files(dir, t) { + Ok(c) => changed |= c, + Err(e) => log::error!(target: "ianitor::pki", "device files not written: {e}"), + } + } + if !changed { + return; + } + if self.engine_running() == "caddy" { + // Caddy reads the allow list when it starts: restart it so a revocation counts. + if let Err(e) = self.restart_caddy().await { + log::error!(target: "ianitor::pki", "caddy-fallback not restarted after a device change: {e}"); + } + } else if self.edge.attached() + && let Err(e) = self.edge.reload_devices().await + { + log::error!(target: "ianitor::pki", "edge did not re-read the device certificates: {e}"); + } + } + + async fn reload_serving_engine(&self) { + if self.engine_running() == "caddy" { + if let Err(e) = self.restart_caddy().await { + log::error!(target: "ianitor::pki", "caddy-fallback not restarted: {e}"); + } + } else if self.edge.attached() + && let Err(e) = self.edge.reload().await + { + log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}"); + } + } + + /// The code and message for a PKI request that waits for its approval. + pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) { + let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual"); + let c = match (kind, manual) { + ("intermediate", _) => "pki.renew.manual", + (_, true) => "pki.waiting.manual", + (_, false) => "pki.waiting", + }; + ( + c.to_owned(), + messages::message(c, &messages::params([("code", code.to_owned())])), + ) + } +} diff --git a/crates/control/src/switch.rs b/crates/control/src/switch.rs new file mode 100644 index 0000000..5bd6e15 --- /dev/null +++ b/crates/control/src/switch.rs @@ -0,0 +1,400 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4). +//! +//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start, +//! stop and restart only those two, through a polkit rule scoped to exactly them (NixOS +//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit +//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the +//! target), stops the old engine, starts the new one and waits until it serves; if the new +//! one does not come up, it goes back to the old one and says so. +//! +//! Decisions (phase 3): +//! - While Caddy serves, changes are paused (`engine.caddy`): Caddy is the emergency +//! fallback, and the apply pipeline's trial, watch and revert are built on edge's admin +//! socket. Changes made then would also have no differential check. +//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md): +//! Caddy cannot check them, and control never serves visitors itself. +//! - Device revocations while Caddy serves restart caddy-fallback (Caddy reads the allow +//! list when it starts); this is why the polkit rule also allows `restart`. +//! +//! The systemd calls go through [`Units`], so tests use a fake. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::config::EngineConfig; +use crate::engine::{Control, Fail, reason}; +use crate::messages::{self, Params}; +use crate::records::Reason; +use crate::util::{now, write_atomic}; + +/// Start, stop and look at systemd units. +pub trait Units: Send + Sync { + fn start(&self, unit: &str) -> Result<(), String>; + fn stop(&self, unit: &str) -> Result<(), String>; + fn restart(&self, unit: &str) -> Result<(), String>; + fn is_active(&self, unit: &str) -> Result; +} + +/// `systemctl --no-ask-password `, as the control user (polkit decides). +pub struct Systemctl { + pub bin: PathBuf, +} + +impl Systemctl { + fn run(&self, args: &[&str]) -> Result { + std::process::Command::new(&self.bin) + .arg("--no-ask-password") + .args(args) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|e| format!("cannot run {}: {e}", self.bin.display())) + } + + fn verb(&self, verb: &str, unit: &str) -> Result<(), String> { + let o = self.run(&[verb, unit])?; + if o.status.success() { + Ok(()) + } else { + Err(format!( + "systemctl {verb} {unit} failed: {}", + String::from_utf8_lossy(&o.stderr).trim() + )) + } + } +} + +impl Units for Systemctl { + fn start(&self, unit: &str) -> Result<(), String> { + self.verb("start", unit) + } + fn stop(&self, unit: &str) -> Result<(), String> { + self.verb("stop", unit) + } + fn restart(&self, unit: &str) -> Result<(), String> { + self.verb("restart", unit) + } + fn is_active(&self, unit: &str) -> Result { + Ok(self.run(&["is-active", "--quiet", unit])?.status.success()) + } +} + +/// In-memory units for tests: records every call; `fail_start` makes a start fail. +#[derive(Default)] +pub struct FakeUnits { + pub calls: Mutex>, + pub active: Mutex>, + pub fail_start: Mutex>, +} + +impl Units for FakeUnits { + fn start(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("start {unit}")); + } + if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) { + return Err(format!("{unit} failed to start")); + } + if let Ok(mut a) = self.active.lock() { + a.insert(unit.to_owned()); + } + Ok(()) + } + fn stop(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("stop {unit}")); + } + if let Ok(mut a) = self.active.lock() { + a.remove(unit); + } + Ok(()) + } + fn restart(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("restart {unit}")); + } + Ok(()) + } + fn is_active(&self, unit: &str) -> Result { + Ok(self.active.lock().is_ok_and(|a| a.contains(unit))) + } +} + +/// Which engine serves, as control knows it. +#[derive(Debug, Clone)] +pub struct EngineState { + /// `pingora` or `caddy`. + pub running: String, + /// `running`, `switching` or `stopped`. + pub state: String, + pub since: u64, + /// The target while switching. + pub target: Option, + /// Why the last switch did not happen. + pub last_error: Option, +} + +pub fn read_engine_file(p: &Path) -> String { + match std::fs::read_to_string(p) { + Ok(s) if s.trim() == "caddy" => "caddy".into(), + _ => "pingora".into(), + } +} + +pub fn engine_name(e: &str) -> String { + if e == "caddy" { "Caddy" } else { "Pingora" }.into() +} + +impl Control { + pub fn engine_cfg(&self) -> Option<&EngineConfig> { + self.cfg.engine.as_ref() + } + + /// `pingora` or `caddy`. + pub fn engine_running(&self) -> String { + self.engine + .lock() + .map(|e| e.running.clone()) + .unwrap_or_else(|_| "pingora".into()) + } + + pub fn engine_state(&self) -> EngineState { + self.engine + .lock() + .map(|e| e.clone()) + .unwrap_or(EngineState { + running: "pingora".into(), + state: "running".into(), + since: 0, + target: None, + last_error: None, + }) + } + + fn set_engine(&self, f: impl FnOnce(&mut EngineState)) { + if let Ok(mut e) = self.engine.lock() { + f(&mut e); + } + } + + pub async fn restart_caddy(&self) -> Result<(), String> { + let (Some(cfg), Some(units)) = (self.engine_cfg(), self.units.clone()) else { + return Err("no engine settings".into()); + }; + let unit = cfg.caddy_unit.clone(); + tokio::task::spawn_blocking(move || units.restart(&unit)) + .await + .map_err(|e| e.to_string())? + } + + /// Check a switch request and start it. Answers at once; the switch runs in the + /// background (`overview.engine.state` is `switching` until it ends). + pub fn request_switch(self: &Arc, target: &str) -> Result { + if self.engine_cfg().is_none() || self.units.is_none() { + return Err(Fail::new(409, "engine.unmanaged", Params::new())); + } + if target != "pingora" && target != "caddy" { + return Err(Fail::new( + 422, + "request.body", + messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]), + )); + } + { + let mut e = self + .engine + .lock() + .map_err(|_| Fail::new(500, "internal", Params::new()))?; + if e.state == "switching" { + return Err(Fail::new(409, "engine.switching", Params::new())); + } + if e.running == target { + return Err(Fail::new( + 409, + "engine.same", + messages::params([("engine", engine_name(target))]), + )); + } + e.state = "switching".into(); + e.target = Some(target.to_owned()); + e.last_error = None; + } + let me = self.clone(); + let t = target.to_owned(); + tokio::spawn(async move { me.switch(&t).await }); + Ok(self.engine_state()) + } + + async fn switch(self: Arc, target: &str) { + // No apply runs during a switch, and none starts. + let _lock = self.apply_lock.lock().await; + let from = self.engine_running(); + let res = self.switch_inner(&from, target).await; + let t = now(); + match res { + Ok(()) => { + log::info!(target: "ianitor::engine", "switched from {from} to {target}"); + self.set_engine(|e| { + e.running = target.to_owned(); + e.state = "running".into(); + e.since = t; + e.target = None; + }); + } + Err(detail) => { + log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}"); + // Go back to what served before. + let back = self.bring_back(&from).await; + let mut r = reason( + "engine.switch_failed", + messages::params([ + ("engine", engine_name(target)), + ("previous", engine_name(&from)), + ]), + ); + r.detail = Some(match back { + Ok(()) => detail, + Err(b) => format!("{detail}; going back also failed: {b}"), + }); + self.set_engine(|e| { + e.running = from.clone(); + e.state = "running".into(); + e.target = None; + e.last_error = Some(r); + }); + } + } + } + + fn units_and_cfg(&self) -> Result<(Arc, EngineConfig), String> { + match (self.units.clone(), self.engine_cfg().cloned()) { + (Some(u), Some(c)) => Ok((u, c)), + _ => Err("no engine settings".into()), + } + } + + fn unit_of(cfg: &EngineConfig, engine: &str) -> String { + if engine == "caddy" { + cfg.caddy_unit.clone() + } else { + cfg.edge_unit.clone() + } + } + + async fn blocking( + f: impl FnOnce() -> Result + Send + 'static, + ) -> Result { + tokio::task::spawn_blocking(f) + .await + .map_err(|e| e.to_string())? + } + + async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> { + let (units, cfg) = self.units_and_cfg()?; + if target == "caddy" { + // Caddy starts from caddy.json: make sure it is the current tree's. + self.write_current_caddy()?; + } + write_atomic(&cfg.file, target.as_bytes(), 0o644) + .map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?; + let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target)); + let u = units.clone(); + Self::blocking(move || u.stop(&old)).await?; + let u = units.clone(); + let n = new.clone(); + Self::blocking(move || u.start(&n)).await?; + self.wait_serving(target, &units, &new).await + } + + async fn bring_back(&self, engine: &str) -> Result<(), String> { + let (units, cfg) = self.units_and_cfg()?; + let other = if engine == "caddy" { + "pingora" + } else { + "caddy" + }; + write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?; + let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine)); + let u = units.clone(); + let _ = Self::blocking(move || u.stop(&stop)).await; + let u = units.clone(); + let s = start.clone(); + Self::blocking(move || u.start(&s)).await?; + self.wait_serving(engine, &units, &start).await + } + + /// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts + /// connections on the HTTPS address. + async fn wait_serving( + &self, + engine: &str, + units: &Arc, + unit: &str, + ) -> Result<(), String> { + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + let addr = if engine == "caddy" { + self.cfg.caddy_compile().https_listen + } else { + self.cfg.compile.https_listen + }; + loop { + let u = units.clone(); + let n = unit.to_owned(); + let active = Self::blocking(move || u.is_active(&n)) + .await + .unwrap_or(false); + let serving = active + && if engine == "pingora" && self.edge.attached() { + self.edge.status().await.is_ok() + } else { + tokio::net::TcpStream::connect(addr).await.is_ok() + }; + if serving { + return Ok(()); + } + if tokio::time::Instant::now() > deadline { + return Err(format!("{unit} did not come up within 20 s")); + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + + /// Compile the current tree for Caddy and write caddy.json (the file only ever holds a + /// kept tree, so this only matters when it is missing or older). + fn write_current_caddy(&self) -> Result<(), String> { + let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?; + self.pki_prepare(&model).map_err(|f| f.reason.message)?; + let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options()) + .map_err(|e| e.to_string())?; + if std::fs::read_to_string(&self.cfg.caddy.config) + .ok() + .as_deref() + != Some(text.as_str()) + { + write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + } + Ok(()) + } + + /// Changes wait while Caddy serves. + pub fn engine_pause(&self) -> Option { + (self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new())) + } +} + +/// What control.toml's `[engine]` asks for. +pub fn units_for(cfg: Option<&EngineConfig>) -> Option> { + let c = cfg?; + match c.units.as_str() { + "systemctl" => Some(Arc::new(Systemctl { + bin: c.systemctl.clone(), + })), + _ => None, + } +} diff --git a/crates/control/tests/common/mod.rs b/crates/control/tests/common/mod.rs index 7e5d1a9..aea097f 100644 --- a/crates/control/tests/common/mod.rs +++ b/crates/control/tests/common/mod.rs @@ -66,6 +66,8 @@ pub struct EnvSpec { pub watch_secs: u64, pub site: String, pub remote: Option, + /// Appended to control.toml (extra sections such as [pki]). + pub extra_config: String, } impl Default for EnvSpec { @@ -74,6 +76,7 @@ impl Default for EnvSpec { watch_secs: 2, site: String::new(), remote: None, + extra_config: String::new(), } } } @@ -202,7 +205,7 @@ caddy_credentials_dir = "{creds}" certs = d("certs"), edge_state = d("edge-state"), log = d("logs/access.log"), - ); + ) + &spec.extra_config; std::fs::write(self.dir.join("control.toml"), text).unwrap(); } @@ -254,7 +257,7 @@ caddy_credentials_dir = "{creds}" std::thread::sleep(Duration::from_millis(200)); } - fn command(&self) -> Command { + pub fn command(&self) -> Command { let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control")); c.env_remove("IANITOR_TEST_CRASH_AT"); c.env_remove("IANITOR_TEST_FAIL_WRITE"); diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs new file mode 100644 index 0000000..9e14f54 --- /dev/null +++ b/crates/control/tests/pki.rs @@ -0,0 +1,421 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is +//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server +//! certificates that chain to the root; device certificates need the match code; the install +//! file works once; revocation takes the device off the allow list; no root key file is ever +//! in the state directory, and control refuses to start with one there. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux; run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::path::Path; + use std::time::{Duration, Instant}; + + use crate::common::{Env, EnvSpec}; + use ianitor_core::pki; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + use serde_json::{Value, json}; + + const PASSWORD: &str = "intermediate-test-password-123"; + + fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 + } + + /// The offline side: a root that lives only in this test's memory (and its cert file). + struct Offline { + root_pem: String, + root_key: pki::KeyPair, + } + + async fn env_with_pki() -> (Env, Offline) { + let (root_pem, root_key) = pki::create_root(now()).unwrap(); + // Only the root certificate goes next to control; the key stays in this test. + let extra = |dir: &Path| { + format!( + "\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n", + dir.join("offline-root.crt").display() + ) + }; + 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("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 }) + } + + async fn wait_request(env: &Env, id: &str, want: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let r = env + .call("GET", &format!("/api/v1/pki-requests/{id}"), None) + .await; + assert_eq!(r.status, 200, "{}", r.text); + if r.json["state"] == want { + return r.json; + } + if Instant::now() > deadline { + panic!( + "request {id} is {} not {want}\n{}", + r.json["state"], + env.control_log() + ); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + + fn cli(env: &Env, args: &[&str]) -> std::process::Output { + env.command() + .args(args) + .arg("--config") + .arg(env.config_path()) + .output() + .unwrap() + } + + /// Renew (first intermediate), sign offline, install with the CLI. + async fn install_intermediate(env: &Env, off: &Offline) -> Value { + 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 csr = r.json["csr_pem"].as_str().unwrap().to_owned(); + // The code the UI shows is the one the offline signer computes from the CSR. + assert_eq!( + r.json["match_code"].as_str().unwrap(), + pki::match_code(&pki::csr_der(&csr).unwrap()) + ); + let r2 = env + .call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None) + .await; + assert_eq!(r2.status, 200); + assert_eq!(r2.text, csr); + let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); + let f = env.dir.join("signed.crt"); + std::fs::write(&f, &signed).unwrap(); + let out = cli(env, &["pki", "install", f.to_str().unwrap()]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + wait_request(env, &rid, "approved").await + } + + #[tokio::test(flavor = "multi_thread")] + async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() { + let (env, off) = env_with_pki().await; + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text); + + // Before an intermediate exists a domi host cannot get a certificate. + let echo = Echo::start("domi").await; + let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await; + assert_eq!(rec["state"], "failed", "{rec}"); + assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}"); + + install_intermediate(&env, &off).await; + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text); + assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364); + + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); + // The served certificate chains to the Domi root (only the root is trusted here). + let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem); + let edge = env.edge.as_ref().unwrap(); + let r = client::https( + edge.https, + "fresh.test", + roots, + &Req::get("fresh.test", "/"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); + let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap(); + let info = pki::inspect(&crt).unwrap(); + assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]); + assert_eq!( + (info.not_after - now()) / 86_400, + i64::from(pki::SERVER_DAYS) - 1 + ); + + // No root key anywhere control writes. + let key_pem = off.root_key.serialize_pem(); + let body: String = key_pem + .lines() + .filter(|l| !l.starts_with("-----")) + .collect(); + for d in ["state", "certs", "edge", "caddy", "edge-state"] { + for f in walk(&env.dir.join(d)) { + let bytes = std::fs::read(&f).unwrap(); + let text = String::from_utf8_lossy(&bytes); + assert!( + !text.contains(&body[..40]), + "root key material in {}", + f.display() + ); + assert!( + !contains(&bytes, &off.root_key.serialize_der()), + "root key DER in {}", + f.display() + ); + } + } + // The intermediate key is only stored encrypted. + let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap(); + assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY"))); + assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY"))); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_wrong_certificate_is_not_installed() { + let (env, off) = env_with_pki().await; + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); + // Signed by another root. + let (other, other_key) = pki::create_root(now()).unwrap(); + let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": wrong})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "pki.not_our_root"); + // For another key. + let k = pki::generate_key().unwrap(); + let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); + let wrong = + pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": wrong})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "pki.wrong_key"); + // A leaf is not an intermediate. + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": "garbage"})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + let st = env + .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) + .await; + assert_eq!(st.json["state"], "waiting"); + // The right one through the API works too. + let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": good})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["state"], "approved"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn device_certificate_needs_the_match_code_and_installs_once() { + let (env, off) = env_with_pki().await; + install_intermediate(&env, &off).await; + let r = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "Mark's phone", "kind": "phone"})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let code = r.json["match_code"].as_str().unwrap().to_owned(); + assert_eq!(code.len(), 8, "{code}"); + // The same name again while it waits: refused. + let again = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "mark's PHONE", "kind": "phone"})), + ) + .await; + assert_eq!(again.status, 409, "{}", again.text); + assert_eq!(again.json["error"]["code"], "pki.device_name_taken"); + + // A wrong code does nothing. + let wrong = if code.starts_with('0') { + "11 11 11" + } else { + "00 00 00" + }; + let out = cli(&env, &["pki", "approve", wrong]); + assert!(!out.status.success()); + tokio::time::sleep(Duration::from_millis(2500)).await; + let st = env + .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) + .await; + assert_eq!(st.json["state"], "waiting"); + + let out = cli(&env, &["pki", "approve", &code]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let done = wait_request(&env, &rid, "approved").await; + let did = done["device_id"].as_str().unwrap().to_owned(); + + let certs = env.call("GET", "/api/v1/certs", None).await; + assert_eq!(certs.status, 200, "{}", certs.text); + assert_eq!(certs.json["root"]["offline"], true); + let dev = certs.json["devices"] + .as_array() + .unwrap() + .iter() + .find(|d| d["id"] == did.as_str()) + .unwrap() + .clone(); + assert_eq!(dev["state"], "valid"); + assert_eq!(dev["name"], "Mark's phone"); + + // The allow list both engines read has it. + let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); + assert!(allow.contains("BEGIN CERTIFICATE")); + + // One-time install file. + let b = env + .call( + "POST", + &format!("/api/v1/certs/devices/{did}/bundle"), + Some(json!({"format": "qr"})), + ) + .await; + assert_eq!(b.status, 200, "{}", b.text); + let url = b.json["download_url"].as_str().unwrap().to_owned(); + let password = b.json["one_time_password"].as_str().unwrap().to_owned(); + assert!(b.json["qr_svg"].as_str().unwrap().starts_with(" Vec { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else { + out.push(p); + } + } + } + out + } + + fn contains(hay: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) + } +} diff --git a/crates/control/tests/ui_auth.rs b/crates/control/tests/ui_auth.rs new file mode 100644 index 0000000..d003fb3 --- /dev/null +++ b/crates/control/tests/ui_auth.rs @@ -0,0 +1,194 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Sign-in for the web UI (G14, tests first). The UI reaches control through edge on the +//! admin host, behind Authelia; edge adds a per-boot secret header (`X-Ianitor-Proof`, from a +//! systemd credential only edge and control can read). Control trusts `Remote-User` only on a +//! request that carries that proof: any local process can send `Remote-User` to loopback, but +//! none can send the proof. API tokens keep working for scripts. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux; run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use crate::common::{Env, EnvSpec}; + use ianitor_testkit::authelia::MockAuthelia; + use ianitor_testkit::client::{self, Req}; + use serde_json::json; + + const PROOF: &str = "per-boot-proof-0123456789abcdef0123456789abcdef"; + + async fn env(site: String) -> Env { + env_for(site, "ui.test").await + } + + async fn env_for(site: String, ui_host: &str) -> Env { + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + std::fs::write(env.dir.join("creds/ui-proof"), format!("{PROOF}\n")).unwrap(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!("\n[ui]\nhostname = \"{ui_host}\"\nproof_credential = \"ui-proof\"\n"); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + env + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_forged_remote_user_without_the_proof_gets_401() { + let env = env(String::new()).await; + for headers in [ + vec![("Remote-User", "mark")], + vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")], + vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "")], + vec![("remote-user", "mark"), ("Remote-Groups", "admins")], + ] { + let r = env + .call_with("GET", "/api/v1/overview", &headers, None) + .await; + assert_eq!(r.status, 401, "{headers:?}: {}", r.text); + assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text); + } + // A valid API token does not make a forged identity acceptable either. + let auth = format!("Bearer {}", env.token); + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("Authorization", &auth), ("Remote-User", "mark")], + None, + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + // Nothing was trusted: the log does not show the forged user as an actor. + assert!(!env.control_log().contains("by mark")); + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_proof_with_a_remote_user_signs_the_ui_in() { + let env = env(String::new()).await; + let ok = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)]; + let r = env.call_with("GET", "/api/v1/overview", &ok, None).await; + assert_eq!(r.status, 200, "{}", r.text); + // Through edge the Host is the admin host's. + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[ + ("Remote-User", "mark"), + ("X-Ianitor-Proof", PROOF), + ("Host", "ui.test"), + ], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + // Writes need the UI header (CSRF), browser or not. + let r = env + .call_with( + "POST", + "/api/v1/tokens", + &ok, + Some(json!({"name": "from ui"})), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let mut w = ok.to_vec(); + w.push(("X-Ianitor-UI", "1")); + let r = env + .call_with( + "POST", + "/api/v1/tokens", + &w, + Some(json!({"name": "from ui"})), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + // The proof without a user is not a sign-in. + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("X-Ianitor-Proof", PROOF)], + None, + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + assert_eq!(r.json["error"]["code"], "ui.no_user"); + // API tokens still work for scripts. + let r = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(r.status, 200, "{}", r.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn through_edge_authelia_decides_and_a_client_cannot_bring_its_own_proof() { + let auth = MockAuthelia::start().await; + let site = format!( + "secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n", + auth.url() + ); + let env = env_for(site, "a.test").await; + // The admin host: forward-auth, upstream control, the proof header from the secret. + let host = json!({"host": { + "hostname": "a.test", "upstreams": [format!("http://{}", env.api)], + "tls": "domi", "auth": "forward-auth", + "request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}] + }}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); + let edge = env.edge.as_ref().unwrap(); + let roots = env.ca.roots(); + // Signed in at Authelia (mock: alice): the UI gets in. + let r = client::https( + edge.https, + "a.test", + roots.clone(), + &Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", r.text()); + assert!(r.text().contains("\"hosts\""), "{}", r.text()); + // Not signed in: Authelia's answer, control never sees it. + let r = client::https( + edge.https, + "a.test", + roots.clone(), + &Req::get("a.test", "/api/v1/overview"), + ) + .await + .unwrap(); + assert_ne!(r.status, 200); + // A client that sends its own proof and user gets neither through: edge replaces + // the proof with the real one only after Authelia allowed the request, and strips + // Remote-* from clients. + let r = client::https( + edge.https, + "a.test", + roots, + &Req::get("a.test", "/api/v1/overview") + .header("x-ianitor-proof", "guess") + .header("remote-user", "mallory"), + ) + .await + .unwrap(); + assert_ne!(r.status, 200); + } +} diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs index f9f04e1..e7ff8d8 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -566,6 +566,15 @@ pub fn match_code(request: &[u8]) -> String { ) } +/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). +pub fn csr_public_key_der(csr_pem: &str) -> Result, PkiError> { + use x509_parser::prelude::FromDer; + let der = csr_der(csr_pem)?; + let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der) + .map_err(|_| PkiError::BadCsr)?; + Ok(csr.certification_request_info.subject_pki.raw.to_vec()) +} + /// DER of the first PEM block of a CSR (for the match code). pub fn csr_der(csr_pem: &str) -> Result, PkiError> { for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs index 945ea38..44260bf 100644 --- a/tests/diff/tests/apply_sequence.rs +++ b/tests/diff/tests/apply_sequence.rs @@ -121,6 +121,9 @@ mod unix { }, compile: compile_of(&edge_opts), compile_caddy: Some(compile_of(&caddy_opts)), + pki: None, + ui: None, + engine: None, }; // Start from the site file and every host except three; then a sequence of applies diff --git a/tests/support/src/more.rs b/tests/support/src/more.rs index c0938ca..e680e17 100644 --- a/tests/support/src/more.rs +++ b/tests/support/src/more.rs @@ -179,6 +179,8 @@ pub struct JsonResp { pub headers: Vec<(String, String)>, pub json: serde_json::Value, pub text: String, + /// The raw body (for binary answers). + pub body: Vec, } impl JsonResp { @@ -197,6 +199,7 @@ fn json_resp(r: Resp) -> JsonResp { headers: r.headers, json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null), text, + body: r.body, } } -- 2.53.0 From c18ae154ad1268803d1464edcdaa93a943fbde72 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:21:49 +0100 Subject: [PATCH 09/34] [control] Domi CA and UI sign-in: intermediate renewal by CSR with manual offline signing, domi host certificates, device requests approved by code, one-time PKCS#12 installs, revocation; Remote-User trusted only with edge's per-boot proof --- crates/control/src/api/handlers.rs | 99 ++++- crates/control/src/api/mod.rs | 119 ++++- crates/control/src/api/pki.rs | 687 +++++++++++++++++++++++++++++ crates/control/src/api/ui.rs | 122 +++++ crates/control/src/api/views.rs | 33 +- crates/control/src/engine.rs | 8 + crates/control/src/hostspec.rs | 9 + crates/control/src/lib.rs | 1 + crates/control/src/main.rs | 169 +++++++ crates/control/src/pki.rs | 7 +- crates/control/src/switch.rs | 8 + crates/control/tests/api.rs | 12 +- crates/control/tests/pki.rs | 18 +- crates/edge/src/admin.rs | 4 + crates/edge/src/proxy.rs | 10 +- crates/edge/src/shared.rs | 44 +- crates/edge/src/tls.rs | 4 + 17 files changed, 1300 insertions(+), 54 deletions(-) create mode 100644 crates/control/src/api/pki.rs create mode 100644 crates/control/src/api/ui.rs diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index a6d12fe..a1f69dc 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -179,39 +179,77 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result ApiError { // ---------------------------------------------------------------- middleware -fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { +pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else { return false; }; @@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { format!("127.0.0.1:{port}"), format!("[::1]:{port}"), ]; - ok.iter().any(|o| o.eq_ignore_ascii_case(host)) + // The admin host edge forwards the UI on, with or without edge's HTTPS port. + let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref()); + let ui_ok = ui.is_some_and(|u| { + let edge_port = ctl.cfg.compile.https_listen.port(); + host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}")) + }); + ui_ok + || ok.iter().any(|o| o.eq_ignore_ascii_case(host)) || ctl .cfg .allowed_hosts @@ -336,6 +345,45 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { .any(|a| a.eq_ignore_ascii_case(host)) } +enum UiIdentity { + /// No sign-in headers: an API-token request. + None, + /// `Remote-*` or a proof header without the right proof. + Forged, + /// The right proof but no usable `Remote-User`. + NoUser, + User(String), +} + +fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { + let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-")); + let proof = headers.get("x-ianitor-proof"); + if !names_user && proof.is_none() { + return UiIdentity::None; + } + let ok = match (proof, &ctl.ui_proof) { + (Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want), + _ => false, + }; + if !ok { + return UiIdentity::Forged; + } + let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect(); + match users.as_slice() { + [one] => match one.to_str() { + Ok(u) + if !u.is_empty() + && u.len() <= 64 + && u.bytes().all(|c| c.is_ascii_graphic() && c != b':') => + { + UiIdentity::User(u.to_owned()) + } + _ => UiIdentity::NoUser, + }, + _ => UiIdentity::NoUser, + } +} + /// Host check, CSRF check, token, rate limit; logs method, route template, status, time. async fn guard(State(st): State>, mut req: Request, next: Next) -> Response { let started = Instant::now(); @@ -367,6 +415,46 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> Params::new(), )); } + // The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request + // with the per-boot proof edge adds is identified by its Remote-User. Any other + // request that names a user is refused, so a local process cannot claim to be one. + match ui_identity(&st.ctl, req.headers()) { + UiIdentity::None => {} + UiIdentity::Forged => { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "ui.no_proof", + Params::new(), + )); + } + UiIdentity::NoUser => { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "ui.no_user", + Params::new(), + )); + } + UiIdentity::User(user) => { + // Cookie-based sign-in: every write carries the UI header, browser or not. + if write && !ui { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + st.limit(&format!("user:{user}"), RATE_PER_MINUTE, 60) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()) + .retry(s) + })?; + req.extensions_mut().insert(Actor { + token_id: format!("user:{user}"), + name: user, + }); + return Ok(next.run(req).await); + } + } let auth = req .headers() .get(header::AUTHORIZATION) @@ -429,7 +517,7 @@ async fn finish(req: Request, next: Next) -> Response { let out = match serde_json::from_slice::(&bytes) { Ok(serde_json::Value::Object(mut m)) => { m.insert("server_time".into(), rfc3339(now()).into()); - if m.contains_key("error") { + if m.get("error").is_some_and(serde_json::Value::is_object) { m.insert("request_id".into(), request_id.into()); } serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec()) @@ -503,14 +591,35 @@ pub fn router(st: Arc) -> Router { post(h::stop_all_share_links), ) .route("/api/v1/share-links/{id}", delete(h::stop_share_link)) + .route("/api/v1/certs", get(pki::get_certs)) + .route("/api/v1/certs/devices", post(pki::request_device)) + .route("/api/v1/certs/devices/{id}", delete(pki::revoke_device)) + .route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle)) + .route("/api/v1/certs/intermediate/renewal", post(pki::renew)) + .route( + "/api/v1/pki-requests/{id}", + 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}/certificate", + axum::routing::put(pki::put_certificate), + ) + .route( + "/api/v1/engine", + get(pki::get_engine).post(pki::switch_engine), + ) .route("/api/v1/health", get(h::health)) .route("/api/v1/openapi.json", get(h::openapi)) .method_not_allowed_fallback(method_not_allowed) .fallback(not_found) .layer(middleware::from_fn_with_state(st.clone(), guard)) .layer(DefaultBodyLimit::max(MAX_BODY)) - .with_state(st); - api.layer(middleware::from_fn(finish)) + .with_state(st.clone()); + // In front of the guard: the built UI (static files, no token: they hold no data) and + // the one-time device downloads (the link is the secret). Both still check the Host. + api.layer(middleware::from_fn_with_state(st, ui::front)) + .layer(middleware::from_fn(finish)) } /// The OpenAPI document. diff --git a/crates/control/src/api/pki.rs b/crates/control/src/api/pki.rs new file mode 100644 index 0000000..c9297d4 --- /dev/null +++ b/crates/control/src/api/pki.rs @@ -0,0 +1,687 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9). + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Path, State}; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::views::Blocked; +use super::{Actor, ApiError, AppState, Body}; +use crate::engine::Control; +use crate::messages::{self, Params, message}; +use crate::pki::{Device, PkiFail, Request}; +use crate::pki_ctl::pki_fail; +use crate::switch::engine_name; +use crate::util::{now, rfc3339}; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +fn plain_id(s: &str) -> bool { + !s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') +} + +fn not_found(code: &str) -> ApiError { + ApiError::new(StatusCode::NOT_FOUND, code, Params::new()) +} + +/// Run blocking PKI work (key unlock, file writes) off the async threads. +async fn blocking( + st: &Arc, + f: impl FnOnce(&Control) -> Result + Send + 'static, +) -> Result { + let c = st.ctl.clone(); + if c.pki.is_none() { + return Err(ApiError::new( + StatusCode::CONFLICT, + "pki.not_configured", + Params::new(), + )); + } + tokio::task::spawn_blocking(move || f(&c)) + .await + .map_err(|e| ApiError::internal(e.to_string()))? + .map_err(|e| ApiError::from(pki_fail(e))) +} + +fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> { + c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured")) +} + +// ---------------------------------------------------------------- views + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct PkiRequestView { + pub request_id: String, + /// `device` or `intermediate`. + pub kind: String, + /// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`. + pub state: String, + pub match_code: String, + pub created_at: String, + pub expires_at: String, + pub approved_at: Option, + pub device_id: Option, + pub name: Option, + /// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`). + pub csr_pem: Option, + /// Renewals, once installed: the new intermediate's expiry. + pub not_after: Option, + /// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …). + pub message_code: String, + pub message: String, + /// The command that approves it on the server (manual approval). + pub approve_command: Option, + /// Why it failed, when it did. + pub problem: Option, +} + +pub fn request_view(c: &Control, r: &Request) -> PkiRequestView { + let (message_code, message_text) = match r.state.as_str() { + "waiting" => c.waiting_message(&r.kind, &r.match_code), + "approved" if r.kind == "intermediate" => { + let date = r + .not_after + .map(|t| ianitor_core::time::long_date(t.max(0) as u64)) + .unwrap_or_default(); + ( + "pki.renewed".to_owned(), + message("pki.renewed", &messages::params([("date", date)])), + ) + } + "approved" => ( + "pki.issued".to_owned(), + message( + "pki.issued", + &messages::params([("name", r.name.clone().unwrap_or_default())]), + ), + ), + "denied" => ( + "pki.denied".to_owned(), + message("pki.denied", &Params::new()), + ), + "expired" => ( + "pki.expired".to_owned(), + message("pki.expired", &Params::new()), + ), + "cancelled" => ( + "pki.cancelled".to_owned(), + "Cancelled. Nothing was issued.".to_owned(), + ), + _ => ("internal".to_owned(), message("internal", &Params::new())), + }; + let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual"); + PkiRequestView { + request_id: r.id.clone(), + kind: r.kind.clone(), + state: r.state.clone(), + match_code: r.match_code.clone(), + created_at: rfc3339(r.created_at), + expires_at: rfc3339(r.expires_at), + approved_at: r.approved_at.map(rfc3339), + device_id: r.device_id.clone(), + name: r.name.clone(), + csr_pem: r.csr_pem.clone(), + not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)), + message_code, + 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() + } else { + format!("ianitor-control pki approve {}", r.match_code) + } + }), + problem: r.error.clone(), + } +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct IntermediateView { + /// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`. + pub state: String, + pub subject: Option, + pub not_after: Option, + pub days_left: Option, + pub renewal: Option, + /// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`. + pub banner: Option, +} + +pub fn intermediate_view(c: &Control) -> Option { + let p = c.pki.as_ref()?; + let s = p.status(now()); + let date = s + .not_after + .map(|t| ianitor_core::time::long_date(t.max(0) as u64)) + .unwrap_or_default(); + let days = s.days_left.unwrap_or(0).to_string(); + let banner = match s.state { + "due" => Some("pki.renew_due"), + "urgent" => Some("pki.renew_urgent"), + "expired" => Some("pki.intermediate_expired"), + "missing" => Some("pki.no_intermediate"), + _ => None, + } + .map(|code| Blocked { + code: code.into(), + message: message( + code, + &messages::params([("days", days.clone()), ("date", date.clone())]), + ), + }); + Some(IntermediateView { + state: s.state.into(), + subject: s.subject, + not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)), + days_left: s.days_left, + renewal: s.renewal.as_ref().map(|r| request_view(c, r)), + banner, + }) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct RootView { + /// The root key is never on this server. + pub offline: bool, + pub subject: String, + pub not_after: String, + pub sha256: String, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct DeviceView { + pub id: String, + pub name: String, + /// `phone`, `computer` or `app`. + pub kind: String, + pub created_at: String, + pub not_after: String, + /// `valid`, `revoked` or `expired`. + pub state: String, + pub revoked_at: Option, + pub serial: String, +} + +fn device_view(d: &Device, t: u64) -> DeviceView { + DeviceView { + id: d.id.clone(), + name: d.name.clone(), + kind: d.kind.clone(), + created_at: rfc3339(d.created_at), + not_after: rfc3339(d.not_after.max(0) as u64), + state: d.state(t).into(), + revoked_at: d.revoked_at.map(rfc3339), + serial: d.serial.clone(), + } +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct CertsView { + pub intermediate: Option, + pub root: RootView, + pub devices: Vec, + pub device_lifetime_days: u32, + pub server_lifetime_days: u32, + /// `manual` (on the server, until Custos can) or `custos`. + pub approval: String, + /// Open device requests. + pub requests: Vec, +} + +// ---------------------------------------------------------------- handlers + +/// The certificates screen. +#[utoipa::path(get, path = "/api/v1/certs", tag = "certs", + responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_certs(State(st): Shared) -> Result { + let view = blocking(&st, |c| { + let p = pki(c)?; + let t = now(); + let root = ianitor_core::pki::inspect(p.root_pem())?; + let requests = p_requests(c, t)?; + Ok(CertsView { + intermediate: intermediate_view(c), + root: RootView { + offline: true, + subject: root.subject_cn, + not_after: rfc3339(root.not_after.max(0) as u64), + sha256: root.sha256_hex, + }, + devices: p + .devices()? + .iter() + .rev() + .map(|d| device_view(d, t)) + .collect(), + device_lifetime_days: ianitor_core::pki::DEVICE_DAYS, + server_lifetime_days: ianitor_core::pki::SERVER_DAYS, + approval: c + .cfg + .pki + .as_ref() + .map(|p| p.approval.clone()) + .unwrap_or_default(), + requests, + }) + }) + .await?; + Ok(json(StatusCode::OK, &view)) +} + +fn p_requests(c: &Control, t: u64) -> Result, PkiFail> { + let path = crate::pki::requests_path(&c.cfg.state_dir); + let rs: Vec = crate::util::read_json(&path) + .map_err(PkiFail::Internal)? + .unwrap_or_default(); + Ok(rs + .iter() + .filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t) + .map(|r| request_view(c, r)) + .collect()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct DeviceRequestBody { + pub name: String, + /// `phone`, `computer` or `app`. + pub kind: String, +} + +/// Ask for a device certificate; it is issued once the request is approved with its code. +#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody, + responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn request_device( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + st.limit(&format!("pki:{}", actor.token_id), 20, 3600) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) + })?; + let b = body.value; + let name_for_err = b.name.clone(); + let r = blocking(&st, move |c| { + let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?; + Ok(request_view(c, &r)) + }) + .await + .map_err(|mut e| { + if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" { + e.body.field = Some("name".into()); + e.body + .params + .insert("name".into(), name_for_err.chars().take(64).collect()); + } else if e.body.code == "pki.device_kind" { + e.body.field = Some("kind".into()); + } + e + })?; + log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id); + Ok(json(StatusCode::ACCEPTED, &r)) +} + +/// One approval request. +#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs", + responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_request(State(st): Shared, Path(id): Path) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let v = blocking(&st, move |c| { + let r = pki(c)? + .request(&id, now())? + .ok_or(PkiFail::Code("pki.request_not_found"))?; + Ok(request_view(c, &r)) + }) + .await?; + Ok(json(StatusCode::OK, &v)) +} + +/// Cancel a request that waits. +#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs", + responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn cancel_request( + State(st): Shared, + Path(id): Path, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + blocking(&st, move |c| { + pki(c)? + .cancel(&id)? + .map(|_| ()) + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + Ok(StatusCode::NO_CONTENT.into_response()) +} + +/// A renewal's CSR, as a file to carry to the offline machine. +#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs", + responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_csr(State(st): Shared, Path(id): Path) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let csr = blocking(&st, move |c| { + pki(c)? + .request(&id, now())? + .and_then(|r| r.csr_pem) + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + let mut r = csr.into_response(); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/pkcs10"), + ); + r.headers_mut().insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_static("attachment; filename=\"ianitor-intermediate.csr\""), + ); + Ok(r) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct CertificateBody { + /// The intermediate certificate signed by the Domi root (PEM). + pub certificate_pem: String, +} + +/// Install the signed intermediate for an open renewal. +#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody, + responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn put_certificate( + State(st): Shared, + Path(id): Path, + body: Body, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let pem = body.value.certificate_pem; + if pem.len() > 16 * 1024 { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "pki.bad_certificate", + Params::new(), + )); + } + let v = blocking(&st, move |c| { + let r = pki(c)?.install_intermediate(&id, &pem, now())?; + Ok(request_view(c, &r)) + }) + .await?; + let c = st.ctl.clone(); + tokio::spawn(async move { c.refresh_certificates(true).await }); + Ok(json(StatusCode::OK, &v)) +} + +/// Start the renewal of the intermediate (or set up the first one). +#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs", + responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn renew( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + let v = blocking(&st, move |c| { + let r = pki(c)?.request_renewal(now(), &actor.name)?; + Ok(request_view(c, &r)) + }) + .await?; + Ok(json(StatusCode::ACCEPTED, &v)) +} + +/// Revoke a device: it is off the allow list at once. +#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs", + responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn revoke_device( + State(st): Shared, + Extension(actor): Extension, + Path(id): Path, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.device_not_found")); + } + let d = blocking(&st, move |c| { + pki(c)? + .revoke(&id, now())? + .ok_or(PkiFail::Code("pki.device_not_found")) + }) + .await?; + log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id); + st.ctl.devices_changed().await; + Ok(StatusCode::NO_CONTENT.into_response()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct BundleBody { + /// `p12` (a file to download) or `qr` (the same link as a QR code). + #[serde(default = "p12")] + pub format: String, +} + +fn p12() -> String { + "p12".into() +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct BundleView { + /// Works once, for 10 minutes. + pub download_url: String, + /// Asked for when the file is installed. Shown once. + pub one_time_password: String, + pub expires_at: String, + pub filename: String, + /// `format = "qr"`: the link as an SVG QR code. + pub qr_svg: Option, +} + +/// A one-time install file for a device (G15): PKCS#12, behind a link that works once. +#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody, + responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn make_bundle( + State(st): Shared, + Path(id): Path, + body: Body, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.device_not_found")); + } + let format = body.value.format; + if format != "p12" && format != "qr" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.body", + messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]), + )); + } + let (token, password, expires) = + blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?; + let url = bundle_url(&st, &token).await; + let qr_svg = if format == "qr" { + Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?) + } else { + None + }; + Ok(json( + StatusCode::OK, + &BundleView { + download_url: url, + one_time_password: password, + expires_at: rfc3339(expires), + filename: "domi-device.p12".into(), + qr_svg, + }, + )) +} + +/// Where a device downloads its file: through edge on the admin host when there is one +/// (as a share link when that host has share links on, so a device without a sign-in can +/// reach it; the link covers only this one-time path), else control's own address. +async fn bundle_url(st: &AppState, token: &str) -> String { + let c = &st.ctl; + let path = format!("/api/v1/device-bundles/{token}"); + let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else { + return format!("http://{}{path}", c.cfg.listen); + }; + let port = c.cfg.compile.https_listen.port(); + let authority = if port == 443 { + ui.clone() + } else { + format!("{ui}:{port}") + }; + let shares_on = c + .head_model() + .ok() + .and_then(|(_, _, m)| { + m.hosts() + .iter() + .find(|h| h.hostname.as_str() == ui) + .map(|h| h.share_links) + }) + .unwrap_or(false); + if shares_on + && c.engine_running() != "caddy" + && let Some(key) = &c.share_key + && let Ok(m) = c.shares.mint( + key, + &ui, + &path, + crate::shares::MIN_EXPIRY, + None, + None, + "device install", + ) + { + return format!( + "https://{authority}{}?{}={}", + m.record.path_prefix, + ianitor_core::share::QUERY_PARAM, + m.token + ); + } + format!("https://{authority}{path}") +} + +/// The one-time download itself. The link is the secret: no token or sign-in is needed, and +/// it works once. +#[utoipa::path(get, path = "/api/v1/device-bundles/{token}", tag = "certs", + responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))] +pub async fn download_bundle( + State(st): Shared, + Path(token): Path, +) -> Result { + if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) { + return Err(ApiError::new( + StatusCode::GONE, + "pki.bundle_used", + Params::new(), + )); + } + let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?; + log::info!(target: "ianitor::pki", "a device install file was downloaded"); + let mut r = bytes.into_response(); + let h = r.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/x-pkcs12"), + ); + h.insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_static("attachment; filename=\"domi-device.p12\""), + ); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + h.insert("referrer-policy", HeaderValue::from_static("no-referrer")); + Ok(r) +} + +// ---------------------------------------------------------------- engine + +#[derive(Debug, Serialize, ToSchema)] +pub struct EngineSwitchView { + /// `pingora` or `caddy`. + pub running: String, + /// `running`, `switching` or `stopped`. + pub state: String, + pub target: Option, + pub since: String, + /// Whether this server lets control switch (an `[engine]` section and its units). + pub switchable: bool, + /// Why the last switch did not happen. + pub last_error: Option, + /// What changes while Caddy serves. + pub notes: Vec, +} + +pub fn engine_view(c: &Control) -> EngineSwitchView { + let e = c.engine_state(); + let notes = if e.running == "caddy" { + ["engine.caddy", "share.engine_caddy"] + .iter() + .map(|code| Blocked { + code: (*code).into(), + message: message(code, &Params::new()), + }) + .collect() + } else { + Vec::new() + }; + EngineSwitchView { + running: e.running, + state: e.state, + target: e.target, + since: rfc3339(e.since), + switchable: c.engine_cfg().is_some() && c.units.is_some(), + last_error: e.last_error, + notes, + } +} + +/// Which engine serves. +#[utoipa::path(get, path = "/api/v1/engine", tag = "engine", + responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))] +pub async fn get_engine(State(st): Shared) -> Response { + json(StatusCode::OK, &engine_view(&st.ctl)) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct EngineBody { + /// `pingora` or `caddy`. + pub target: String, +} + +/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`. +#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody, + responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn switch_engine( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let target = body.value.target; + st.ctl.request_switch(&target).map_err(ApiError::from)?; + log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id); + Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl))) +} diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs new file mode 100644 index 0000000..e57a9dc --- /dev/null +++ b/crates/control/src/api/ui.rs @@ -0,0 +1,122 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device +//! downloads. The UI's files hold no data (it reads everything from the API, which the guard +//! protects), so they need no token; the Host check still applies against DNS rebinding. + +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +use axum::body::Body as AxumBody; +use axum::extract::{Path as AxPath, Request, State}; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; + +use super::{ApiError, AppState, host_allowed}; +use crate::messages::Params; + +const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \ + script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + +pub async fn front(State(st): State>, req: Request, next: Next) -> Response { + let path = req.uri().path().to_owned(); + if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") { + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()) + .into_response(); + } + if req.method() != axum::http::Method::GET { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + let token = token.to_owned(); + return super::pki::download_bundle(State(st), AxPath(token)) + .await + .unwrap_or_else(IntoResponse::into_response); + } + if path.starts_with("/api/") || path == "/api" { + return next.run(req).await; + } + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response(); + } + let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + }; + if !matches!(req.method().as_str(), "GET" | "HEAD") { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + serve_static(&dir, &path).await +} + +/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused; +/// a path without a file extension is the single-page app (`index.html`). +async fn serve_static(dir: &Path, url_path: &str) -> Response { + let rel = url_path.trim_start_matches('/'); + let clean = !rel.contains('\\') + && rel + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c)) + && Path::new(rel) + .components() + .all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.'))); + if !clean { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + } + let has_ext = Path::new(rel).extension().is_some(); + let file: PathBuf = if rel.is_empty() || !has_ext { + dir.join("index.html") + } else { + dir.join(rel) + }; + let Ok(bytes) = tokio::fs::read(&file).await else { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + }; + let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") { + "html" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "svg" => "image/svg+xml", + "png" => "image/png", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "json" | "webmanifest" => "application/json", + "txt" => "text/plain; charset=utf-8", + _ => "application/octet-stream", + }; + let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/"); + let mut r = Response::new(AxumBody::from(bytes)); + let h = r.headers_mut(); + h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype)); + h.insert( + header::CACHE_CONTROL, + HeaderValue::from_static(if immutable { + "public, max-age=31536000, immutable" + } else { + "no-cache" + }), + ); + h.insert("content-security-policy", HeaderValue::from_static(CSP)); + h.insert( + "x-content-type-options", + HeaderValue::from_static("nosniff"), + ); + h.insert("referrer-policy", HeaderValue::from_static("no-referrer")); + h.insert("x-frame-options", HeaderValue::from_static("DENY")); + r +} diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs index dfd5fc9..9e8db7e 100644 --- a/crates/control/src/api/views.rs +++ b/crates/control/src/api/views.rs @@ -406,6 +406,8 @@ pub struct HostRow { pub auth: String, pub websockets: bool, pub share_links: bool, + /// Visitors need a Domi device certificate. + pub device_certs: bool, pub added_at: Option, pub health: HealthView, pub certificate: CertView, @@ -439,13 +441,28 @@ pub struct Counts { #[derive(Debug, Clone, Serialize, ToSchema)] pub struct EngineView { - /// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)). + /// `pingora` or `caddy`. pub running: String, - /// `running` or `stopped` (control cannot reach it). + /// `running`, `switching` or `stopped` (control cannot reach it). pub state: String, pub since: Option, - #[schema(value_type = Option)] - pub fallback_ready: Option, + /// The engine a running switch goes to. + pub target: Option, + /// Whether control can switch on this server (`[engine]` in control.toml). + pub switchable: bool, + /// The fallback's config: when it was written and whether it is the current tree's. + pub fallback_ready: Option, + /// Why the last switch did not happen. + pub last_error: Option, + /// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`). + pub notes: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct FallbackReady { + pub built_at: Option, + /// caddy.json is the compiled current tree. + pub current: bool, } #[derive(Debug, Clone, Serialize, ToSchema)] @@ -507,9 +524,8 @@ pub struct Overview { pub undo: UndoView, pub active_apply: Option, pub repo: Option, - /// The Domi intermediate; arrives in phase 3. - #[schema(value_type = Option)] - pub intermediate: Option, + /// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`). + pub intermediate: Option, pub site: Option, pub paused: Option, /// Set when control cannot read health from edge (`health.unavailable`). @@ -526,7 +542,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option { } pub fn undo_view(c: &Control) -> UndoView { - let blocked = if let Some(p) = c.paused() { + let blocked = if let Some(p) = c.effective_pause() { Some(Blocked { code: "undo.paused".into(), message: message("undo.paused", &messages::Params::new()) + " " + &p.message, @@ -621,6 +637,7 @@ pub fn host_rows( auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(), websockets: spec.as_ref().is_none_or(|s| s.websockets), share_links: spec.as_ref().is_some_and(|s| s.share_links), + device_certs: spec.as_ref().is_some_and(|s| s.device_certs), added_at: added_at(c, &h), health: health_view(st, spec.as_ref(), since.get(&h).copied()), certificate: cert_view(st, spec.as_ref()), diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 573484d..fdf4b11 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -143,6 +143,8 @@ pub struct Control { pub share_key: Option, /// The Domi CA, when `[pki]` is configured. pub pki: Option, + /// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`. + pub ui_proof: Option>, /// Which engine serves (see `switch`). pub engine: Mutex, /// How control starts and stops the engines; `None` without `[engine]`. @@ -238,6 +240,12 @@ impl Control { repo, edge, share_key, + ui_proof: cfg + .ui + .as_ref() + .and_then(|u| u.proof_credential.as_deref()) + .and_then(|n| cfg.credential(n)) + .filter(|p| p.len() >= 32), pki, engine: Mutex::new(crate::switch::EngineState { running: cfg diff --git a/crates/control/src/hostspec.rs b/crates/control/src/hostspec.rs index 538a72c..2b7e8ec 100644 --- a/crates/control/src/hostspec.rs +++ b/crates/control/src/hostspec.rs @@ -26,6 +26,9 @@ pub struct HostSpec { pub websockets: bool, #[serde(default)] pub share_links: bool, + /// Visitors need a Domi device certificate (mTLS). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub device_certs: bool, /// `off` or `truncated`. #[serde(default = "off")] pub access_log: String, @@ -115,6 +118,11 @@ impl HostSpec { to.share_links.to_string(), ); push("access_log", self.access_log.clone(), to.access_log.clone()); + push( + "device_certs", + self.device_certs.to_string(), + to.device_certs.to_string(), + ); let hc = |h: &Option| h.as_ref().map(|h| (h.path.clone(), h.interval_secs)); let (a, b) = (hc(&self.health_check), hc(&to.health_check)); @@ -157,6 +165,7 @@ mod tests { auth: "none".into(), websockets: false, share_links: true, + device_certs: true, access_log: "truncated".into(), health_check: Some(HealthCheckSpec { path: "/health".into(), diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 3740c9c..578d27d 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -39,6 +39,7 @@ pub async fn serve( tokio::spawn(ctl.clone().worker()); tokio::spawn(ctl.clone().health_poller()); tokio::spawn(ctl.clone().pusher()); + tokio::spawn(ctl.clone().pki_poller()); let app = api::router(api::AppState::new(ctl.clone())); if !listen.ip().is_loopback() { return Err("ianitor-control only listens on loopback".into()); diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index 063e2b3..c2a6375 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -9,6 +9,11 @@ //! ianitor-control token list (--config | --state-dir ) //! ianitor-control token revoke (--config | --state-dir ) //! ianitor-control openapi print the OpenAPI document +//! ianitor-control pki approve|deny (--config | --state-dir ) approve a device request +//! ianitor-control pki install (--config ) install a signed intermediate +//! ianitor-control pki status (--config ) open requests +//! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) +//! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), @@ -197,6 +202,168 @@ fn token(args: &[String]) -> Result<(), String> { } } +fn arg_after(args: &[String], name: &str) -> Option { + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == name { + return it.next().cloned(); + } + } + None +} + +/// A passphrase from `--passphrase-file`, or asked on the terminal without echo. +fn passphrase(args: &[String], confirm: bool) -> Result { + if let Some(f) = arg_after(args, "--passphrase-file") { + let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?; + let v = v.trim_end_matches(['\r', '\n']).to_owned(); + if v.chars().count() < 12 { + return Err("the passphrase must have at least 12 characters".into()); + } + return Ok(v); + } + let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?; + if p.chars().count() < 12 { + return Err("the passphrase must have at least 12 characters".into()); + } + if confirm { + let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?; + if again != p { + return Err("the two passphrases differ".into()); + } + } + Ok(p) +} + +/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the +/// server. +fn ca(args: &[String]) -> Result<(), String> { + use ianitor_core::pki; + let now = ianitor_control::util::now() as i64; + match args.first().map(String::as_str) { + Some("init") => { + let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out ")?); + let crt = out.join("domi-root.crt"); + let key = out.join("domi-root.key"); + if crt.exists() || key.exists() { + return Err(format!( + "{} already has a root; refusing to replace it", + out.display() + )); + } + std::fs::create_dir_all(&out).map_err(|e| e.to_string())?; + let pass = passphrase(args, true)?; + let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?; + let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600) + .map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + let info = pki::inspect(&cert).map_err(|e| e.to_string())?; + eprintln!( + "Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\ + Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\ + Keep domi-root.key and its passphrase offline (Custos, once it can hold it).", + out.display(), + info.subject_cn, + ianitor_core::time::long_date(info.not_after.max(0) as u64), + info.sha256_hex + ); + Ok(()) + } + Some("sign") => { + let root = PathBuf::from( + arg_after(args, "--root") + .ok_or("ca sign --root --csr --out ")?, + ); + let csr_path = arg_after(args, "--csr").ok_or("--csr is required")?; + let out = PathBuf::from(arg_after(args, "--out").ok_or("--out is required")?); + let csr = std::fs::read_to_string(&csr_path) + .map_err(|e| format!("cannot read {csr_path}: {e}"))?; + let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?); + eprintln!("This request's code is {code}. It must be the code Ianitor shows."); + if !args.iter().any(|a| a == "--yes") { + let typed = rpassword::prompt_password("Type the code to sign (no echo): ") + .map_err(|e| e.to_string())?; + if ianitor_control::pki::normalise_code(&typed) + != ianitor_control::pki::normalise_code(&code) + { + return Err("the code does not match; nothing was signed".into()); + } + } + let cert = + std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?; + let sealed = + std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?; + let pass = passphrase(args, false)?; + let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?; + let signed = + pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + let info = pki::inspect(&signed).map_err(|e| e.to_string())?; + eprintln!( + "Signed {} until {}. Install it on the server: ianitor-control pki install {}", + info.subject_cn, + ianitor_core::time::long_date(info.not_after.max(0) as u64), + out.display() + ); + Ok(()) + } + _ => Err("ca init --out | ca sign --root --csr --out ".into()), + } +} + +/// `pki approve|deny|install|status` on the server, as the user control runs as. +fn pki_cli(args: &[String]) -> Result<(), String> { + let dir = state_dir(args)?; + same_owner(&dir)?; + let now = ianitor_control::util::now(); + match args.first().map(String::as_str) { + Some(verb @ ("approve" | "deny")) => { + // The code may be given as one word or three (47 19 83). + let code: String = args + .iter() + .skip(1) + .take_while(|a| !a.starts_with("--")) + .cloned() + .collect::>() + .join(""); + let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?; + eprintln!( + "{} the request for \"{}\" ({}). Control acts on it within a few seconds.", + if verb == "deny" { "Turned down" } else { "Approved" }, + r.name.unwrap_or_default(), + r.id + ); + Ok(()) + } + Some("install") => { + let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install ")?; + let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?; + let r = ianitor_control::pki::cli_install(&dir, &pem, now)?; + eprintln!("Handed to renewal {}. Control installs it within a few seconds.", r.id); + Ok(()) + } + Some("status") => { + let rs: Vec = + ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default(); + for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) { + println!( + "{} {} {} code {} until {}", + r.id, + r.kind, + r.name.clone().unwrap_or_default(), + r.match_code, + ianitor_control::util::rfc3339(r.expires_at) + ); + } + Ok(()) + } + _ => Err("pki approve | pki deny | pki install | pki status (--config | --state-dir )".into()), + } +} + fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); @@ -215,6 +382,8 @@ fn main() -> ExitCode { }; let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), + Some("pki") => pki_cli(&args[1..]), + Some("ca") => ca(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); Ok(()) diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs index d68c990..f5b4fec 100644 --- a/crates/control/src/pki.rs +++ b/crates/control/src/pki.rs @@ -279,12 +279,7 @@ impl Pki { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - let mode = if d.ends_with("approvals") { - 0o700 - } else { - 0o700 - }; - let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)); + let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)); } } Ok(Pki { diff --git a/crates/control/src/switch.rs b/crates/control/src/switch.rs index 5bd6e15..b7311f6 100644 --- a/crates/control/src/switch.rs +++ b/crates/control/src/switch.rs @@ -22,6 +22,9 @@ //! //! The systemd calls go through [`Units`], so tests use a fake. +// A refusal is built once per request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -382,6 +385,11 @@ impl Control { Ok(()) } + /// Any reason changes wait now: Caddy serving, or a pause. + pub fn effective_pause(&self) -> Option { + self.engine_pause().or_else(|| self.paused()) + } + /// Changes wait while Caddy serves. pub fn engine_pause(&self) -> Option { (self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new())) diff --git a/crates/control/tests/api.rs b/crates/control/tests/api.rs index 2d45a8c..c41f05c 100644 --- a/crates/control/tests/api.rs +++ b/crates/control/tests/api.rs @@ -34,6 +34,11 @@ mod unix { fn routes(doc: &Value) -> Vec<(String, String)> { let mut out = Vec::new(); for (path, item) in doc["paths"].as_object().unwrap() { + // The one-time device download is the one call without a token: the link is + // the secret (G15). Every other call needs one. + if path.starts_with("/api/v1/device-bundles/") { + continue; + } for method in ["get", "post", "put", "patch", "delete"] { if item.get(method).is_some() { let p = path @@ -118,14 +123,14 @@ mod unix { vec![("Authorization".into(), "Bearer ".into())], "token.unknown", ), - // Identity headers do not authenticate (docs/ui-api.md G14). + // Identity headers without edge's proof are refused (docs/ui-api.md G14). ( "remote-user".into(), vec![ ("Remote-User".into(), "mark".into()), ("Remote-Groups".into(), "admins".into()), ], - "token.missing", + "ui.no_proof", ), ]; for (what, headers, code) in &cases { @@ -147,7 +152,8 @@ mod unix { env.call_with("GET", "/api/v1/nope", &[], None).await.status, 401 ); - assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401); + // Outside /api/ only the built UI is served (no data, no token); none is set up here. + assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404); // A wrong Host header (DNS rebinding) is refused even with a good token. let auth = format!("Bearer {}", env.token); diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs index 9e14f54..b54d2d4 100644 --- a/crates/control/tests/pki.rs +++ b/crates/control/tests/pki.rs @@ -116,7 +116,16 @@ mod unix { let r2 = env .call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None) .await; - assert_eq!(r2.status, 200); + assert_eq!( + r2.status, + 200, + "{} +{} +{}", + r.text, + r2.text, + env.control_log() + ); assert_eq!(r2.text, csr); let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); let f = env.dir.join("signed.crt"); @@ -170,7 +179,8 @@ mod unix { i64::from(pki::SERVER_DAYS) - 1 ); - // No root key anywhere control writes. + // No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same + // for every key, so the unique end is compared.) let key_pem = off.root_key.serialize_pem(); let body: String = key_pem .lines() @@ -181,7 +191,7 @@ mod unix { let bytes = std::fs::read(&f).unwrap(); let text = String::from_utf8_lossy(&bytes); assert!( - !text.contains(&body[..40]), + !text.contains(&body[body.len() - 40..]), "root key material in {}", f.display() ); @@ -407,7 +417,7 @@ mod unix { let p = e.path(); if p.is_dir() { stack.push(p); - } else { + } else if p.is_file() { out.push(p); } } diff --git a/crates/edge/src/admin.rs b/crates/edge/src/admin.rs index 9ffd085..505142b 100644 --- a/crates/edge/src/admin.rs +++ b/crates/edge/src/admin.rs @@ -235,6 +235,10 @@ async fn handle(shared: Arc, req: Request) -> Resp { } } ("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })), + ("POST", "/v1/device-certs/reload") => match shared.reload_device_trust() { + Ok(n) => reply(StatusCode::OK, json!({ "reloaded": true, "allowed": n })), + Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + }, ("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() { Ok(()) => { let r = shared.revocations(); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index a69f400..134f9ea 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -131,7 +131,9 @@ impl ProxyHttp for EdgeProxy { let rt = self.shared.current(); ctx.rt = Some(rt.clone()); ctx.host_header = host_header(session.req_header()); - if rt.device_trust.is_some() && sni_mismatch(session, &hostname(&ctx.host_header)) { + if self.shared.devices.current().is_some() + && sni_mismatch(session, &hostname(&ctx.host_header)) + { // Like Caddy once client certificates are configured: a request for another host // than the one the TLS connection was opened for is refused, so a connection // that was never asked for a certificate cannot reach a device host. @@ -144,7 +146,7 @@ impl ProxyHttp for EdgeProxy { }; ctx.host = Some(host.clone()); - if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) { + if host.cfg.device_certs && !has_allowed_device_cert(session, &self.shared) { // No certificate on this connection (one that is presented but not allowed never // gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream. respond_empty(session, 403).await?; @@ -441,8 +443,8 @@ fn sni_mismatch(session: &Session, host: &str) -> bool { /// Did this connection present a device certificate that the current config allows? The /// handshake already checked the chain and the list; this checks again against the runtime /// serving the request, so a revocation also ends requests on connections made before it. -fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool { - let Some(trust) = rt.device_trust.as_ref() else { +fn has_allowed_device_cert(session: &Session, shared: &crate::shared::Shared) -> bool { + let Some(trust) = shared.devices.current() else { return false; }; session diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index a6e2fac..0493b20 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -187,7 +187,16 @@ impl Shared { fn install(&self, rt: Arc) { self.certs.replace_files(rt.file_certs.clone()); - self.devices.replace(rt.device_trust.clone()); + // Read the device files again: the runtime may be older than the latest allow list + // (a revert after a revocation must not let a revoked device back in). + let trust = match fresh_trust(&rt) { + Ok(t) => t, + Err(e) => { + log::error!(target: "ianitor::tls", "{e}; keeping the device check this config was built with"); + rt.device_trust.clone() + } + }; + self.devices.replace(trust); self.current.store(rt); self.generation.fetch_add(1, Ordering::SeqCst); self.notify(); @@ -496,3 +505,36 @@ fn poisoned() -> AdminError { fn short(sha: &str) -> &str { sha.get(..12).unwrap_or(sha) } + +/// The device check for a runtime, built from the files as they are now. +fn fresh_trust(rt: &Runtime) -> Result>, String> { + let Some(dc) = &rt.cfg.device_certs else { + return Ok(None); + }; + let hosts: std::collections::HashSet = rt + .cfg + .hosts + .iter() + .filter(|h| h.device_certs) + .map(|h| h.hostname.clone()) + .collect(); + if hosts.is_empty() { + return Ok(None); + } + let ca = std::fs::read(&dc.ca).map_err(|e| format!("cannot read {}: {e}", dc.ca))?; + let allow = std::fs::read(&dc.allow).map_err(|e| format!("cannot read {}: {e}", dc.allow))?; + crate::tls::DeviceTrust::new(&ca, &allow, hosts).map(|t| Some(Arc::new(t))) +} + +impl Shared { + /// Re-read the device CA bundle and allow list now (control calls this after an issue + /// or a revocation; allowed during a trial). Returns how many devices are allowed. + pub fn reload_device_trust(&self) -> Result { + let rt = self.current(); + let t = fresh_trust(&rt)?; + let n = t.as_ref().map_or(0, |t| t.allowed()); + self.devices.replace(t); + log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed"); + Ok(n) + } +} diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 51e345c..347acef 100644 --- a/crates/edge/src/tls.rs +++ b/crates/edge/src/tls.rs @@ -159,6 +159,10 @@ impl DeviceTrust { }) } + pub fn allowed(&self) -> usize { + self.allow.len() + } + pub fn allows(&self, cert_sha256: &[u8]) -> bool { <[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d)) } -- 2.53.0 From 12886a1d319206fadd14917c21f6da34fd64b31b Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:22:59 +0100 Subject: [PATCH 10/34] [control] Engine switch: POST /engine through a Units abstraction (systemctl via polkit, a fake in tests); engine file first, back to the old engine if the new one does not serve; changes and share links wait while Caddy serves --- crates/control/tests/engine_switch.rs | 227 ++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 crates/control/tests/engine_switch.rs diff --git a/crates/control/tests/engine_switch.rs b/crates/control/tests/engine_switch.rs new file mode 100644 index 0000000..0a31815 --- /dev/null +++ b/crates/control/tests/engine_switch.rs @@ -0,0 +1,227 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Switching the engine at runtime (ROADMAP §3, §4; G18) with a fake `systemctl`: the engine +//! file is written first, the old unit stopped and the new one started; while Caddy serves, +//! changes and share links wait; a switch whose target does not come up goes back. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux; run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::{Duration, Instant}; + + use crate::common::{Env, EnvSpec}; + use serde_json::{Value, json}; + + /// Records every call; `is-active` answers from marker files; a unit named in + /// `fail-start` cannot start. + const FAKE: &str = r#"#!/bin/sh +dir="$(dirname "$0")/units" +mkdir -p "$dir" +[ "$1" = "--no-ask-password" ] && shift +echo "$*" >> "$dir/../calls.log" +case "$1" in + start) if grep -qx "$2" "$dir/../fail-start" 2>/dev/null; then exit 1; fi; touch "$dir/$2" ;; + stop) rm -f "$dir/$2" ;; + restart) touch "$dir/$2" ;; + is-active) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; + *) exit 2 ;; +esac +"#; + + async fn env() -> Env { + let mut env = Env::new(EnvSpec::default()).await; + let fake = env.dir.join("fake/systemctl"); + std::fs::create_dir_all(env.dir.join("fake/units")).unwrap(); + std::fs::write(&fake, FAKE).unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + // Edge runs now. + std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + "\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n", + env.dir.join("engine").display(), + fake.display() + ); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + env + } + + fn calls(env: &Env) -> Vec { + std::fs::read_to_string(env.dir.join("fake/calls.log")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .filter(|l| !l.starts_with("is-active")) + .collect() + } + + async fn wait_engine(env: &Env, running: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let r = env.call("GET", "/api/v1/engine", None).await; + assert_eq!(r.status, 200, "{}", r.text); + if r.json["state"] == "running" && r.json["running"] == running { + return r.json; + } + if Instant::now() > deadline { + panic!("engine is {}\n{}", r.text, env.control_log()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn switch_to_caddy_and_back() { + let env = env().await; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let host = json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], + "tls": "domi", "auth": "none", "share_links": true}}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(rec["state"], "kept", "{rec}"); + + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let e = wait_engine(&env, "caddy").await; + assert!(e["last_error"].is_null(), "{e}"); + assert_eq!( + calls(&env), + ["stop ianitor-edge.service", "start caddy-fallback.service"] + ); + assert_eq!( + std::fs::read_to_string(env.dir.join("engine")).unwrap(), + "caddy" + ); + // Caddy starts from the current tree. + let caddy = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap(); + assert!(caddy.contains("a.test")); + + // While Caddy serves: changes and share links wait, the overview says so. + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text); + assert_eq!(ov.json["paused"]["code"], "engine.caddy", "{}", ov.text); + assert_eq!(ov.json["site"]["share_links_available"], false); + let add = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({"host": {"hostname": "b.test", "upstreams": ["http://127.0.0.1:9"], "tls": "domi"}})), + ) + .await; + assert_eq!(add.status, 409, "{}", add.text); + let share = env + .call( + "POST", + "/api/v1/hosts/a.test/share-links", + Some(json!({"path_prefix": "/", "expires_in_s": 86400})), + ) + .await; + assert_eq!(share.status, 409, "{}", share.text); + assert_eq!(share.json["error"]["code"], "share.engine_caddy"); + // The same target again is refused. + let again = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(again.status, 409); + assert_eq!(again.json["error"]["code"], "engine.same"); + + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "pingora"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + wait_engine(&env, "pingora").await; + assert_eq!( + calls(&env)[2..], + ["stop caddy-fallback.service", "start ianitor-edge.service"] + ); + assert_eq!( + std::fs::read_to_string(env.dir.join("engine")).unwrap(), + "pingora" + ); + let ov = env.call("GET", "/api/v1/overview", None).await; + assert!(ov.json["paused"].is_null(), "{}", ov.text); + let share = env + .call( + "POST", + "/api/v1/hosts/a.test/share-links", + Some(json!({"path_prefix": "/", "expires_in_s": 86400})), + ) + .await; + assert_eq!(share.status, 201, "{}", share.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_target_that_does_not_start_switches_back() { + let env = env().await; + std::fs::write(env.dir.join("fake/fail-start"), "caddy-fallback.service\n").unwrap(); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + // It ends where it started, and says why. + let deadline = Instant::now() + Duration::from_secs(30); + let e = loop { + let r = env.call("GET", "/api/v1/engine", None).await; + if r.json["state"] == "running" && !r.json["last_error"].is_null() { + break r.json; + } + assert!(Instant::now() < deadline, "{}", r.text); + tokio::time::sleep(Duration::from_millis(100)).await; + }; + assert_eq!(e["running"], "pingora"); + assert_eq!(e["last_error"]["code"], "engine.switch_failed"); + assert_eq!( + calls(&env), + [ + "stop ianitor-edge.service", + "start caddy-fallback.service", + "stop caddy-fallback.service", + "start ianitor-edge.service" + ] + ); + assert_eq!( + std::fs::read_to_string(env.dir.join("engine")).unwrap(), + "pingora" + ); + // Changes go on as before. + let ov = env.call("GET", "/api/v1/overview", None).await; + assert!(ov.json["paused"].is_null(), "{}", ov.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn without_engine_settings_nothing_switches() { + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "engine.unmanaged"); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "nginx"}))) + .await; + assert_eq!(r.status, 409); + let e = env.call("GET", "/api/v1/engine", None).await; + assert_eq!(e.json["switchable"], false); + } +} -- 2.53.0 From 6237e721d62533f8bb182223dd5cb5b42f3d14c9 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:23:51 +0100 Subject: [PATCH 11/34] [control] Test hooks: IANITOR_TEST_CRASH_AT and IANITOR_TEST_FAIL_WRITE only with the default test-hooks feature; a --no-default-features build has neither --- crates/control/Cargo.toml | 6 ++++++ crates/control/src/crash.rs | 20 +++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index d2a3801..74615ba 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -15,6 +15,12 @@ path = "src/lib.rs" name = "ianitor-control" path = "src/main.rs" +[features] +# The crash and write-failure hooks of the crash-safety tests (src/crash.rs). The Nix release +# build turns them off with --no-default-features. +default = ["test-hooks"] +test-hooks = [] + [dependencies] ianitor-core.workspace = true axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] } diff --git a/crates/control/src/crash.rs b/crates/control/src/crash.rs index b85bbe4..34354da 100644 --- a/crates/control/src/crash.rs +++ b/crates/control/src/crash.rs @@ -4,10 +4,13 @@ //! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=` in its //! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage. -//! Without the variable this does nothing; the NixOS unit never sets it. //! //! `IANITOR_TEST_FAIL_WRITE=` makes every write of a state file with that name //! fail, as on a full disk (fault injection for the same tests). +//! +//! Both exist only with the `test-hooks` cargo feature (on by default, so `cargo test` has +//! them). The release build (`nix build .#ianitor`) is built with `--no-default-features`: +//! there these functions do nothing and read no environment variable. /// The stages, in order. pub const STAGES: [&str; 9] = [ @@ -22,6 +25,10 @@ pub const STAGES: [&str; 9] = [ "reverting", ]; +/// Whether this binary has the test hooks. +pub const ENABLED: bool = cfg!(feature = "test-hooks"); + +#[cfg(feature = "test-hooks")] pub fn point(stage: &str) { if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) { log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: aborting on purpose"); @@ -29,7 +36,12 @@ pub fn point(stage: &str) { } } +#[cfg(not(feature = "test-hooks"))] +#[inline(always)] +pub fn point(_stage: &str) {} + /// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file. +#[cfg(feature = "test-hooks")] pub fn fail_write(path: &std::path::Path) -> Result<(), String> { match ( std::env::var_os("IANITOR_TEST_FAIL_WRITE"), @@ -42,3 +54,9 @@ pub fn fail_write(path: &std::path::Path) -> Result<(), String> { _ => Ok(()), } } + +#[cfg(not(feature = "test-hooks"))] +#[inline(always)] +pub fn fail_write(_path: &std::path::Path) -> Result<(), String> { + Ok(()) +} -- 2.53.0 From f9dd2247f8ddb0206dd020bdbfb8784665e6b4fb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:24:45 +0100 Subject: [PATCH 12/34] [control] Dev mode: a throw-away Domi root signs the first intermediate at start, so tls = "domi" works for any name; --ui-dir serves a built UI --- Cargo.lock | 1 - crates/control/Cargo.toml | 1 - crates/control/src/dev.rs | 86 ++++++++++++++++++++------------------- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1a4ccad..b89b3d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1301,7 +1301,6 @@ dependencies = [ "log", "p12-keystore", "qrcode", - "rcgen", "ring", "rpassword", "rustls", diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 74615ba..03a2c4a 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -35,7 +35,6 @@ ring.workspace = true base64.workspace = true http.workspace = true bytes.workspace = true -rcgen.workspace = true # Device certificate install files (PKCS#12) and their QR codes. p12-keystore = "0.4" qrcode = { version = "0.14", default-features = false, features = ["svg"] } diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 22f43c3..80b0122 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -18,42 +18,16 @@ use ianitor_control::repo::Repo; use ianitor_control::tokens::Tokens; use ianitor_control::util::{hex, random, write_atomic}; -/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them. -const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"]; - -/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`. -fn dev_certs(dir: &Path) -> Result<(), String> { - use rcgen::{ - BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose, - }; - let e = |x: rcgen::Error| x.to_string(); - let ca_key = KeyPair::generate().map_err(e)?; - let mut ca = CertificateParams::new(Vec::::new()).map_err(e)?; - ca.distinguished_name - .push(DnType::CommonName, "Ianitor dev CA"); - ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); - ca.key_usages = vec![ - KeyUsagePurpose::KeyCertSign, - KeyUsagePurpose::DigitalSignature, - ]; - let ca_cert = ca.self_signed(&ca_key).map_err(e)?; - std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?; - let issuer = Issuer::new(ca, ca_key); - for h in DEV_HOSTS { - let key = KeyPair::generate().map_err(e)?; - let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?; - p.distinguished_name.push(DnType::CommonName, h); - let cert = p.signed_by(&key, &issuer).map_err(e)?; - std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem()) - .map_err(|x| x.to_string())?; - write_atomic( - &dir.join(format!("certs/{h}.key")), - key.serialize_pem().as_bytes(), - 0o600, - ) - .map_err(|x| x.to_string())?; - } - Ok(()) +/// A throw-away Domi root for dev mode, in `offline-root/` (its key stays in memory, like +/// on the offline machine), and the PKI password credential. Control then works like +/// production: it issues server certificates for every `tls = "domi"` host. +fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> { + let (root, key) = + ianitor_core::pki::create_root(ianitor_control::util::now() as i64).map_err(|e| e.to_string())?; + std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?; + let pass = hex(&random::<24>().map_err(|e| e.to_string())?); + write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600).map_err(|e| e.to_string())?; + Ok((root, key)) } const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\ @@ -125,10 +99,11 @@ pub async fn run(args: &[String]) -> Result<(), String> { "creds", "logs", "edge-state", + "offline-root", ] { std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?; } - dev_certs(&dir)?; + let (root_pem, root_key) = dev_pki(&dir)?; let key = hex(&random::<32>().map_err(|e| e.to_string())?); write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600) .map_err(|e| e.to_string())?; @@ -174,8 +149,17 @@ pub async fn run(args: &[String]) -> Result<(), String> { caddy_admin: None, }, compile_caddy: None, - pki: None, - ui: None, + pki: Some(ianitor_control::config::PkiConfig { + root_cert: dir.join("offline-root/domi-root.crt"), + password_credential: "pki-password".into(), + approval: "manual".into(), + kdf_iterations: 10_000, + }), + ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig { + hostname: None, + proof_credential: None, + static_dir: Some(PathBuf::from(d)), + }), engine: None, }; cfg.check().map_err(|e| e.to_string())?; @@ -186,6 +170,21 @@ pub async fn run(args: &[String]) -> Result<(), String> { // Control writes edge.json first; then edge can start from it. let ctl_cfg = cfg.clone(); let opened = ianitor_control::Control::open(ctl_cfg).await?; + // Dev only: sign the first intermediate with the throw-away root at once (in production + // this is the offline step in docs/pki.md). + if let Some(p) = &opened.pki { + let now = ianitor_control::util::now(); + let r = p.request_renewal(now, "dev").map_err(|e| e.to_string())?; + let signed = ianitor_core::pki::sign_intermediate( + &root_pem, + &root_key, + r.csr_pem.as_deref().unwrap_or_default(), + now as i64, + ) + .map_err(|e| e.to_string())?; + p.install_intermediate(&r.id, &signed, now) + .map_err(|e| e.to_string())?; + } drop(opened); if let Some(bin) = &edge_bin { cleanup.edge = Some(start_edge(bin, &dir, &cfg)?); @@ -195,16 +194,19 @@ pub async fn run(args: &[String]) -> Result<(), String> { println!("Routes repository: {}", cfg.routes.repo.display()); match &edge_bin { Some(b) => println!( - "Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for {}; CA: {}", + "Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for any name; Domi root: {}", b.display(), - DEV_HOSTS.join(", "), - dir.join("certs/dev-ca.crt").display() + dir.join("offline-root/domi-root.crt").display() ), None => println!( "No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)." ), } println!("API token (shown once): {token}"); + println!( + "Approve a device request: ianitor-control pki approve --state-dir {}", + dir.join("state").display() + ); println!("Press Ctrl-C to stop and remove {}", dir.display()); let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await; drop(cleanup); -- 2.53.0 From aed5fbfcff7f649b1b01a678ba33d134a19ef10c Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:44:25 +0100 Subject: [PATCH 13/34] [control] Overview for the UI: who is looking (viewer) and the underlying pause reason, so the UI offers the right action --- crates/control/src/api/handlers.rs | 15 ++++++++++++++- crates/control/src/api/views.rs | 12 ++++++++++++ crates/control/src/dev.rs | 7 ++++--- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index a1f69dc..3670e49 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -128,7 +128,11 @@ fn replay(st: &AppState, s: Stored) -> Response { #[utoipa::path(get, path = "/api/v1/overview", tag = "overview", responses((status = 200, body = Overview), (status = 304, description = "Unchanged since the ETag"), (status = 401, body = ErrorEnvelope)), security(("bearer" = [])))] -pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result { +pub async fn overview( + State(st): Shared, + Extension(actor): Extension, + headers: HeaderMap, +) -> Result { let c = &st.ctl; let (status, error, since) = { let h = c @@ -227,6 +231,7 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result Result, pub site: Option, pub paused: Option, + /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`, + /// `repo.unreadable`, `engine.caddy`, …), so the UI can offer the right action. + pub paused_reason: Option, /// Set when control cannot read health from edge (`health.unavailable`). pub health_error: Option, pub rev: Option, + /// Who is looking: the Authelia user (through edge) or the API token's name. + pub viewer: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Viewer { + pub name: String, + /// `authelia` or `token`. + pub via: String, } pub fn added_at(c: &Control, hostname: &str) -> Option { diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 80b0122..921bda0 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -22,11 +22,12 @@ use ianitor_control::util::{hex, random, write_atomic}; /// on the offline machine), and the PKI password credential. Control then works like /// production: it issues server certificates for every `tls = "domi"` host. fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> { - let (root, key) = - ianitor_core::pki::create_root(ianitor_control::util::now() as i64).map_err(|e| e.to_string())?; + let (root, key) = ianitor_core::pki::create_root(ianitor_control::util::now() as i64) + .map_err(|e| e.to_string())?; std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?; let pass = hex(&random::<24>().map_err(|e| e.to_string())?); - write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600).map_err(|e| e.to_string())?; + write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600) + .map_err(|e| e.to_string())?; Ok((root, key)) } -- 2.53.0 From 3e326e85a062ebc7688a5db8324b5151fc70e34e Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 23:44:27 +0100 Subject: [PATCH 14/34] =?UTF-8?q?[web]=20The=20web=20UI:=20hosts,=20add/ed?= =?UTF-8?q?it=20with=20apply=20progress,=20undo,=20history=20and=20restore?= =?UTF-8?q?,=20share=20links,=20engine=20switch,=20certificates=20and=20de?= =?UTF-8?q?vice=20installs,=20signing=20by=20hand,=20settings=20and=20toke?= =?UTF-8?q?ns;=20smoke=20test=20counts=20every=20=C2=A74=20flow's=20clicks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/index.html | 17 + apps/web/package.json | 25 +- apps/web/src/App.svelte | 160 ++ apps/web/src/components/ApplyProgress.svelte | 80 + apps/web/src/components/ChangeBar.svelte | 140 ++ apps/web/src/components/EnginePopover.svelte | 107 + apps/web/src/components/HostList.svelte | 142 ++ apps/web/src/components/HostMenu.svelte | 86 + apps/web/src/components/HostPanel.svelte | 499 +++++ .../src/components/IntermediateBanner.svelte | 69 + apps/web/src/components/ShareDialog.svelte | 163 ++ apps/web/src/components/TopBanners.svelte | 73 + apps/web/src/lib/api.ts | 184 ++ apps/web/src/lib/app.svelte.ts | 150 ++ apps/web/src/lib/applies.ts | 58 + apps/web/src/lib/format.ts | 99 + apps/web/src/lib/types.ts | 247 +++ apps/web/src/main.ts | 11 + apps/web/src/views/Certificates.svelte | 245 +++ apps/web/src/views/History.svelte | 179 ++ apps/web/src/views/Hosts.svelte | 141 ++ apps/web/src/views/RenewByHand.svelte | 110 + apps/web/src/views/Settings.svelte | 279 +++ apps/web/src/views/SignedIn.svelte | 33 + apps/web/svelte.config.js | 7 + apps/web/tests/flows.test.ts | 202 ++ apps/web/tests/mockApi.ts | 174 ++ apps/web/tests/setup.ts | 39 + apps/web/tsconfig.json | 19 + apps/web/vite.config.ts | 38 + docs/ui-handoff.md | 1443 ++++++++++++++ docs/ui-open-questions.md | 159 ++ packages/ui/package.json | 22 + packages/ui/src/Banner.svelte | 48 + packages/ui/src/Button.svelte | 62 + packages/ui/src/Details.svelte | 32 + packages/ui/src/Dialog.svelte | 73 + packages/ui/src/Icon.svelte | 10 + packages/ui/src/Progress.svelte | 21 + packages/ui/src/Segmented.svelte | 45 + packages/ui/src/Status.svelte | 14 + packages/ui/src/components.css | 196 ++ packages/ui/src/icons.ts | 30 + packages/ui/src/index.ts | 14 + packages/ui/src/status.ts | 13 + packages/ui/src/tokens.css | 150 ++ pnpm-lock.yaml | 1763 +++++++++++++++++ 47 files changed, 7868 insertions(+), 3 deletions(-) create mode 100644 apps/web/index.html create mode 100644 apps/web/src/App.svelte create mode 100644 apps/web/src/components/ApplyProgress.svelte create mode 100644 apps/web/src/components/ChangeBar.svelte create mode 100644 apps/web/src/components/EnginePopover.svelte create mode 100644 apps/web/src/components/HostList.svelte create mode 100644 apps/web/src/components/HostMenu.svelte create mode 100644 apps/web/src/components/HostPanel.svelte create mode 100644 apps/web/src/components/IntermediateBanner.svelte create mode 100644 apps/web/src/components/ShareDialog.svelte create mode 100644 apps/web/src/components/TopBanners.svelte create mode 100644 apps/web/src/lib/api.ts create mode 100644 apps/web/src/lib/app.svelte.ts create mode 100644 apps/web/src/lib/applies.ts create mode 100644 apps/web/src/lib/format.ts create mode 100644 apps/web/src/lib/types.ts create mode 100644 apps/web/src/main.ts create mode 100644 apps/web/src/views/Certificates.svelte create mode 100644 apps/web/src/views/History.svelte create mode 100644 apps/web/src/views/Hosts.svelte create mode 100644 apps/web/src/views/RenewByHand.svelte create mode 100644 apps/web/src/views/Settings.svelte create mode 100644 apps/web/src/views/SignedIn.svelte create mode 100644 apps/web/svelte.config.js create mode 100644 apps/web/tests/flows.test.ts create mode 100644 apps/web/tests/mockApi.ts create mode 100644 apps/web/tests/setup.ts create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/vite.config.ts create mode 100644 docs/ui-handoff.md create mode 100644 docs/ui-open-questions.md create mode 100644 packages/ui/package.json create mode 100644 packages/ui/src/Banner.svelte create mode 100644 packages/ui/src/Button.svelte create mode 100644 packages/ui/src/Details.svelte create mode 100644 packages/ui/src/Dialog.svelte create mode 100644 packages/ui/src/Icon.svelte create mode 100644 packages/ui/src/Progress.svelte create mode 100644 packages/ui/src/Segmented.svelte create mode 100644 packages/ui/src/Status.svelte create mode 100644 packages/ui/src/components.css create mode 100644 packages/ui/src/icons.ts create mode 100644 packages/ui/src/index.ts create mode 100644 packages/ui/src/status.ts create mode 100644 packages/ui/src/tokens.css create mode 100644 pnpm-lock.yaml diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..d0f2f85 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,17 @@ + + + + + + + + + Hosts — Ianitor Domi + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json index 591d4d1..77afe14 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,10 +1,29 @@ { "name": "web", - "version": "0.0.0", + "version": "0.1.0", "private": true, "license": "MPL-2.0", - "description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.", + "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.", + "type": "module", "scripts": { - "dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\"" + "dev": "vite", + "build": "vite build", + "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", + "test": "vitest run" + }, + "dependencies": { + "@ianitor/ui": "workspace:*" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.3", + "@testing-library/svelte": "^5.2.6", + "@testing-library/user-event": "^14.6.1", + "@tsconfig/svelte": "^5.0.4", + "jsdom": "^26.0.0", + "svelte": "^5.20.0", + "svelte-check": "^4.1.4", + "typescript": "^5.7.3", + "vite": "^6.1.0", + "vitest": "^3.0.5" } } diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte new file mode 100644 index 0000000..5507c99 --- /dev/null +++ b/apps/web/src/App.svelte @@ -0,0 +1,160 @@ + + + +{#if route.view === "signed-in"} + +{:else} + +
+ +
IANITOR DOMI
+
+ + {#if route.view === "hosts"} + + {:else if route.view === "history"} + {#key route.host}{/key} + {:else if route.view === "certs"} + + {:else if route.view === "renew"} + + {:else if route.view === "settings"} + + {/if} +
+ +
+ +
+ {#each app.toasts as t (t.id)}
{t.text}
{/each} +
+ + {#if app.signedOut} + {}}> +

Sign in again; this page keeps what you typed.

+ {#snippet footer()} + + + {/snippet} +
+ {/if} +{/if} + + diff --git a/apps/web/src/components/ApplyProgress.svelte b/apps/web/src/components/ApplyProgress.svelte new file mode 100644 index 0000000..0659c19 --- /dev/null +++ b/apps/web/src/components/ApplyProgress.svelte @@ -0,0 +1,80 @@ + + + +{#if apply.state === "queued"} +

+ + + Waiting for "{apply.queue?.waiting_for?.summary ?? "another change"}" to finish{apply.queue?.waiting_for?.seconds_left != null + ? `, about ${apply.queue.waiting_for.seconds_left} s` + : ""}. + {#if (apply.queue?.position ?? 1) > 1}{(apply.queue?.position ?? 1) - 1} other changes are ahead of this one.{/if} + +

+ {#if oncancel}
{/if} +{:else} +
    + {#each rows as r, i (i)} +
  1. + {#if r.s === "done"}{:else if r.s === "running"}{:else if r.s === "failed"}{:else}{/if} + {prefix[r.s]}{r.t[r.s as keyof typeof r.t]} +
  2. + {/each} + {#if st("watch") === "failed" && !final} +
  3. Now:Undoing the change
  4. + {/if} +
+ {#if apply.state === "watching"} + +

You can leave this screen. Other changes wait their turn; only one apply runs at a time.

+ {/if} +{/if} + + diff --git a/apps/web/src/components/ChangeBar.svelte b/apps/web/src/components/ChangeBar.svelte new file mode 100644 index 0000000..50b7352 --- /dev/null +++ b/apps/web/src/components/ChangeBar.svelte @@ -0,0 +1,140 @@ + + + +{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)} + {@const parts = firstSentence(last.reason?.message ?? "")} + (app.dismissed = [...app.dismissed, dismissKey])}> + {#snippet title()}{last.state === "failed" ? "not applied" : "reverted"} {parts[0]}{/snippet} + {#if parts[1]}Reason: {parts[1]}{/if} + {#snippet actions()} + {#if last.attempted_host}{/if} + {/snippet} + +{/if} + +{#if last || active} +
+ {#if active} +
+
{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"} + {runningHeading(active.summary, last && last.id === active.id ? last : null)}
+
{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}
+ {#if active.state === "watching" && watchLeft != null} + {@const total = o?.site?.watch_seconds ?? 60} + + {/if} +
+ {#if active.state === "queued"}{:else}{/if} + {:else if last} +
+ {#if last.state === "kept"} +
kept {last.summary}
+
{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}
+ {:else if undo?.target} +
Undo: {undo.target.summary}
+ {/if} + {#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}
{undo.effect}
{/if} + {#if moved}
{moved}
{/if} + {#if undoReason}
{undoReason}
{/if} + {#if !undo?.target}
Nothing to undo yet.
{/if} +
+ {#if pushFailed}{/if} + {#if undo?.target} + + {/if} + {/if} +
+{/if} + + diff --git a/apps/web/src/components/EnginePopover.svelte b/apps/web/src/components/EnginePopover.svelte new file mode 100644 index 0000000..cd7f368 --- /dev/null +++ b/apps/web/src/components/EnginePopover.svelte @@ -0,0 +1,107 @@ + + + + +

Engine

+ {#if e?.state === "stopped"} +

{name} is not answering. Visitors may not reach any host. Switching to {other} is the quickest way back.

+ {:else} +

+ {#if e?.since}Since {when(e.since, app.now)}. {/if} + {#if running === "pingora"} + {#if notReady}Caddy is not ready: its settings have not been built yet.{:else}Caddy is ready with the same routes: built {when(e?.fallback_ready?.built_at, app.now)}{e?.fallback_ready?.current ? "" : " (it is rebuilt from the current routes when you switch)"}.{/if} + {:else}Pingora is ready with the same routes.{/if} +

+ {/if} +
+

What happens

+
    +
  • {name} stops and {other} starts. New visits reach {other} in about 2 seconds.
  • +
  • Open connections close; videos and uploads in progress restart.
  • +
  • Hosts and certificates stay the same.
  • + {#if running === "pingora"} +
  • Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks} Hosts with share links: {activeLinks}.{/if}
  • +
  • Changes wait while Caddy serves; switch back to make them.
  • + {:else} +
  • Share links work again, and changes can be made again.
  • + {/if} +
  • This page may lose contact for a few seconds.
  • +
+
+ {#if switching} +

Switching to {other}

+ + {/if} + {#if problem}{#snippet title()}{problem}{/snippet}{/if} + {#if disabledReason}

{disabledReason}

{/if} + {#snippet footer()} + + + {/snippet} +
+ + diff --git a/apps/web/src/components/HostList.svelte b/apps/web/src/components/HostList.svelte new file mode 100644 index 0000000..a51cd60 --- /dev/null +++ b/apps/web/src/components/HostList.svelte @@ -0,0 +1,142 @@ + + + +
+
+ Status + Host + Sends traffic to + More +
+ {#each sorted as h (h.hostname)} + {@const [k, w] = kind(h)} + {@const s = sub(h)} +
+ + + + {h.hostname} + {#each chips(h) as c (c)}{c}{/each} + {w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""} + + + {h.upstreams[0] ?? ""}{#if h.upstreams.length > 1} +{h.upstreams.length - 1} more{/if} + {running.includes(h.hostname) ? "Changing now · " : ""}{s.text} + {#if h.certificate.state === "pending"}Waiting for Let's Encrypt to issue the certificate.{/if} + {#if h.certificate.state === "failed"} + Let's Encrypt could not confirm {h.hostname}. The name must point to this server, and port 80 must be open from the internet. + + {/if} + + + onshare(h.hostname) }, + { label: "Edit host", icon: "pencil", reason: blocked, run: () => onedit(h.hostname) }, + { label: "Show in history", icon: "history", run: () => onhistory(h.hostname) }, + { label: "Remove host", icon: "trash", danger: true, divider: true, reason: blocked, run: () => onremove(h.hostname) }, + ]} /> + +
+ {/each} +
+ + diff --git a/apps/web/src/components/HostMenu.svelte b/apps/web/src/components/HostMenu.svelte new file mode 100644 index 0000000..95be1ee --- /dev/null +++ b/apps/web/src/components/HostMenu.svelte @@ -0,0 +1,86 @@ + + + + + + + +
+ + {#if open} + + {/if} +
diff --git a/apps/web/src/components/HostPanel.svelte b/apps/web/src/components/HostPanel.svelte new file mode 100644 index 0000000..23001bc --- /dev/null +++ b/apps/web/src/components/HostPanel.svelte @@ -0,0 +1,499 @@ + + + + + {#if loading} +

Loading…

+ {:else if notFound} + {#snippet title()}{notFound}{/snippet} + {#snippet actions()}{/snippet} + + {:else if phase === "progress" && apply} +
+ {#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if} +
+ + {#if apply.state === "kept"} + + {#snippet title()}kept {apply?.hosts[0] ?? name} {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet} + {apply.reason?.message ?? ""}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if} + + {:else if apply.state === "reverted" || apply.state === "failed"} + {@const parts = firstSentence(apply.reason?.message ?? "")} + + {#snippet title()}{apply?.state === "failed" ? "not applied" : "reverted"} {parts[0]}{/snippet} + {#if parts[1]}Reason: {parts[1]}{/if} + {#snippet actions()} + {#if reasonOffer} + + {/if} + {/snippet} + + {#if apply.reason?.detail}
{/if} +

Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.

+ {:else if apply.state === "needs_attention"} + {#snippet title()}Ianitor could not undo a failed change.{/snippet}{apply.reason?.message} + {/if} + {:else} +
+ {#if summary}{/if} + {#if conflict} + + {#snippet title()}{conflict?.message}{/snippet} + {#snippet actions()}{#if hostname}{/if}{/snippet} + + {/if} + {#if topError} + {#snippet title()}{sentence(topError)}{/snippet} + {#if topError.body.detail}
{/if} + {/if} + +
+ + blur("hostname")} /> + {#if errAt("hostname") && touched["hostname"]} +

{errAt("hostname").message} + {#if errAt("hostname").params?.suggestion} + + {/if} +

+ {/if} + {#if hostname}

To use another address, add a new host and remove this one.

{/if} +
+ + {#each host.upstreams as _, i (i)} + {@const f = `upstreams[${i}]`} + {@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)} +
+ {#if i === 0}{/if} +
+ blur(f)} /> + {#if i > 0}{/if} +
+ {#if err && (touched[f] || touched["upstreams"])} +

{err.message} + {#if err.params?.suggestion}{/if} +

+ {/if} + {#if i === 0 && host.upstreams.length === 1}

Add another address later for a second server.

{/if} +
+ {/each} +
+ + +

Domi for home devices only; Let's Encrypt for a public site.

+ + + {#if !signinOk}

Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository.

{/if} + {#if errAt("auth")}

{errAt("auth").message}

{/if} + +
+ +
+ {#if more} +
+
+ Health check + +

Ianitor asks this address regularly and shows the result on the main screen.

+
+ {#if host.hc} +
+ + blur("health_check.path")} /> + {#if errAt("health_check.path")}

{errAt("health_check.path").message}

{/if} +

Use an address that answers without signing in, like /health.

+
+
+ +
blur("health_check.interval_secs")} /> seconds
+ {#if errAt("health_check.interval_secs")}

{errAt("health_check.interval_secs").message}

{/if} +
+ {/if} +
+ Websockets + +

Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.

+
+
+ Share links + +

Lets you make links that open this host without signing in, until they expire.

+ {#if shareWarning}

Anyone can already open {name}, so a share link changes nothing.

{/if} +
+
+ Device certificates + +

Phones, computers and apps need a certificate from Certificates before they can open it.

+
+ +

On keeps a log on this server, with visitor addresses shortened.

+ {#each [{ list: "request_headers", rules: host.req, title: "Header rules sent to your service", secrets: true }, { list: "response_headers", rules: host.resp, title: "Header rules sent back to visitors", secrets: false }] as group (group.list)} +
+ {group.title} + {#each group.rules as r, i (i)} + {@const p = `${group.list}[${i}]`} +
+ + + blur(p + ".name")} /> + {#if r.action === "set"} + {#if group.secrets} + + {/if} + {#if r.kind === "secret" && group.secrets} + + {:else} + blur(p + ".value")} /> + {/if} + {/if} + {#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}

{e.message}

{/each} + +
+ {/each} +
+ {#if group.secrets && (site?.secrets.length ?? 0) === 0}

No secrets are listed in ianitor.toml.

{/if} +
+ {/each} +
+ {/if} + + {/if} + + {#snippet footer()} + {#if phase === "form" && !loading && !notFound} + {#if underFooter}

{underFooter}

{/if} + {#if blocked}

{blocked}

{/if} + + + {:else if phase === "progress" && apply && FINAL.includes(apply.state)} + + {/if} + {/snippet} +
+ + diff --git a/apps/web/src/components/IntermediateBanner.svelte b/apps/web/src/components/IntermediateBanner.svelte new file mode 100644 index 0000000..5a5ea9b --- /dev/null +++ b/apps/web/src/components/IntermediateBanner.svelte @@ -0,0 +1,69 @@ + + + +{#if app.renewedUntil} + (app.renewedUntil = null)}> + {#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet} + +{:else if i?.renewal} + {@const r = i.renewal} + + {#snippet title()} + Sign the renewal on the offline computer. Check that it shows the same code: + {r.match_code} + {/snippet} + The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if} + {#snippet actions()} + + + {/snippet} + +{:else if i?.banner} + + {#snippet title()}{i.banner?.message}{/snippet} + {i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs; check the match code on both screens."} + {#if problem} {problem}{/if} + {#snippet actions()}{/snippet} + +{/if} + + diff --git a/apps/web/src/components/ShareDialog.svelte b/apps/web/src/components/ShareDialog.svelte new file mode 100644 index 0000000..5a6a6df --- /dev/null +++ b/apps/web/src/components/ShareDialog.svelte @@ -0,0 +1,163 @@ + + + + + {#if !on} + {#if turning} + + {#if turning.state === "reverted" || turning.state === "failed"} + {#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet} + {/if} + {:else} +

Share links are off for {hostname}.

+

Turning them on is a change to the host, checked like any other.

+ {#if problem}{/if} +
+ {/if} + {:else} +

Anyone with this link can open the site without signing in, until it expires.

+ {#if underCaddy} + {#snippet title()}Caddy is serving right now, so share links do not work: visitors with this link get the normal sign-in. The link works after switching back to Pingora, until it expires.{/snippet} + {/if} + {#if link?.warning}

{link.warning.message}

{/if} + {#if problem}{#snippet title()}{problem}{/snippet}{/if} + {#if link} + (e.currentTarget as HTMLInputElement).select()} /> + {:else if minting} +

Making the link…

+ {/if} + {#if copied} +

Copied

+

Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.

+ {:else} + + {/if} + {#if refused}{/if} + {#if copiedBefore && !copied}

The link you copied before is stopped. Copy this one.

{/if} + + mint()} + options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} /> +
+ + mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }} + aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} /> + {#if fieldErr?.field === "path_prefix"}

{fieldErr.message}

{/if} +

/ shares the whole site. Try /share/summer-2026 for one album.

+
+ {#if usingPassword} +

This link asks for the password.

+
+ {:else if showPassword} +
+ + + {#if fieldErr?.field === "password"}

{fieldErr.message}

{/if} +

At least 8 characters. Send it to them separately.

+
+
+ {:else} +
+ {/if} + {/if} +
diff --git a/apps/web/src/components/TopBanners.svelte b/apps/web/src/components/TopBanners.svelte new file mode 100644 index 0000000..c625b6c --- /dev/null +++ b/apps/web/src/components/TopBanners.svelte @@ -0,0 +1,73 @@ + + + +{#if o?.paused} + + {#snippet title()}{restorable ? "needs attention" : "paused"} {o.paused?.message}{/snippet} + {#if restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {when(o.undo.target.kept_at, app.now)}. It is checked like any change.{/if} + {#if problem} {problem}{/if} + {#snippet actions()} + {#if restorable}{/if} + {/snippet} + +{/if} + +{#if app.lostContact} + + {#snippet title()}{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}{/snippet} + Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if} + {#snippet actions()}{/snippet} + +{/if} + +{#if o?.health_error} + {#snippet title()}{o.health_error?.message}{/snippet} +{/if} + +{#if app.switchResult} + {@const r = app.switchResult} + (app.switchResult = null)}> + {#snippet title()}{r.title}{/snippet} + {r.text} + {#if r.detail}
{/if} + +{/if} + +{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)} + {#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet} +{/if} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts new file mode 100644 index 0000000..5eedc8f --- /dev/null +++ b/apps/web/src/lib/api.ts @@ -0,0 +1,184 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF), +// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server +// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides +// nothing about the data. + +import type { ErrorBody, ErrorEnvelope } from "./types"; + +export const BASE = "/api/v1"; + +/** A refusal from control, with its envelope. */ +export class ApiError extends Error { + constructor( + public status: number, + public body: ErrorBody, + public errors: ErrorBody[], + public requestId: string, + ) { + super(body.message); + } + get code(): string { + return this.body.code; + } +} + +/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */ +export class SignedOut extends Error {} + +/** No answer (network, or a proxy error without an envelope). */ +export class LostContact extends Error {} + +type Listener = () => void; + +export interface ClientEvents { + onSignedOut?: Listener; + onContact?: (ok: boolean) => void; + onServerTime?: (offsetMs: number) => void; +} + +let events: ClientEvents = {}; +export function setClientEvents(e: ClientEvents): void { + events = e; +} + +/** A key for one click; reused by every retry of that click (§11.3). */ +export function newKey(): string { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID(); + return Math.random().toString(36).slice(2) + Date.now().toString(36); +} + +export interface CallOptions { + idem?: string; + etag?: string; + /** Do not count a failure as lost contact (engine switch, §9.2). */ + quiet?: boolean; + keepalive?: boolean; +} + +export interface Answer { + status: number; + data: T | null; + etag: string | null; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function envelope(v: unknown): v is ErrorEnvelope { + return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object"; +} + +export async function call( + method: string, + path: string, + body?: unknown, + opts: CallOptions = {}, +): Promise> { + let rateRetried = false; + for (let attempt = 0; attempt < 12; attempt++) { + const headers: Record = { "X-Ianitor-UI": "1", Accept: "application/json" }; + if (body !== undefined) headers["Content-Type"] = "application/json"; + if (opts.idem) headers["Idempotency-Key"] = opts.idem; + if (opts.etag) headers["If-None-Match"] = opts.etag; + let res: Response; + try { + res = await fetch(BASE + path, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: "manual", + credentials: "same-origin", + keepalive: opts.keepalive, + }); + } catch { + if (!opts.quiet) events.onContact?.(false); + throw new LostContact("no answer"); + } + if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) { + events.onSignedOut?.(); + throw new SignedOut("signed out"); + } + if (res.status === 304) { + events.onContact?.(true); + return { status: 304, data: null, etag: opts.etag ?? null }; + } + let json: unknown = null; + const text = await res.text(); + try { + json = text ? JSON.parse(text) : null; + } catch { + json = null; + } + if (json && typeof json === "object" && "server_time" in json) { + const t = Date.parse(String((json as { server_time: string }).server_time)); + if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now()); + } + if (!envelope(json)) { + if (res.status === 401) { + events.onSignedOut?.(); + throw new SignedOut("signed out"); + } + if (res.status >= 502 && res.status <= 504) { + if (!opts.quiet) events.onContact?.(false); + throw new LostContact(`proxy answered ${res.status}`); + } + events.onContact?.(true); + return { status: res.status, data: json as T, etag: res.headers.get("ETag") }; + } + events.onContact?.(true); + const env = json; + if (env.error.code === "request.in_progress") { + await sleep(1000); + continue; + } + if (env.error.code === "rate.limited" && !rateRetried) { + rateRetried = true; + await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000); + continue; + } + if (res.status === 401 && env.error.code.startsWith("token.")) { + // The UI holds no token: a token refusal means the sign-in did not reach control. + events.onSignedOut?.(); + throw new SignedOut(env.error.message); + } + throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? ""); + } + throw new ApiError( + 409, + { + code: "request.in_progress", + message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.", + field: null, + params: {}, + retry_after_s: 1, + detail: null, + }, + [], + "", + ); +} + +export const get = (path: string, opts?: CallOptions) => call("GET", path, undefined, opts).then((a) => a.data as T); +export const post = (path: string, body: unknown = {}, opts?: CallOptions) => + call("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const put = (path: string, body: unknown, opts?: CallOptions) => + call("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const patch = (path: string, body: unknown, opts?: CallOptions) => + call("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const del = (path: string, opts?: CallOptions) => call("DELETE", path, undefined, opts).then(() => undefined); + +/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */ +export function sentence(e: unknown): string { + if (e instanceof ApiError) { + if (e.code.startsWith("request.") && e.code !== "request.in_progress") { + return "Ianitor refused this request from the page. Reload the page and try again."; + } + return e.body.message; + } + if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back."; + if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed."; + return "Something went wrong."; +} diff --git a/apps/web/src/lib/app.svelte.ts b/apps/web/src/lib/app.svelte.ts new file mode 100644 index 0000000..ee5c6bd --- /dev/null +++ b/apps/web/src/lib/app.svelte.ts @@ -0,0 +1,150 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, +// the server clock offset and toasts. No business logic: everything shown comes from control. + +import { call, setClientEvents } from "./api"; +import type { Overview } from "./types"; + +export interface Toast { + id: number; + text: string; +} + +export const app = $state({ + overview: null as Overview | null, + etag: null as string | null, + loadError: false, + lostContact: false, + lostSince: 0, + lastUpdated: 0, + signedOut: false, + offset: 0, + now: Date.now(), + path: typeof location === "undefined" ? "/" : location.pathname + location.search, + toasts: [] as Toast[], + /** Dismissed banner keys (reverted outcome, renewed, switched). */ + dismissed: [] as string[], + /** The outcome of the last engine switch, until dismissed (handoff §9.2). */ + switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, + /** A renewal just installed (handoff §13.5). */ + renewedUntil: null as null | string, + /** Panels the main screen opens (add/edit host, share, engine). */ + panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" }, +}); + +let failures = 0; +let firstFailure = 0; + +setClientEvents({ + onSignedOut: () => { + app.signedOut = true; + }, + onContact: (ok) => { + if (ok) { + failures = 0; + app.lostContact = false; + return; + } + if (failures === 0) firstFailure = Date.now(); + failures++; + // Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1). + if (Date.now() - firstFailure >= 10_000) { + if (!app.lostContact) app.lostSince = Date.now(); + app.lostContact = true; + } + }, + onServerTime: (o) => { + app.offset = o; + }, +}); + +/** Server time now, in ms (all countdowns use it, §7.2). */ +export function serverNow(): number { + return app.now + app.offset; +} + +/** Seconds left until an ISO time, on the server's clock. */ +export function secondsLeft(iso: string | null | undefined): number { + if (!iso) return 0; + return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000)); +} + +export async function refresh(): Promise { + if (app.signedOut) return; + try { + const a = await call("GET", "/overview", undefined, { etag: app.etag ?? undefined }); + if (a.status === 200 && a.data) { + app.overview = a.data; + app.etag = a.etag; + } + app.loadError = false; + app.lastUpdated = Date.now(); + } catch { + if (!app.overview) app.loadError = true; + } +} + +let timer: ReturnType | undefined; +let hiddenSince = 0; + +/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */ +export function startPolling(): () => void { + let stopped = false; + const tick = async () => { + if (stopped) return; + const hidden = typeof document !== "undefined" && document.visibilityState === "hidden"; + if (hidden && !hiddenSince) hiddenSince = Date.now(); + if (!hidden) hiddenSince = 0; + if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh(); + const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000; + timer = setTimeout(tick, every); + }; + const vis = () => { + if (document.visibilityState === "visible" && hiddenSince) { + hiddenSince = 0; + clearTimeout(timer); + void tick(); + } + }; + document.addEventListener("visibilitychange", vis); + const clock = setInterval(() => (app.now = Date.now()), 1000); + void tick(); + return () => { + stopped = true; + clearTimeout(timer); + clearInterval(clock); + document.removeEventListener("visibilitychange", vis); + }; +} + +let toastId = 0; +export function toast(text: string): void { + const id = ++toastId; + app.toasts = [...app.toasts.slice(-2), { id, text }]; + setTimeout(() => { + app.toasts = app.toasts.filter((t) => t.id !== id); + }, 6000); +} + +export function navigate(path: string): void { + if (path === app.path) return; + history.pushState({}, "", path); + app.path = path; +} + +if (typeof window !== "undefined") { + window.addEventListener("popstate", () => { + app.path = location.pathname + location.search; + }); +} + +/** Is a change allowed now? (Paused, or no contact.) */ +export function changesBlocked(): string | null { + const o = app.overview; + if (app.lostContact) return "Ianitor's control service is not answering."; + if (o?.paused) return "Changes are paused."; + return null; +} diff --git a/apps/web/src/lib/applies.ts b/apps/web/src/lib/applies.ts new file mode 100644 index 0000000..59691a2 --- /dev/null +++ b/apps/web/src/lib/applies.ts @@ -0,0 +1,58 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it +// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it. + +import { get } from "./api"; +import { refresh } from "./app.svelte"; +import type { ApplyView } from "./types"; + +export const FINAL = ["kept", "reverted", "failed", "needs_attention"]; +const KEY = "ianitor.activeApply"; + +export function remember(id: string | null): void { + try { + if (id) sessionStorage.setItem(KEY, id); + else sessionStorage.removeItem(KEY); + } catch { + /* storage may be off; the bar still shows the running apply */ + } +} + +export function remembered(): string | null { + try { + return sessionStorage.getItem(KEY); + } catch { + return null; + } +} + +/** Poll until the apply ends. Returns a stop function. */ +export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void { + let stopped = false; + let timer: ReturnType | undefined; + remember(id); + const tick = async () => { + if (stopped) return; + try { + const a = await get(`/applies/${encodeURIComponent(id)}`); + if (stopped) return; + onupdate(a); + if (FINAL.includes(a.state)) { + remember(null); + void refresh(); + return; + } + } catch { + /* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */ + } + timer = setTimeout(tick, every); + }; + void tick(); + return () => { + stopped = true; + clearTimeout(timer); + }; +} diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts new file mode 100644 index 0000000..61b1c70 --- /dev/null +++ b/apps/web/src/lib/format.ts @@ -0,0 +1,99 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences. + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +const two = (n: number) => String(n).padStart(2, "0"); + +/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */ +export function when(iso: string | null | undefined, now = Date.now()): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + const n = new Date(now); + const hm = `${two(d.getHours())}:${two(d.getMinutes())}`; + const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); + if (sameDay(d, n)) return `Today ${hm}`; + const y = new Date(n); + y.setDate(n.getDate() - 1); + if (sameDay(d, y)) return `Yesterday ${hm}`; + if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; + return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`; +} + +/** "14 November 2026 at 14:20". */ +export function longDate(iso: string | null | undefined, withTime = true): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`; + return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s; +} + +/** "2 Mar 2027". */ +export function shortDate(iso: string | null | undefined): string { + if (!iso) return ""; + const d = new Date(iso); + return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; +} + +/** "8 s", "6 minutes", "2 hours", "3 days". */ +export function duration(secs: number): string { + if (secs < 60) return `${Math.max(0, Math.round(secs))} s`; + const m = Math.round(secs / 60); + if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`; + const h = Math.round(secs / 3600); + if (h < 48) return h === 1 ? "1 hour" : `${h} hours`; + const days = Math.round(secs / 86400); + return `${days} days`; +} + +export function ago(iso: string | null | undefined, now: number): string { + if (!iso) return ""; + return duration((now - Date.parse(iso)) / 1000) + " ago"; +} + +/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */ +export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string { + const parts = [`${c.healthy} healthy`]; + if (c.degraded) parts.push(`${c.degraded} degraded`); + if (c.down) parts.push(`${c.down} down`); + if (c.unknown) parts.push(`${c.unknown} not checked`); + return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`; +} + +/** Split a server message on its first sentence (handoff §7.5). */ +export function firstSentence(m: string): [string, string] { + const i = m.indexOf(". "); + return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)]; +} + +/** Field labels in sentences (handoff §6.5). */ +export const FIELD_LABEL: Record = { + hostname: "address", + upstreams: "sends traffic to", + tls: "certificate", + auth: "who can open it", + "health_check.path": "health check address", + "health_check.interval_secs": "checks every", + share_links: "share links", + device_certs: "device certificates", + access_log: "visit log", + websockets: "websockets", + headers: "header rules", +}; + +export function fieldValue(field: string, v: string): string { + if (v === "") return "none"; + if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt"; + if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone"; + if (field === "access_log") return v === "truncated" ? "on" : "off"; + if (v === "true") return "on"; + if (v === "false") return "off"; + if (field === "health_check.interval_secs") return `${v} s`; + return v; +} diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts new file mode 100644 index 0000000..407bd31 --- /dev/null +++ b/apps/web/src/lib/types.ts @@ -0,0 +1,247 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json). +// Only the fields the UI uses are typed. + +export interface ErrorBody { + code: string; + message: string; + field: string | null; + params: Record; + retry_after_s: number | null; + detail: string | null; +} + +export interface ErrorEnvelope { + error: ErrorBody; + errors: ErrorBody[]; + request_id: string; +} + +export interface Blocked { + code: string; + message: string; +} + +export interface Reason { + code: string; + message: string; + hostname?: string | null; + upstream?: string | null; + field?: string | null; + detail?: string | null; + params?: Record; +} + +export interface Step { + key: "validate" | "compile" | "write" | "reload" | "watch" | "push"; + state: "pending" | "running" | "done" | "failed" | "skipped"; +} + +export interface ApplyView { + id: string; + change_id: string; + kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links"; + summary: string; + hosts: string[]; + state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention"; + created_at: string; + finished_at: string | null; + steps: Step[]; + queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null; + watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null; + reason: Reason | null; + errors: ErrorBody[]; + commit_short: string | null; + push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null; + attempted_host?: HostSpec | null; +} + +export interface HeaderRule { + action: "set" | "remove"; + name: string; + value?: string; + secret?: string; +} + +export interface HostSpec { + hostname: string; + upstreams: string[]; + tls: "domi" | "letsencrypt"; + auth: "none" | "forward-auth"; + websockets: boolean; + share_links: boolean; + device_certs?: boolean; + access_log: "off" | "truncated"; + health_check?: { path: string; interval_secs: number } | null; + request_headers?: HeaderRule[]; + response_headers?: HeaderRule[]; +} + +export interface HealthView { + state: "healthy" | "degraded" | "down" | "unknown" | "pending"; + last_check_at: string | null; + latency_ms: number | null; + since: string | null; + failure: { kind: string; upstream: string | null; count: number; of: number } | null; + upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[]; +} + +export interface HostRow { + hostname: string; + upstreams: string[]; + tls: string; + auth: string; + websockets: boolean; + share_links: boolean; + device_certs: boolean; + added_at: string | null; + health: HealthView; + certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null }; +} + +export interface PkiRequest { + request_id: string; + kind: "device" | "intermediate"; + state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed"; + match_code: string; + created_at: string; + expires_at: string; + approved_at: string | null; + device_id: string | null; + name: string | null; + csr_pem: string | null; + not_after: string | null; + message_code: string; + message: string; + approve_command: string | null; + problem: string | null; +} + +export interface IntermediateView { + state: "ok" | "due" | "urgent" | "expired" | "missing"; + subject: string | null; + not_after: string | null; + days_left: number | null; + renewal: PkiRequest | null; + banner: Blocked | null; +} + +export interface EngineView { + running: "pingora" | "caddy"; + state: "running" | "switching" | "stopped"; + since: string | null; + target: string | null; + switchable: boolean; + fallback_ready: { built_at: string | null; current: boolean } | null; + last_error: Reason | null; + notes: Blocked[]; +} + +export interface UndoView { + available: boolean; + target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null; + effect: string | null; + blocked: Blocked | null; +} + +export interface Overview { + counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }; + hosts: HostRow[]; + engine: EngineView; + last_apply: ApplyView | null; + undo: UndoView; + active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null; + repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null; + intermediate: IntermediateView | null; + site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean } | null; + paused: Blocked | null; + paused_reason: string | null; + health_error: Blocked | null; + rev: string | null; + viewer?: { name: string; via: string } | null; + server_time: string; +} + +export interface HistoryEntry { + change_id: string; + summary: string; + kind: string; + state: string; + at: string; + commit_short: string | null; + hosts: string[]; + reason_short: string | null; +} + +export interface RestorePreview { + restorable: boolean; + same_as_current: boolean; + changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[]; + blocked: Blocked | null; +} + +export interface ShareLink { + id: string; + hostname: string; + path_prefix: string; + created_at: string; + expires_at: string; + has_password: boolean; + state: "active" | "expired" | "stopped"; +} + +export interface MintedLink { + id: string; + url: string; + expires_at: string; + path_prefix: string; + has_password: boolean; + warning: Blocked | null; +} + +export interface TokenRow { + id: string; + name: string; + created_at: string; + last_used_at: string | null; + expires_at: string | null; + revoked_at?: string | null; +} + +export interface CreatedToken { + id: string; + name: string; + token: string; + expires_at: string | null; +} + +export interface DeviceRow { + id: string; + name: string; + kind: "phone" | "computer" | "app"; + created_at: string; + not_after: string; + state: "valid" | "revoked" | "expired"; + revoked_at: string | null; +} + +export interface CertsView { + intermediate: IntermediateView | null; + root: { offline: boolean; subject: string; not_after: string; sha256: string }; + devices: DeviceRow[]; + device_lifetime_days: number; + server_lifetime_days: number; + approval: string; + requests: PkiRequest[]; +} + +export interface Bundle { + download_url: string; + one_time_password: string; + expires_at: string; + filename: string; + qr_svg: string | null; +} diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts new file mode 100644 index 0000000..fcd4afc --- /dev/null +++ b/apps/web/src/main.ts @@ -0,0 +1,11 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import "@ianitor/ui/tokens.css"; +import "@ianitor/ui/components.css"; +import { mount } from "svelte"; +import App from "./App.svelte"; + +const target = document.getElementById("app"); +if (target) mount(App, { target }); diff --git a/apps/web/src/views/Certificates.svelte b/apps/web/src/views/Certificates.svelte new file mode 100644 index 0000000..f0b7a4e --- /dev/null +++ b/apps/web/src/views/Certificates.svelte @@ -0,0 +1,245 @@ + + + +
+

Certificates

+ +
+ + +{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + +{#if certs} +
+

Domi intermediate

+

{#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}

+

Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).

+
+ +

Devices

+ {#if certs.devices.length === 0} +

No device certificates yet

A device certificate lets a phone, computer or Domi app into hosts that ask for one.

+ {:else} +
    + {#each certs.devices as d (d.id)} +
  • + + {d.name} + until {shortDate(d.not_after)} + {#if d.state === "revoked"}{:else if d.state === "expired"}{/if} + {#if confirmRevoke === d.id} + Revoke the certificate of "{d.name}"? It can no longer get in. + + + {:else if d.state === "valid"} + install(d, d.kind === "computer" ? "p12" : "qr") }, + { label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) }, + ]} /> + {/if} +
  • + {/each} +
+ {/if} +{/if} + +{#if newDevice} + + {#if !request} +
+
+ + + {#if nameErr}

{nameErr}

{/if} +

Shown in this list and inside the certificate.

+
+ +

Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.

+ + {:else if request.state === "waiting"} +

Waiting for approval

+

Approve it on the server, and only if it shows the same code:

+

{request.match_code}

+ {#if request.approve_command}

Run on the server:

{request.approve_command}
{/if} +

The request stays open for {Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")}. Nothing is issued until it is approved.

+
+ Waiting for approval. Code {request.match_code}. + {:else if issuedDevice} + {#snippet title()}{issuedDevice.name} has a certificate. Approved at {when(request?.approved_at, app.now)}.{/snippet} +
+ + +
+

The file is protected with a one-time password shown next to the QR code.

+ {:else} + {#snippet title()}{request?.message}{/snippet} + {#snippet actions()}{/snippet} + {/if} + {#snippet footer()} + {#if !request} + + + {:else if request.state !== "waiting"} + + {/if} + {/snippet} +
+{/if} + +{#if bundle} + { bundle = null; void refresh(); }}> +
+ {#if bundle.b.qr_svg} + + {/if} +
+

Password for the file

+

{bundle.b.one_time_password}

+

Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).

+
+
+

+ {#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks. + {:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password. + {:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if} +

+
+{/if} + + diff --git a/apps/web/src/views/History.svelte b/apps/web/src/views/History.svelte new file mode 100644 index 0000000..70d9be3 --- /dev/null +++ b/apps/web/src/views/History.svelte @@ -0,0 +1,179 @@ + + + +

{host ? `History of ${host}` : "History"}

+{#if host}
{/if} +{#if problem}{#snippet title()}{problem}{/snippet}{/if} + +
+
+ {#if loaded && entries.length === 0} +

No changes yet

Every change you apply is listed here, newest first.

+ {/if} +
    + {#each entries as e, i (e.change_id)} + {@const [k, w] = stateOf(e)} +
  • + +
  • + {/each} +
+ {#if next}{/if} +
+ + {#if chosen && preview} +
+

Version of {when(entry?.at, app.now)}

+ {#if preview.blocked?.code === "restore.not_kept"} +

This change did not stay

+ {#if attempt?.reason}

{attempt.reason.message}

{/if} +

This change was undone at the time, so there is nothing to go back to.

+ {#if attempt?.attempted_host}
{/if} + {:else if preview.blocked?.code === "restore.same"} +

Go back to this version?

+

This version is the same as the current one. Nothing to restore.

+
+ {:else} +

Go back to this version?

+

{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}

+
    + {#each preview.changes as c (c.hostname)} + {#if c.effect === "added"}
  • {c.hostname} is added back
  • + {:else if c.effect === "removed"}
  • {c.hostname} is removed
  • + {:else} + {#each c.fields as f (f.field)} +
  • {c.hostname}: {#if f.field === "headers"}header rules change{:else}{FIELD_LABEL[f.field] ?? f.field} changes from {fieldValue(f.field, f.from)} to {fieldValue(f.field, f.to)}{/if}
  • + {/each} + {/if} + {/each} +
+

Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.

+ {#if blocked}

{blocked}

{/if} +
+ + +
+ {/if} +
+ {/if} +
+ +{#if resume} + { resume = null; void load(); }} /> +{/if} +{#if editFrom} + { editFrom = null; void load(); }} /> +{/if} +{longDate(entry?.at)} + + diff --git a/apps/web/src/views/Hosts.svelte b/apps/web/src/views/Hosts.svelte new file mode 100644 index 0000000..36d292b --- /dev/null +++ b/apps/web/src/views/Hosts.svelte @@ -0,0 +1,141 @@ + + + +
+
+

Hosts

+ {#if o}

{countsSentence(o.counts)}

{/if} +
+
+ {#if o} + + {/if} + + {#if blocked}{blocked}{/if} +
+
+ + +{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + + (app.panel = { kind: "host", resume: id })} onedit={editAgain} /> + +{#if !o && !app.loadError} +
Loading hosts… + {#each [0, 1, 2] as i (i)}
{/each} +
+{:else if app.loadError && !o} + {#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet} + {#snippet actions()}{/snippet} +{:else if o && o.hosts.length === 0} +

No hosts yet

Add the first one: the name people type, and where Ianitor should send them.

+{:else if o} + navigate(`/hosts/${encodeURIComponent(h)}/edit`)} + onremove={remove} + onshare={(h) => (app.panel = { kind: "share", hostname: h })} + onhistory={(h) => navigate(`/history?host=${encodeURIComponent(h)}`)} + onretry={retry} /> +{/if} + +{#if o?.repo} +
+ +{/if} + +{#if panelOpen} + {#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")} + + {/key} +{/if} +{#if app.panel?.kind === "share"} + { app.panel = null; void refresh(); }} /> +{/if} +{#if app.panel?.kind === "engine"} + (app.panel = null)} /> +{/if} + + diff --git a/apps/web/src/views/RenewByHand.svelte b/apps/web/src/views/RenewByHand.svelte new file mode 100644 index 0000000..6278c16 --- /dev/null +++ b/apps/web/src/views/RenewByHand.svelte @@ -0,0 +1,110 @@ + + + +

Sign the intermediate by hand

+

Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.

+ +{#if !r} + {#snippet title()}There is no open renewal request.{/snippet} + {#snippet actions()}{/snippet} +{:else} +
+

Step 1

+

Download the request

+

This file asks the Domi root to sign a new intermediate certificate. It holds no secret.

+

Check that the offline computer shows the same code: {r.match_code}

+
+
+
+

Step 2

+

Sign it on the offline computer

+

Copy the file to the offline computer that holds the Domi root, then run:

+
ianitor-control ca sign --root <root folder> --csr domi-intermediate-{day}.csr --out domi-intermediate-{day}.crt
+

It asks for the root's passphrase and shows the code; sign only if it is the code above.

+
+
+

Step 3

+

Upload the signed certificate

+ {#if paste} +
+ + +
+ {:else} +
+ + +
+
+ {/if} + {#if err}{/if} +
+
+{/if} + + diff --git a/apps/web/src/views/Settings.svelte b/apps/web/src/views/Settings.svelte new file mode 100644 index 0000000..bda12ba --- /dev/null +++ b/apps/web/src/views/Settings.svelte @@ -0,0 +1,279 @@ + + + +

Settings

+
+ {#each TABS as t, i (t.id)} + + {/each} +
+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + +
+ {#if tab === "general"} +

Routes repository

+

{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + when(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}

+

Health watch after apply

+

{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds

+

Signed in

+

{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}

+ {:else if tab === "api"} +
+

API tokens

+ + +
+

The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.

+ {#if tokens.length === 0} +

No API tokens

Scripts and other Domi apps use a token to talk to Ianitor.

+ {:else} +
    + {#each tokens as t (t.id)} +
  • +
    + {t.name} + + {#if revoked[t.id]}Revoked {when(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${when(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if} + +
    + {#if !revoked[t.id] && !t.revoked_at} + {#if confirmRevoke === t.id} + Revoke "{t.name}"? Anything using it stops working now. + + + {:else} + + {/if} + {/if} +
  • + {/each} +
+ {/if} + {:else if tab === "share-links"} +
+

Share links

+ {#if active.length}{/if} +
+ {#if app.overview?.engine.running === "caddy"} + {#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet} + {/if} + {#if confirmStopAll} +

Stop all {active.length} active links? Every link made so far stops working. New ones work as usual. +

+ {/if} + {#if links.length === 0} +

No share links

Make one from a host's menu (⋯), Share link.

+ {:else} +
    + {#each active as l (l.id)} +
  • +
    {l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""} + Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}
    + +
  • + {/each} +
+ {#if ended.length} +
Ended ({ended.length}) +
    {#each ended as l (l.id)}
  • {l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}{l.state} {shortDate(l.expires_at)}
  • {/each}
+
+ {/if} + {/if} + {:else} +

Ianitor Domi 0.1.0

+

MPL-2.0

+

Built, tested and signed by Fabrica Domi

+

Source on Gitea

+ {/if} +
+ +{#if made} + closeToken()}> +

Copy it now and save it in Custos.

+

Ianitor cannot show it again; if it is lost, make a new one and revoke this one.

+ (e.currentTarget as HTMLInputElement).select()} /> +
+
+ + + {#if nameErr}

{nameErr}

{/if} +

Rename it now or later, so you know what uses it.

+
+ +
+ {#if tokenCopied}

Copied. Paste it into Custos now. Ianitor cannot show it again.

{/if} +

{made.expires_at ? `Expires on ${shortDate(made.expires_at)}.` : "Never expires."}

+ {#if askClose} +

Close without copying? The token cannot be shown again. +

+ {/if} + {#snippet footer()}{/snippet} +
+{/if} + + diff --git a/apps/web/src/views/SignedIn.svelte b/apps/web/src/views/SignedIn.svelte new file mode 100644 index 0000000..8c2c16d --- /dev/null +++ b/apps/web/src/views/SignedIn.svelte @@ -0,0 +1,33 @@ + + + +
+

IANITOR DOMI

+

You are signed in again.

+

You can close this tab and go back to Ianitor.

+
+ + diff --git a/apps/web/svelte.config.js b/apps/web/svelte.config.js new file mode 100644 index 0000000..b235e46 --- /dev/null +++ b/apps/web/svelte.config.js @@ -0,0 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; + +export default { preprocess: vitePreprocess() }; diff --git a/apps/web/tests/flows.test.ts b/apps/web/tests/flows.test.ts new file mode 100644 index 0000000..7950cba --- /dev/null +++ b/apps/web/tests/flows.test.ts @@ -0,0 +1,202 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real +// app against a stand-in for control's API. Typing, focus and waiting are not clicks. + +import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import App from "../src/App.svelte"; +import { app } from "../src/lib/app.svelte"; +import { installMock, type Mock } from "./mockApi"; + +let mock: Mock; +let clicks = 0; +let user: ReturnType; + +async function click(el: Element) { + clicks++; + await user.click(el); +} + +function start(path = "/") { + history.replaceState({}, "", path); + app.path = path; + app.panel = null; + app.overview = null; + app.etag = null; + app.signedOut = false; + app.switchResult = null; + app.renewedUntil = null; + app.dismissed = []; + mock = installMock(); + clicks = 0; + user = userEvent.setup(); + render(App); +} + +const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path)); +const T = { timeout: 5000 }; + +beforeEach(() => { + try { + sessionStorage.clear(); + } catch { + /* none */ + } +}); +afterEach(() => cleanup()); + +describe("ROADMAP §4 flows, clicks counted", () => { + it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => { + start(); + await click(await screen.findByRole("button", { name: "Add a host" })); + await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test"); + await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080"); + await click(screen.getByRole("button", { name: "Apply" })); + // Kept: the panel closes by itself and the new host is in the list. + await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T); + await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T); + await screen.findByRole("button", { name: "More for recipes.home.test" }, T); + expect(called("POST", "/hosts")).toBe(true); + const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record }; + // Every field is sent explicitly, with the design's defaults. + expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true }); + expect(clicks).toBe(2); + }); + + it("Undo last change = 1 click", async () => { + start(); + await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ })); + await waitFor(() => expect(called("POST", "/undo")).toBe(true)); + const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record; + expect(body.target_change_id).toBe("ch_1"); + expect(clicks).toBe(1); + }); + + it("Restore: History → pick → Restore = 3 clicks", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "History" })); + await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ })); + await screen.findByText(/sends traffic to changes from/); + await click(await screen.findByRole("button", { name: "Restore this version" })); + await waitFor(() => expect(called("POST", "/restore")).toBe(true)); + expect(clicks).toBe(3); + }); + + it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => { + start(); + await click(await screen.findByRole("button", { name: "More for wiki.home.test" })); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + const copy = await screen.findByRole("button", { name: "Copy link" }); + await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull()); + await click(copy); + await screen.findByText("Copied"); + const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record; + expect(mint.expires_in_s).toBe(604800); + expect(await navigator.clipboard.readText()).toContain("?share=ish1."); + expect(clicks).toBe(3); + }); + + it("Share link on a host with links off: 4 clicks (open question Q1 not decided)", async () => { + start(); + await click(await screen.findByRole("button", { name: "More for photos.home.test" })); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + await click(await screen.findByRole("button", { name: "Turn on share links" })); + const copy = await screen.findByRole("button", { name: "Copy link" }, T); + await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull()); + await click(copy); + await screen.findByText("Copied"); + expect(called("PATCH", "/hosts/photos.home.test")).toBe(true); + expect(clicks).toBe(4); + }); + + it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => { + start(); + await click(await screen.findByRole("button", { name: /^Engine: Pingora/ })); + await click(await screen.findByRole("button", { name: "Switch to Caddy" })); + await waitFor(() => expect(called("POST", "/engine")).toBe(true)); + const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record; + expect(body.target).toBe("caddy"); + await screen.findByText("Now serving with Caddy.", {}, T); + expect(clicks).toBe(2); + }); + + it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "Certificates" })); + await click(await screen.findByRole("button", { name: "Add a device certificate" })); + await user.type(await screen.findByLabelText("Device name"), "Mark's phone"); + await click(screen.getByRole("button", { name: "Issue" })); + await screen.findByLabelText("Match code 47 19 83"); + expect(clicks).toBe(3); + // Approved on the server (the stand-in approves on the first poll). + await click(await screen.findByRole("button", { name: "Show QR code" }, T)); + await screen.findByText("ABCD-EFGH-JKLM-NPQR"); + expect(clicks).toBe(4); + }); + + it("Renew intermediate: banner Renew = 1 click", async () => { + start(); + await click(await screen.findByRole("button", { name: "Renew" })); + await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true)); + await screen.findByLabelText("Match code 47 19 83"); + expect(clicks).toBe(1); + }); + + it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "Settings" })); + await click(await screen.findByRole("tab", { name: "API" })); + await click(await screen.findByRole("button", { name: "New token" })); + const box = (await screen.findByLabelText("New API token")) as HTMLInputElement; + expect(box.value).toBe("ian_tk1_secretvalue"); + expect(clicks).toBe(3); + await click(screen.getByRole("button", { name: "Copy token" })); + expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue"); + expect(clicks).toBe(4); + // The token is never stored by the page. + expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1"); + expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1"); + }); +}); + +describe("sign-in and contact", () => { + it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch; + app.etag = null; + await click(screen.getByRole("button", { name: "Add a host" })); + await user.type(await screen.findByLabelText("Hostname"), "x.home.test"); + await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080"); + await click(screen.getByRole("button", { name: "Apply" })); + await screen.findByRole("alertdialog", { name: "Your sign-in has ended" }); + // What was typed is still there. + expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test"); + }); + + it("every request carries the UI header and no token", async () => { + const seen: Headers[] = []; + start(); + const inner = globalThis.fetch; + globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => { + seen.push(new Headers(init?.headers)); + return inner(i, init); + }) as typeof fetch; + await click(await screen.findByRole("button", { name: /^Undo:/ })); + await waitFor(() => expect(seen.length).toBeGreaterThan(0)); + for (const h of seen) { + expect(h.get("X-Ianitor-UI")).toBe("1"); + expect(h.get("Authorization")).toBeNull(); + } + }); +}); diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts new file mode 100644 index 0000000..58967a4 --- /dev/null +++ b/apps/web/tests/mockApi.ts @@ -0,0 +1,174 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the +// smoke tests can walk every §4 flow and count its clicks. + +type Json = Record; + +export interface Mock { + calls: { method: string; path: string; body: unknown }[]; + state: { + engine: "pingora" | "caddy"; + switching: number; + intermediate: "ok" | "due"; + renewal: boolean; + requestPolls: number; + hostsAdded: string[]; + }; +} + +const now = () => new Date().toISOString(); +const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); + +function host(hostname: string, share: boolean) { + return { + hostname, + upstreams: ["http://10.0.0.2:3000"], + tls: "domi", + auth: "forward-auth", + websockets: true, + share_links: share, + device_certs: false, + added_at: null, + health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] }, + certificate: { state: "ok", not_after: later(86400 * 80), error_code: null }, + }; +} + +function apply(id: string, state: string, summary: string, hosts: string[]) { + return { + id, + change_id: id, + kind: "add", + summary, + hosts, + state, + created_at: now(), + finished_at: state === "kept" ? now() : null, + steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })), + queue: null, + watch: null, + reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null, + errors: [], + commit_short: "4f1c2ab", + push: null, + attempted_host: null, + }; +} + +export function installMock(): Mock { + const m: Mock = { + calls: [], + state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] }, + }; + + const overview = (): Json => ({ + counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 }, + hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))], + engine: { + running: m.state.engine, + state: m.state.switching > 0 ? "switching" : "running", + since: now(), + target: null, + switchable: true, + fallback_ready: { built_at: now(), current: true }, + last_error: null, + notes: [], + }, + last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]), + undo: { + available: true, + target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" }, + effect: "Removes recipes.home.test", + blocked: null, + }, + active_apply: null, + repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null }, + intermediate: + m.state.intermediate === "due" + ? { + state: "due", + subject: "Ianitor Domi Intermediate 2025-12", + not_after: later(86400 * 23), + days_left: 23, + renewal: m.state.renewal + ? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null } + : null, + banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." }, + } + : { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null }, + site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true }, + paused: null, + paused_reason: null, + health_error: null, + rev: "rev1", + viewer: { name: "mark", via: "authelia" }, + server_time: now(), + }); + + const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [ + ["GET", /^\/overview$/, () => [200, overview()]], + ["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]], + ["POST", /^\/hosts$/, (_, b) => { + const h = (b.host as Json).hostname as string; + m.state.hostsAdded.push(h); + return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }]; + }], + ["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]], + ["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]], + ["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]], + ["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]], + ["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]], + ["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]], + ["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]], + ["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]], + ["DELETE", /^\/share-links\/.+$/, () => [204, null]], + ["GET", /^\/engine$/, () => { + if (m.state.switching > 0) { + m.state.switching--; + if (m.state.switching === 0) m.state.engine = "caddy"; + } + return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }]; + }], + ["POST", /^\/engine$/, () => { + m.state.switching = 1; + return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }]; + }], + ["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]], + ["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]], + ["GET", /^\/pki-requests\/pr_dev$/, () => { + m.state.requestPolls++; + return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }]; + }], + ["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: "" }]], + ["POST", /^\/certs\/intermediate\/renewal$/, () => { + m.state.renewal = true; + return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }]; + }], + ["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]], + ["GET", /^\/tokens$/, () => [200, { items: [] }]], + ["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]], + ["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]], + ]; + + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url; + const path = url.replace(/^.*\/api\/v1/, ""); + const method = (init?.method ?? "GET").toUpperCase(); + const body = init?.body ? JSON.parse(String(init.body)) : {}; + m.calls.push({ method, path, body }); + for (const [mm, re, f] of routes) { + const match = path.match(re); + if (mm === method && match) { + const [status, data] = f(match, body); + const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data; + return new Response(status === 204 ? null : JSON.stringify(withTime), { status, headers: { "Content-Type": "application/json" } }); + } + } + return new Response(JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }), { status: 404, headers: { "Content-Type": "application/json" } }); + }) as typeof fetch; + + return m; +} diff --git a/apps/web/tests/setup.ts b/apps/web/tests/setup.ts new file mode 100644 index 0000000..4aadd80 --- /dev/null +++ b/apps/web/tests/setup.ts @@ -0,0 +1,39 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// jsdom lacks a few browser features the UI uses. + +if (typeof HTMLDialogElement !== "undefined") { + const p = HTMLDialogElement.prototype as HTMLDialogElement & Record; + if (!p.showModal) { + p.showModal = function (this: HTMLDialogElement) { + this.setAttribute("open", ""); + }; + p.show = function (this: HTMLDialogElement) { + this.setAttribute("open", ""); + }; + p.close = function (this: HTMLDialogElement) { + this.removeAttribute("open"); + }; + } +} + +const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) }; +Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true }); +(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard; + +if (!("BroadcastChannel" in globalThis)) { + (globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class { + onmessage: unknown = null; + postMessage() {} + close() {} + }; +} + +if (!("randomUUID" in crypto)) { + Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) }); +} + +window.open = () => null; +HTMLAnchorElement.prototype.click = function () {}; diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json new file mode 100644 index 0000000..b898d96 --- /dev/null +++ b/apps/web/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "skipLibCheck": true, + "types": ["vite/client"], + "lib": ["ES2022", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"] +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..8ce02c2 --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,38 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { defineConfig } from "vitest/config"; + +// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on +// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev +// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from +// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints. +const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878"; +const token = process.env.IANITOR_DEV_TOKEN; + +export default defineConfig({ + plugins: [svelte()], + server: { + host: "127.0.0.1", + port: 5173, + strictPort: true, + proxy: { + "/api": { + target: control, + changeOrigin: true, + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }, + }, + }, + preview: { host: "127.0.0.1" }, + build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 }, + resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined, + test: { + environment: "jsdom", + setupFiles: ["./tests/setup.ts"], + include: ["tests/**/*.test.ts"], + testTimeout: 20000, + }, +}); diff --git a/docs/ui-handoff.md b/docs/ui-handoff.md new file mode 100644 index 0000000..fa1e53d --- /dev/null +++ b/docs/ui-handoff.md @@ -0,0 +1,1443 @@ +# Ianitor Domi web UI: hand-off for the Svelte build + +What apps/web and packages/ui are built from. This file is enough by itself: you never need to open +the design artifact. Where the artifact and this file disagree, this file wins, and §14 lists every such place. + +Sources: the approved design (claude.ai artifact "Ianitor Domi — UI", 9 boards, murex palette on Domi), +docs/ui-api.md (the contract), docs/api.md (the built API), crates/control/src/messages.rs (the server's +sentences), ROADMAP §3 and §4, and Mark's decisions of 2026-11-07. + +Conventions in this file: +- "Quoted text" is exact UI copy. `{x}` is a value: from `params` on an error, or from a field. + **Hostnames, addresses (upstreams, paths) and match codes are bold** wherever they appear in a sentence. +- **[built]** means the API exists (Phase 2). **[proposed]** means the shape is mine and the API is not + built yet (engine switch, PKI, sign-in). Build the UI against the proposed shape behind a typed client, + so only the client changes if control lands differently. +- Click counts follow ROADMAP §4: typing is not a click; a click that only opens a menu is a click. + +--- + +## 0. Ground rules for the build + +- Svelte 5 runes, TypeScript strict. apps/web holds no business logic: every decision (validation, + health state, undo target, restore effects) comes from the API. The UI formats and arranges. +- One typed API client (`apps/web/src/lib/api.ts`) owns: base path `/api/v1`, the `X-Ianitor-UI: 1` + header on every request, `redirect: "manual"`, an `Idempotency-Key` per click (see §11.3), the error + envelope, the server-clock offset (§7.2), and the signed-out and lost-contact detection (§10, §11). +- Show the server's `error.message` as the sentence, verbatim. The UI switches on `error.code` only to + decide which buttons to offer, which field to mark and which words to bold (`params`). The table in §12 + gives every code, its sentence and its offer, so you can test that the sentence arrives and that the + right button appears. The UI writes its own sentence only for `ui.*` codes and for the few codes the + server has no sentence for (marked "UI text" in §12). +- Never put a token, share URL, password or one-time password in `localStorage`, `sessionStorage`, the + URL, a log line or an error report. Drop them from component state when their dialog closes. +- Dark only. No light theme, no theme switch. +- No external requests at runtime: fonts are self-hosted (§1.3), no CDN, no analytics. +- Dev server on 127.0.0.1 only (`pnpm --filter web dev`, never `--host`). + +--- + +## 1. Design tokens (packages/ui) + +### 1.1 The block to paste + +`packages/ui/src/tokens.css`. Apply the class `ia` to `` (the artifact puts the tokens on `.ia`; +`:root` would also work, but keep `.ia` so the shared Domi components scope the same way). + +The root font size is left at the browser default (16 px). The artifact rendered with rem = 16 px, so +every rem value below reproduces it exactly, and the UI still follows a user's own font-size setting. +Body text is 0.9375rem (15 px), as drawn. + +```css +.ia { + /* ── Ground and structure: violet-tinted iron black ───────────────────── */ + --ground: #0c0b0f; /* page ground; every ratio is measured on it */ + --colonnade: #121016; /* sidebar, phone bars, menus, dialogs, side panel */ + --surface: #18151d; /* fields, the last-change bar, cards */ + --surface-2: #221d28; /* hover, the current place, a chosen option */ + --hairline: #2c2633; /* dividers only, never a control edge */ + --hairline-strong: #3c3445; /* chip and frame edges (facts, not controls) */ + --control-edge: #7d7189; /* edge of every field, button, segmented control, engine chip */ + + /* ── Text ──────────────────────────────────────────────────────────────── */ + --text: #f1edf3; /* body text, hostnames */ + --text-2: #cfc6d4; /* secondary text, field labels */ + --muted: #a99eb1; /* hints, section labels, times */ + --disabled: #7a7183; /* disabled controls only, never content */ + + /* ── The lead: murex (Tyrian purple) ───────────────────────────────────── */ + --accent: #e0a3dc; /* links, focus ring, the current place, running state */ + --accent-strong: #f2c9ee; /* focus ring on the primary button; match codes */ + --primary-high: #8d3b89; /* primary fill, top */ + --primary-mid: #76306f; /* primary fill, 55 % */ + --primary-low: #5c2257; /* primary fill, foot */ + --primary-edge: #c77cc1; /* primary button edge */ + --on-primary: #ffffff; /* label on the primary fill */ + + /* ── Metal ─────────────────────────────────────────────────────────────── */ + --bronze: #b6adbe; /* ornaments: the interpunct rule (iron, not bronze) */ + --gilt: #f6f0f7; /* the wordmark only */ + + /* ── Second light: quiet iron (Domi's .domi-pill and .domi-status use these) */ + --second: #cfc6d4; + --second-strong: #f1edf3; + --second-edge: #7d7189; + + /* ── Status: blue / amber / vermilion, stepped in lightness (L* 84 / 68 / 58) */ + --healthy: #a6d6fa; /* host answers; a change was kept. Filled dot. */ + --kept: #a6d6fa; + --degraded: #d99a35; /* partly failing; a change was reverted or not applied. Half dot. */ + --reverted: #d99a35; + --down: #e2683a; /* not reachable; needs attention; paused; danger actions. Hollow ring. */ + --danger: #e2683a; + --on-danger: #170804; /* text on a filled danger button (none is planned) */ + --unknown: #a99eb1; /* no health check set; waiting for first check. Dashed ring. */ + --running: #e0a3dc; /* queued, applying, watching, switching, waiting for Custos (= accent) */ + + /* Status washes (banner backgrounds) and edges. color-mix() is what the artifact uses; + the resolved hex is in the comment, for tools that need a literal. */ + --wash-degraded: color-mix(in srgb, var(--degraded) 10%, var(--ground)); /* #201913 */ + --wash-kept: color-mix(in srgb, var(--kept) 10%, var(--ground)); /* #1b1f26 */ + --wash-down: color-mix(in srgb, var(--down) 10%, var(--ground)); /* #211413 */ + --edge-degraded: color-mix(in srgb, var(--degraded) 65%, var(--ground)); /* #916828 */ + --edge-kept: color-mix(in srgb, var(--kept) 65%, var(--ground)); /* #708fa8 */ + --edge-down: color-mix(in srgb, var(--down) 80%, var(--ground)); /* #b75531 */ + --edge-outline: color-mix(in srgb, var(--accent) 60%, var(--ground)); /* #8b668a, outline button */ + --hover-wash: color-mix(in srgb, var(--accent) 8%, transparent); /* quiet button hover */ + --danger-hover: color-mix(in srgb, var(--danger) 7%, transparent); + + /* ── Type ──────────────────────────────────────────────────────────────── */ + --font-inscription: Cinzel, "Trajan Pro", "Cormorant Garamond", Georgia, "Times New Roman", serif; + --font-book: "Cormorant Garamond", Cormorant, "EB Garamond", Garamond, Georgia, "Times New Roman", serif; + --font-hand: Manrope, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Arial, sans-serif; + + --fs-display: 2.6rem; --lh-display: 1.1; /* book 500: a view title ("Hosts") */ + --fs-h2: 1.9rem; --lh-h2: 1.15; /* book 500: panel title; phone view title uses 2.1rem */ + --fs-h3: 1.45rem; --lh-h3: 1.15; /* book 600: dialog and section titles */ + --fs-body: 0.9375rem; --lh-body: 1.6; /* hand 400: everything read (15 px) */ + --fs-host: 0.98rem; /* hand 600: hostname in a row */ + --fs-button: 0.95rem; /* hand 600; 700 on primary */ + --fs-field-label: 0.92rem; /* hand 400, text-2 */ + --fs-hint: 0.88rem; --lh-hint: 1.5; /* hand 400, muted: hints, notes */ + --fs-sub: 0.86rem; /* hand 400, muted: row sub-lines, times */ + --fs-chip: 0.78rem; /* 12.5 px, hand 400, text-2 */ + --fs-state: 0.95rem; /* hand 700, all-small-caps, tracking 0.12em */ + --fs-label: 0.74rem; /* hand 700, tracking 0.26em: SECTION LABELS */ + --fs-nav: 0.95rem; /* sidebar item, hand 600 */ + --fs-tab-phone: 0.78rem; /* bottom-bar label, hand 600 */ + --fs-wordmark: 0.8125rem; /* 13 px Cinzel 500, tracking 0.3em; phone 12 px, 0.26em */ + --fs-code: 2.2rem; /* Cinzel 500, tracking 0.16em: Custos match code */ + --tracking-state: 0.12em; + --tracking-label: 0.26em; + --tracking-wordmark: 0.3em; + + /* ── Spacing (Domi) ────────────────────────────────────────────────────── */ + --space-1: 0.35rem; /* label to its field */ + --space-2: 0.6rem; /* between buttons in a row, list items */ + --space-3: 1rem; /* field to field */ + --space-4: 1.4rem; /* panel padding */ + --space-5: 2rem; /* between sections of a view */ + --space-6: 3.5rem; /* a view's bottom padding */ + --target: 44px; /* minimum height and width of every control and touch target */ + + /* ── Radii ─────────────────────────────────────────────────────────────── */ + --radius-chip: 6px; + --radius-sm: 10px; /* quiet buttons, fields, nav items, menu items */ + --radius: 12px; /* primary button, cards inside panels */ + --radius-lg: 18px; /* panels, banners, the bar, the host list, dialogs */ + --radius-pill: 999px; /* chips, the engine chip */ + + /* ── Shadows ───────────────────────────────────────────────────────────── */ + --leaf-bevel: 0 0 0 1px rgba(199,124,193,0.25), 0 12px 40px -14px rgba(141,59,137,0.6), + inset 0 1px 0 rgba(255,220,250,0.30), inset 0 -2px 0 #3a1237; /* primary button */ + --carved: inset 0 2px 6px rgba(12,11,15,0.8), inset 0 -1px 0 rgba(182,173,190,0.16); /* fields */ + --inset-lit: inset 0 0 18px rgba(224,163,220,0.07); /* current nav item */ + --shadow-dialog: 0 40px 100px -40px rgba(0,0,0,0.95); /* dialogs, menus, popover */ + --scrim: rgba(12,11,15,0.82); /* behind modals */ + + /* ── Focus ─────────────────────────────────────────────────────────────── */ + --focus-ring: 2px solid var(--accent); /* outline, offset 3px, on every :focus-visible */ + --focus-ring-primary: 2px solid var(--accent-strong); + --focus-offset: 3px; + --focus-halo: 0 0 0 4px rgba(224,163,220,0.16); /* fields: border goes accent, plus this halo */ + + /* ── Motion (Domi's transitions; the last three are new for this UI) ──── */ + --dur-color: 0.3s; /* border, background, colour */ + --dur-lift: 0.45s; /* box-shadow, transform (primary hover lifts 1px) */ + --ease: ease; + --dur-tick: 1s; /* watch progress bar: linear, one step per second */ + --dur-enter: 0.18s; /* dialog, panel, menu, toast enter (opacity + 8px) */ + --dur-exit: 0.12s; + + /* ── Layout ────────────────────────────────────────────────────────────── */ + --sidebar-w: 232px; + --main-pad: 26px 32px 40px; /* desktop; phone 18px 16px 20px */ + --gutter-phone: 16px; + --panel-w: 480px; /* add/edit host side panel */ + --dialog-w: 520px; /* share, token, device dialogs */ + --popover-w: 420px; /* engine popover */ + --phone-bar-h: 56px; /* bottom navigation item height */ + --bp-phone: 720px; /* below: phone layout (header + bottom bar) */ + + color-scheme: dark; + background: var(--ground); + color: var(--text); + font-family: var(--font-hand); + font-size: var(--fs-body); + line-height: var(--lh-body); + font-variant-numeric: tabular-nums; +} +.ia *, .ia *::before, .ia *::after { box-sizing: border-box; } +.ia :focus-visible { outline: var(--focus-ring); outline-offset: var(--focus-offset); } +.ia h1, .ia h2, .ia h3, .ia p { margin: 0; } +.ia button { font: inherit; } +@media (prefers-reduced-motion: reduce) { + .ia *, .ia *::before, .ia *::after { animation: none !important; transition: none !important; } +} +``` + +Two things the artifact's theme.css also does, which you must keep in packages/ui: +the Domi button edges raised for contrast (`.domi-btn` edge = `--control-edge`; outline button edge = +`--edge-outline`; danger edge = `--edge-down`; primary edge = `--primary-edge`), and the primary +gradient `linear-gradient(180deg, var(--primary-high) 0%, var(--primary-mid) 55%, var(--primary-low) 100%)`. + +### 1.2 Contrast, every pair used (WCAG 2.x) + +Measured with the resolved hex values above. AA needs 4.5:1 for text, 3:1 for large text (24 px, or +18.7 px bold) and for control edges and focus indicators (1.4.11). + +**Text on the backgrounds it appears on** + +| Text \ background | ground #0c0b0f | colonnade #121016 | surface #18151d | surface-2 #221d28 | wash-degraded #201913 | wash-kept #1b1f26 | wash-down #211413 | +|:--|--:|--:|--:|--:|--:|--:|--:| +| text #f1edf3 | 16.95 | 16.33 | 15.59 | 14.24 | 15.00 | 14.28 | 15.46 | +| text-2 #cfc6d4 | 11.85 | 11.41 | 10.90 | 9.95 | 10.48 | 9.98 | 10.80 | +| muted #a99eb1 | 7.67 | 7.39 | 7.06 | 6.44 | 6.79 | 6.46 | 6.99 | +| accent #e0a3dc (links, running) | 9.76 | 9.39 | 8.97 | 8.19 | 8.63 | 8.22 | 8.89 | +| accent-strong #f2c9ee (match code) | 13.42 | 12.92 | 12.34 | 11.27 | n/u | n/u | n/u | +| healthy / kept #a6d6fa | 12.72 | 12.25 | 11.70 | 10.69 | n/u | 10.72 | n/u | +| degraded / reverted #d99a35 | 8.06 | 7.76 | 7.41 | 6.77 | 7.13 | n/u | n/u | +| down / danger #e2683a | 5.86 | 5.65 | 5.39 | 4.92 | n/u | n/u | 5.34 | +| gilt #f6f0f7 (wordmark) | 17.49 | 16.85 | n/u | n/u | n/u | n/u | n/u | +| disabled #7a7183 | 4.22 | 4.06 | 3.88 | 3.54 | | | | + +n/u = not used together. Every used pair passes AA for small text. `disabled` is below 4.5 by design: +WCAG exempts inactive controls, and a disabled control always has its reason in readable text nearby. +Never use `disabled` for content. + +Button labels on fills: on-primary #fff on primary-high 6.73, on primary-mid 8.67, on primary-low 11.53 +(the label sits across the gradient, so the floor is 6.73). on-danger on down 5.85 (reserved). +Quiet-button hover background (8 % accent over ground, #1d171f): text 15.19, text-2 10.62. + +**Edges and indicators (3:1 needed)** + +| Element | Against | Ratio | +|:--|:--|--:| +| control-edge #7d7189 (fields, quiet buttons, engine chip, segmented control) | ground / colonnade / surface / surface-2 | 4.29 / 4.13 / 3.95 / 3.61 | +| control-edge on banner washes | degraded / kept / down | 3.80 / 3.62 / 3.91 | +| outline-button edge #8b668a | ground / colonnade / surface | 4.08 / 3.93 / 3.75 | +| danger-button edge #b75531 | ground / colonnade | 4.07 / 3.92 | +| primary-edge #c77cc1 | ground / colonnade | 6.62 / 6.37 | +| focus ring accent #e0a3dc | ground / surface-2 | 9.76 / 8.19 | +| focus ring on primary, accent-strong | ground (outside the button) / primary-high | 13.42 / 4.61 | +| banner edges degraded #916828 / kept #708fa8 / down #b75531 | ground | 3.94 / 5.78 / 4.07 | +| status dots healthy / degraded / down / unknown | ground | 12.72 / 8.06 / 5.86 / 7.67 | +| progress fill accent | track surface-2 | 8.19 | +| chosen segment ring (accent 55 % over surface-2, #8b678b) | surface-2 | 3.46 | + +Decoration only, not required to pass: hairline 1.34, hairline-strong 1.65 (dividers and chip edges; +chips are facts, not controls). + +Status colours against each other: healthy/degraded 1.58, degraded/down 1.37. Not enough alone, which is +why every status carries a word and a shape (§2.2). Never colour alone. + +### 1.3 Fonts + +Self-host the Latin woff2 subsets in packages/ui/fonts (all OFL): Cinzel 500; Cormorant Garamond 500, +600, 500 italic; Manrope 400, 600, 700. `font-display: swap`. No Google Fonts request at runtime (the UI +runs on a home server behind Authelia and makes no outside requests). Italic Cormorant is only in the +Domi system; this UI does not use it. + +Where each face goes: Cinzel only for the wordmark "IANITOR DOMI" (written in capitals as is, never +text-transformed) and the Custos match code. Cormorant Garamond (book) only for headings: view title, +panel title, dialog title. Manrope (hand) for everything else. + +--- + +## 2. Components + +Each component lists: what it looks like, states, keyboard, ARIA. Class names follow the artifact +(`ia-*`, `domi-*`) so packages/ui can carry the CSS as drawn; Svelte components wrap them. + +### 2.1 Buttons (`Button.svelte`, Domi `.domi-btn`) + +| Variant | Look | Use | +|:--|:--|:--| +| primary | min-height 50px, padding 0 1.6rem, radius 12px, gradient fill, primary-edge, leaf-bevel, label #fff 700 | at most one per screen: "+ Host", "Apply", "Restore this version", "Copy link", "Issue", "Copy token", "Restore the last kept version" in the needs-attention banner | +| quiet (default) | min-height 44px, padding 0 1.1rem, radius 10px, transparent, control-edge, text-2 600 | Undo, Cancel, Close, secondary actions | +| outline | as quiet, edge #8b668a, label accent | an action inside a banner or card that leads but is not the primary: "Renew", "Edit and try again", "+ Device", "New token", "Switch to Caddy", "Turn on share links and copy link" | +| danger | as quiet, edge #b75531, label danger | "Revoke", "Stop all share links", menu item "Remove host" (as menu text colour) | +| link | no edge, no padding, accent, underline offset 0.2em, hit area ≥ 44px tall (pad vertically) | "More options…", "Show details", "Add a password", "See history" | + +States: hover (quiet: edge accent, bg `--hover-wash`, label text; primary: lifts 1px), focus-visible +(2px accent outline, offset 3px; primary uses accent-strong), active (no extra style), pending, disabled. +- **Pending**: after a click that waits on the API for more than 300 ms, keep the label, add a 16px + spinner before it, set `aria-busy="true"` and `aria-disabled="true"`, ignore further clicks. No width + change (reserve the spinner slot). +- **Disabled**: use `aria-disabled="true"` (not the `disabled` attribute) so the button stays focusable + and its reason can be read: `aria-describedby` points at the visible reason text. Look: label + `--disabled`, edge `--hairline`, no hover. +- Icon-only buttons (`.ia-icon-btn`, 44×44, radius 10px, text-2): always an `aria-label` + ("More for photos.home.example", "Close"). +- Icons are inline stroke SVGs, 18px, stroke 1.8–2.2, `aria-hidden="true"`. The artifact's set: + plus, undo arrow, check, clock, link, pencil, history, trash, key, gear, building (hosts), swap arrows, + copy, chevron down, dots. + +### 2.2 Status: dot and word (`Status.svelte`) + +Always the pair: a 12px shape (decorative, `aria-hidden`) plus a word in small capitals (700, +`font-variant-caps: all-small-caps`, tracking 0.12em, 0.95rem). The word is the accessible text. + +| `data-s` | Dot | Word colour | Words used | +|:--|:--|:--|:--| +| healthy | filled circle, healthy | healthy | "healthy" | +| kept | (no dot; check icon) | kept | "kept" | +| degraded | 2px ring, left half filled, degraded | degraded | "degraded" | +| reverted | (undo-arrow icon) | reverted | "reverted", "not applied" | +| down | 3px hollow ring, down | down | "down", "needs attention", "paused", "renew now", "expired" | +| unknown | 2px dashed ring, unknown | muted | "not checked", "waiting" (pending health), "stopped", "revoked" | +| running | clock icon, accent | accent | "waiting", "applying", "watching", "switching" | + +The degraded dot: `border: 2px solid var(--degraded); background: linear-gradient(90deg, var(--degraded) 50%, transparent 50%)`. +A dot with no word is only allowed where the word is next to it in the same row on phone +(the phone row repeats the word in the sub-line). + +### 2.3 Chips (`Chip.svelte`, `.ia-chip`) + +Facts about a host, not controls: pill, 1px hairline-strong, text-2, 12.5px, `white-space: nowrap`, +padding 1px 10px, gap 6px between chips, wraps. Not focusable, no role. + +| Field | Chip text | +|:--|:--| +| tls = domi | "Domi certificate" | +| tls = letsencrypt | "Let's Encrypt" | +| auth = forward-auth | "Sign-in first" | +| auth = none | no chip (see open question Q11) | +| share_links = true | "Share links on" | +| websockets = false | "No websockets" (G19: no chip when true, the default) | +| access_log = truncated | "Visit log on" | + +### 2.4 Engine chip (`EngineChip.svelte`, `.ia-engine`) + +A control: pill, min-height 44px, padding 0 16px 0 14px, control-edge, surface background, text 600 +0.92rem. Content: status dot · `` "Engine" (muted, 400) · engine name · chevron down. +- Pingora running: dot healthy, "Engine Pingora". +- Caddy running: dot healthy, "Engine Caddy" ``"(fallback)"``. +- Switching: clock icon in accent instead of the dot, "Engine Switching…". +- Stopped (control cannot reach the engine, `engine.state = "stopped"`): dot down, "Engine Pingora" and + the word is announced: accessible name "Engine: Pingora, not answering". +Phone: no "Engine" label (as drawn): dot · name · chevron, padding 0 12px. +`