diff --git a/Cargo.lock b/Cargo.lock index 76ea7d2..cabd477 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,13 +1299,17 @@ dependencies = [ "ianitor-edge", "ianitor-testkit", "log", - "rcgen", + "p12-keystore", + "qrcode", "ring", + "rpassword", "rustls", + "rustls-pki-types", "serde", "serde_json", "thiserror 2.0.21", "tokio", + "tokio-rustls", "toml", "utoipa", ] @@ -1080,13 +1319,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]] @@ -1097,6 +1341,7 @@ dependencies = [ "ianitor-core", "ianitor-edge", "ianitor-testkit", + "rcgen", "rustls", "serde_json", "tokio", @@ -1119,6 +1364,7 @@ dependencies = [ "instant-acme", "log", "pingora", + "rcgen", "ring", "rustls", "rustls-pki-types", @@ -1274,6 +1520,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" @@ -1606,6 +1862,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" @@ -1635,6 +1914,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" @@ -1645,6 +1934,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" @@ -1935,12 +2233,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" @@ -1987,6 +2337,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" @@ -2029,6 +2385,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" @@ -2067,6 +2434,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" @@ -2152,6 +2534,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" @@ -2288,6 +2691,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" @@ -2312,6 +2725,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" @@ -2466,8 +2891,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]] @@ -2524,6 +2971,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" @@ -2924,7 +3381,7 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "sha1", + "sha1 0.10.7", "thiserror 2.0.21", ] @@ -2955,6 +3412,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" @@ -3196,6 +3663,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/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..f073ddc --- /dev/null +++ b/apps/web/src/App.svelte @@ -0,0 +1,175 @@ + + + +{#if route.view === "signed-in"} + +{:else} + +
+ +
IANITOR DOMI{#if app.phone}{/if}
+
+ + {#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} +
+ +
+ + {#if app.panel?.kind === "engine"} + { + app.panel = null; + document.querySelector("[data-engine-chip]")?.focus(); + }} /> + {/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..c7c2dcc --- /dev/null +++ b/apps/web/src/components/ChangeBar.svelte @@ -0,0 +1,165 @@ + + + +{#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} + {#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}
{/if} + {#snippet actions()} + {#if offer}{/if} + {/snippet} + +{/if} + +{#if last || active} +
+ {#if active} +
+
{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"} + {runningHeading(active.summary, active.kind ? active : null)}
+
{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}
+ {#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 ? pushLine : 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 canPushNow}{/if} + {#if undo?.target} + + {/if} + {/if} +
+{/if} + + diff --git a/apps/web/src/components/EngineChip.svelte b/apps/web/src/components/EngineChip.svelte new file mode 100644 index 0000000..ddf194b --- /dev/null +++ b/apps/web/src/components/EngineChip.svelte @@ -0,0 +1,29 @@ + + + +{#if o} + +{/if} + + diff --git a/apps/web/src/components/EnginePopover.svelte b/apps/web/src/components/EnginePopover.svelte new file mode 100644 index 0000000..2d28610 --- /dev/null +++ b/apps/web/src/components/EnginePopover.svelte @@ -0,0 +1,121 @@ + + + + +

Engine

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

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

+ {:else} +

+ {#if e?.since}Since {whenInline(e.since, app.now)}. {/if} + {#if running === "pingora"} + {#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if} + {#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if} + {:else}Pingora is ready with the same routes.{/if} +

+ {#if running === "pingora" && !notReady && fr?.differences.length} +
+ {/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}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}
  • +
  • Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.
  • + {:else} +
  • Share links work 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..94a4554 --- /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..9fcad4a --- /dev/null +++ b/apps/web/src/components/HostMenu.svelte @@ -0,0 +1,88 @@ + + + + + + + +
+ + {#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..961825d --- /dev/null +++ b/apps/web/src/components/HostPanel.svelte @@ -0,0 +1,538 @@ + + + + + {#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 ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#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 restoreProblem}

{restoreProblem}

{/if} + {#snippet actions()} + {#if app.overview?.undo?.target}{/if} + {/snippet} +
+ {/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..f11bf7c --- /dev/null +++ b/apps/web/src/components/IntermediateBanner.svelte @@ -0,0 +1,65 @@ + + + +{#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. The next page has the files, the command and a fingerprint to check. + {/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 on the offline computer."} + {#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..4923ade --- /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} + + {: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..de8492a --- /dev/null +++ b/apps/web/src/components/TopBanners.svelte @@ -0,0 +1,86 @@ + + + +{#if o?.paused} + + {#snippet title()}{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"} {pause.bold}{/snippet} + {#if pause.line2}{pause.line2}{/if} + {#if restorable && o.undo?.target}

Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.

{/if} + {#if problem}

{problem}

{/if} + {#if pauseDetail}
{/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 {atTime(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..be2af13 --- /dev/null +++ b/apps/web/src/lib/app.svelte.ts @@ -0,0 +1,180 @@ +// 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, newKey, sentence, 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, + /** After a kept add or edit: the row whose More button gets focus (§7.5). */ + focusHost: null as string | null, + /** Narrower than 720 px (the phone layout, handoff §5.2). */ + phone: false, + /** 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" && typeof window.matchMedia === "function") { + const mq = window.matchMedia("(max-width: 719.98px)"); + app.phone = mq.matches; + mq.addEventListener?.("change", (e) => (app.phone = e.matches)); +} + +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; +} + +/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel. + * Returns the sentence to show when it could not start. */ +export async function restoreLastKept(): Promise { + const o = app.overview; + if (!o?.undo?.target) return null; + try { + const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() }); + if (a.data) app.panel = { kind: "host", resume: a.data.apply.id }; + return null; + } catch (e) { + return sentence(e); + } +} + +/** Whether the pause can be cleared by restoring the last kept version. */ +export function restorable(): boolean { + const o = app.overview; + return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target; +} diff --git a/apps/web/src/lib/applies.ts b/apps/web/src/lib/applies.ts new file mode 100644 index 0000000..d724450 --- /dev/null +++ b/apps/web/src/lib/applies.ts @@ -0,0 +1,63 @@ +// 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 { app, 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; + if (app.signedOut) { + // No requests while signed out (the overview poll stops too); look again shortly. + timer = setTimeout(tick, every); + 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..9e7dfbb --- /dev/null +++ b/apps/web/src/lib/format.ts @@ -0,0 +1,115 @@ +// 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}`; +} + +/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */ +export function whenInline(iso: string | null | undefined, now = Date.now()): string { + return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase()); +} + +/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */ +export function atTime(iso: string | null | undefined, now = Date.now()): string { + const w = when(iso, now); + if (!w) return ""; + if (w.startsWith("Today ")) return `at ${w.slice(6)}`; + if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`; + const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w); + return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`; +} + +/** "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); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */ +export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): 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`); + if (short) return parts.join(", "); + 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..73bffda --- /dev/null +++ b/apps/web/src/lib/types.ts @@ -0,0 +1,251 @@ +// 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; + csr_sha256?: string | null; + not_after: string | null; + message_code: string; + message: string; + approve_command: string | null; + file_base?: 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; compared: number; matched: number; differences: string[] } | 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; kind: string; hosts: string[]; watch_ends_at: string | 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; auth_logout_url?: string | null } | null; + paused: Blocked | null; + paused_reason: string | null; + paused_detail?: 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; + device_valid_until: string | null; + 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..cea22c1 --- /dev/null +++ b/apps/web/src/views/Certificates.svelte @@ -0,0 +1,257 @@ + + + +
+

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"}{:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000}{/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.

+
+ +

{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.

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

Waiting for approval

+

Custos cannot approve device certificates yet, so 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 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). 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 {atTime(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..5431572 --- /dev/null +++ b/apps/web/src/views/History.svelte @@ -0,0 +1,178 @@ + + + +

{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} + + diff --git a/apps/web/src/views/Hosts.svelte b/apps/web/src/views/Hosts.svelte new file mode 100644 index 0000000..201656f --- /dev/null +++ b/apps/web/src/views/Hosts.svelte @@ -0,0 +1,132 @@ + + + +
+
+

Hosts

+ {#if o}

{countsSentence(o.counts, app.phone)}

{/if} +
+
+ {#if !app.phone}{/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} + + diff --git a/apps/web/src/views/RenewByHand.svelte b/apps/web/src/views/RenewByHand.svelte new file mode 100644 index 0000000..9be98c9 --- /dev/null +++ b/apps/web/src/views/RenewByHand.svelte @@ -0,0 +1,143 @@ + + + +

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.

+
+
+
+

Step 2

+

Sign it on the offline computer

+

Copy both files to the offline computer that holds the Domi root.

+

First check that the request is the one this server made. This prints its fingerprint:

+
{checkCmd}
+ {#if r.csr_sha256}

openssl must print the same fingerprint as this page: {group(r.csr_sha256)}

{/if} +

Then sign it:

+
{signCmd}
+
{#if copied}Copied{/if}
+

On a computer with Ianitor installed, ianitor-control ca sign signs it instead and shows the match code {r.match_code}.

+
+
+

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..2cd2f0f --- /dev/null +++ b/apps/web/src/views/Settings.svelte @@ -0,0 +1,280 @@ + + + +

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 " + whenInline(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"}

+ {#if app.overview?.site?.auth_logout_url}

Sign out

{/if} + {: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 {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(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 {whenInline(l.created_at, app.now)} · expires {whenInline(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 ${longDate(made.expires_at, false)}.` : "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..8a21e87 --- /dev/null +++ b/apps/web/tests/flows.test.ts @@ -0,0 +1,245 @@ +// 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 (Mark, Q1: the accepted 4th)", 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)); + // The renewal is waiting: the banner says where to sign it (no code to compare with openssl). + await screen.findByRole("button", { name: "Sign it by hand" }); + 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("focus", () => { + it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => { + start(); + await click(await screen.findByRole("button", { name: "Add a host" })); + await user.keyboard("recipes.home.test"); + expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test"); + }); + + it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => { + start(); + const more = await screen.findByRole("button", { name: "More for wiki.home.test" }); + await click(more); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + const copy = await screen.findByRole("button", { name: "Copy link" }); + await waitFor(() => expect(document.activeElement).toBe(copy)); + // jsdom fires no cancel event on Esc for a modal dialog: close it with its button. + await click(screen.getByRole("button", { name: "Close" })); + await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(more)); + }); + + it("the engine popover closes with Esc and focus goes back to the chip", async () => { + start(); + const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ }); + await click(chip); + await screen.findByRole("button", { name: "Switch to Caddy" }); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull()); + expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ })); + }); + + it("a click on the engine chip while its popover is open closes it", async () => { + start(); + const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ }); + await click(chip); + await screen.findByRole("button", { name: "Switch to Caddy" }); + await new Promise((r) => setTimeout(r, 10)); + await click(chip); + await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull()); + }); +}); + +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..1c1228e --- /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, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] }, + 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/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3929d18..bd32f97 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -15,8 +15,17 @@ 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 +rustls.workspace = true +rustls-pki-types.workspace = true +tokio-rustls.workspace = true axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] } utoipa = "5" tokio.workspace = true @@ -29,13 +38,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 [lints] workspace = true diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index a6d12fe..1ab3760 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -124,11 +124,50 @@ fn replay(st: &AppState, s: Stored) -> Response { // ---------------------------------------------------------------- overview and hosts +/// What is known to differ on Caddy for these routes (decision Q3: switch allowed, the +/// differences listed). Control cannot run the differential suite at runtime; these are the +/// suite's known differences (tests/diff, KD-*) applied to the hosts that use the feature. +/// Returns (hosts compared, hosts that behave the same, sentences). +pub fn fallback_differences(m: &ianitor_core::Model) -> (u32, u32, Vec) { + let mut out = Vec::new(); + let mut matched = 0u32; + for h in m.hosts() { + let before = out.len(); + if h.share_links { + out.push(format!( + "{}: share links do not work; visitors with a link get the normal sign-in.", + h.hostname + )); + } + if h.auth == ianitor_core::AuthMode::ForwardAuth { + out.push(format!( + "{}: if Authelia's answer is broken or cut off, Pingora refuses the visit; Caddy goes by its status alone.", + h.hostname + )); + } + if out.len() == before { + matched += 1; + } + } + if !m.hosts().is_empty() { + out.push( + "Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none." + .into(), + ); + } + let n = u32::try_from(m.hosts().len()).unwrap_or(u32::MAX); + (n, matched, out) +} + /// Everything the main screen shows, in one call. Answers 304 to a matching If-None-Match. #[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 @@ -169,6 +208,9 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result Result Result { .links .iter() .rev() + // A device install link carries its one-time token in the path: never listed. It + // expires within minutes, and "Stop all" stops it with the others. + .filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/")) .map(|l| ShareLinkView { id: l.id.clone(), hostname: l.hostname.clone(), @@ -1278,19 +1381,26 @@ impl Modify for Bearer { overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host, retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview, get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token, - mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi + mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi, + super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request, + super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, + super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine ), components(schemas( HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost, Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList, TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView, - HealthReport, Done + HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView, + super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody, + super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody, + FallbackReady )), modifiers(&Bearer), tags( (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), - (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links") + (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"), + (name = "certs"), (name = "engine") ) )] pub struct ApiDoc; diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index 6edfd46..c63c84f 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -16,6 +16,8 @@ #![allow(clippy::result_large_err)] pub mod handlers; +pub mod pki; +pub mod ui; pub mod views; use std::collections::HashMap; @@ -317,7 +319,7 @@ fn body_error(e: &serde_json::Error) -> 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,55 @@ 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, + /// The Authelia user name, and the name to show (`Remote-Name` when it is usable). + User(String, String), +} + +fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { + 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':') => + { + let display = headers + .get("remote-name") + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|n| { + !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control) + }) + .unwrap_or(u) + .to_owned(); + UiIdentity::User(u.to_owned(), display) + } + _ => UiIdentity::NoUser, + }, + _ => 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 +425,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, display) => { + // 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: display, + }); + return Ok(next.run(req).await); + } + } let auth = req .headers() .get(header::AUTHORIZATION) @@ -429,7 +527,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 +601,36 @@ 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}/ext", get(pki::get_ext)) + .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..d3b57c7 --- /dev/null +++ b/crates/control/src/api/pki.rs @@ -0,0 +1,839 @@ +// 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: SHA-256 of the request (DER, lowercase hex), what + /// `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints on the offline computer. + pub csr_sha256: 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, + /// Renewals: the base name of the files (`.csr`, `.ext`, `.crt`). + pub file_base: 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(), + csr_sha256: r + .csr_pem + .as_deref() + .and_then(|c| ianitor_core::pki::csr_der(c).ok()) + .map(|d| ianitor_core::pki::sha256_hex(&d)), + 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_core::pki::openssl_sign_command(&file_base(r)) + } else { + format!("ianitor-control pki approve {}", r.match_code) + } + }), + file_base: (r.kind == "intermediate").then(|| file_base(r)), + problem: r.error.clone(), + } +} + +/// `domi-intermediate-2026-11-07`, from the day the request was made. +pub fn file_base(r: &Request) -> String { + format!( + "domi-intermediate-{}", + rfc3339(r.created_at).get(..10).unwrap_or("request") + ) +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct IntermediateView { + /// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`. + 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, + /// When a device certificate issued now would end: a year, but never past the + /// intermediate's end (decision Q7). None without an intermediate. + pub device_valid_until: Option, + pub server_lifetime_days: u32, + /// `manual` (on the server, until Custos can) or `custos`. + pub approval: String, + /// Open device requests. + pub requests: Vec, + /// Set while the device list is not in force (could not be written or handed to the + /// proxy); Ianitor retries every few seconds. + pub devices_problem: Option, +} + +// ---------------------------------------------------------------- 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, + device_valid_until: p.intermediate_info().map(|i| { + let end = (t as i64 + i64::from(ianitor_core::pki::DEVICE_DAYS) * 86_400) + .min(i.not_after); + rfc3339(end.max(0) as u64) + }), + server_lifetime_days: ianitor_core::pki::SERVER_DAYS, + approval: c + .cfg + .pki + .as_ref() + .map(|p| p.approval.clone()) + .unwrap_or_default(), + requests, + devices_problem: c + .devices_problem + .lock() + .ok() + .and_then(|p| p.clone()) + .map(|_| Blocked { + code: "pki.devices_unwritten".into(), + message: message("pki.devices_unwritten", &Params::new()), + }), + }) + }) + .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.clone().map(|c| (c, file_base(&r)))) + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + let (csr, base) = csr; + let mut r = csr.into_response(); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/pkcs10"), + ); + if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) { + r.headers_mut().insert(header::CONTENT_DISPOSITION, v); + } + 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); + // The revocation is recorded; it is in force only once the engines have the new list. + if let Err(e) = st.ctl.devices_changed().await { + let mut err = ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "pki.devices_unwritten", + Params::new(), + ); + err.body.detail = Some(e); + return Err(err); + } + 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}") +} + +/// `GET` on a one-time link: a small page with a Download button that posts back. Link +/// previews and prefetchers only ever GET, so they cannot use up the download. +pub async fn bundle_page(st: Arc, token: String) -> Response { + let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit()); + let name = if valid { + let ctl = st.ctl.clone(); + tokio::task::spawn_blocking(move || { + ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now())) + }) + .await + .ok() + .flatten() + } else { + None + }; + let (status, body) = match name { + Some(n) => ( + StatusCode::OK, + format!( + "

Install the certificate for {}

\ +

This link works once. After the download, open the file and enter the \ + one-time password shown in Ianitor.

\ +
", + html_escape(&n) + ), + ), + None => ( + StatusCode::GONE, + format!( + "

This link has been used

{}

", + html_escape(&message("pki.bundle_used", &Params::new())) + ), + ), + }; + let page = format!( + "\ + \ + Ianitor: device certificate\ + \ +
{body}
" + ); + let mut r = (status, page).into_response(); + let h = r.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + h.insert("referrer-policy", HeaderValue::from_static("no-referrer")); + h.insert( + "content-security-policy", + HeaderValue::from_static( + "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'", + ), + ); + r +} + +fn html_escape(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + '\'' => o.push_str("'"), + c => o.push(c), + } + } + o +} + +/// The one-time download itself (`POST`, from the link's page). The link is the secret: no +/// token or sign-in is needed, and it works once. +#[utoipa::path(post, 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" { + ["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))) +} + +/// The openssl extensions file for signing a renewal by hand (the same profile Custos will +/// use; docs/pki.md). +#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs", + responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_ext(State(st): Shared, Path(id): Path) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let r = blocking(&st, move |c| { + pki(c)? + .request(&id, now())? + .filter(|r| r.kind == "intermediate") + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response(); + resp.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r))) + { + resp.headers_mut().insert(header::CONTENT_DISPOSITION, v); + } + Ok(resp) +} diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs new file mode 100644 index 0000000..8b878c8 --- /dev/null +++ b/crates/control/src/api/ui.rs @@ -0,0 +1,124 @@ +// 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(); + } + let token = token.to_owned(); + // GET shows the page; only its button (POST) uses the link up. + return match req.method().as_str() { + "GET" | "HEAD" => super::pki::bundle_page(st, token).await, + "POST" => super::pki::download_bundle(State(st), AxPath(token)) + .await + .unwrap_or_else(IntoResponse::into_response), + _ => ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .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..323efd1 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,34 @@ 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, + /// Hosts in the current routes, and how many of them behave the same on Caddy as far as + /// Ianitor knows (the differential tests' known differences, applied to these hosts). + pub compared: u32, + pub matched: u32, + /// What is different on Caddy, in plain English (per host first, then for every host). + pub differences: Vec, } #[derive(Debug, Clone, Serialize, ToSchema)] @@ -477,6 +500,11 @@ pub struct ActiveApply { pub state: String, pub summary: String, pub seconds_left: Option, + /// `add`, `edit`, `remove`, `undo`, `restore`, `share_links`: the UI writes the heading. + pub kind: String, + pub hosts: Vec, + /// When the health watch ends (only while watching), for a local countdown. + pub watch_ends_at: Option, pub queued: usize, } @@ -496,6 +524,8 @@ pub struct SiteView { pub secrets: Vec, pub watch_seconds: u64, pub share_links_available: bool, + /// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link. + pub auth_logout_url: Option, } #[derive(Debug, Clone, Serialize, ToSchema)] @@ -507,14 +537,27 @@ 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, + /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`, + /// `repo.unreadable`, …), so the UI can offer the right action. + pub paused_reason: Option, + /// The technical detail behind the pause, for "Show details" (never a secret). + pub paused_detail: 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 { @@ -526,7 +569,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 +664,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/caddy_guard.rs b/crates/control/src/caddy_guard.rs new file mode 100644 index 0000000..e931672 --- /dev/null +++ b/crates/control/src/caddy_guard.rs @@ -0,0 +1,269 @@ +// 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 deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an +//! unconfirmed change never outlives control). Edge drops a trial by itself when control does +//! not confirm it in time; Caddy has no such clock, so two things outside control's own process +//! stand in for it: +//! +//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs +//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the +//! last good config) at once; +//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is +//! covered too): once a second, it reverts a trial whose deadline has passed. +//! +//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial, +//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard +//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is +//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between +//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave +//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or +//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed +//! config, so loading it is always safe. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::config::Config; +use crate::records::Journal; +use crate::util::{read_json, write_json}; + +pub const DEADLINE_FILE: &str = "caddy-trial.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TrialDeadline { + pub apply_id: String, + /// Unix seconds. + pub deadline: u64, +} + +fn path(state_dir: &Path, suffix: &str) -> PathBuf { + state_dir.join(format!("{DEADLINE_FILE}{suffix}")) +} + +/// Before a trial goes into Caddy. +pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> { + write_json( + &path(state_dir, ""), + &TrialDeadline { + apply_id: apply_id.to_owned(), + deadline, + }, + ) +} + +/// Control, before it confirms: `true` if it got the deadline first (the guard has not +/// reverted the trial), `false` if the guard did. +pub fn claim(state_dir: &Path) -> bool { + let claimed = path(state_dir, ".claimed"); + if std::fs::rename(path(state_dir, ""), &claimed).is_err() { + return false; + } + let _ = std::fs::remove_file(claimed); + true +} + +/// After a trial is reverted (or at start): nothing is out any more. +pub fn disarm(state_dir: &Path) { + for s in ["", ".claimed", ".expired", ".reverting"] { + let _ = std::fs::remove_file(path(state_dir, s)); + } +} + +pub fn armed(state_dir: &Path) -> Option { + read_json(&path(state_dir, "")).ok().flatten() +} + +/// Whether control's journal says the change is confirmed (then it is being promoted and +/// caddy.json will hold it; nothing to revert). +fn confirmed(state_dir: &Path) -> bool { + read_json::(&state_dir.join("journal.json")) + .ok() + .flatten() + .is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted") +} + +/// What to do now, for a deadline file as found (pure, for the tests). +#[derive(Debug, PartialEq, Eq)] +pub enum Verdict { + Nothing, + Revert, +} + +pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict { + match armed { + Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert, + _ => Verdict::Nothing, + } +} + +/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`). +fn caddy_serves(cfg: &Config) -> bool { + cfg.engine + .as_ref() + .is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy") +} + +/// A revert that stopped half way (the guard died while loading) counts as armed again. +fn resume_half_done(dir: &Path) { + let reverting = path(dir, ".reverting"); + if reverting.exists() && !path(dir, "").exists() { + let _ = std::fs::rename(reverting, path(dir, "")); + } +} + +/// Take the deadline away from control (rename to `.reverting`), load the last good +/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the +/// load fails, the deadline is given back, so the next try (or control's own claim, while +/// Caddy still runs the trial) decides. +async fn revert(cfg: &Config, why: &str) -> Result { + let dir = &cfg.state_dir; + let reverting = path(dir, ".reverting"); + if std::fs::rename(path(dir, ""), &reverting).is_err() { + // Control claimed it a moment ago: it confirms; nothing to do. + return Ok(false); + } + let loaded = async { + let sock = cfg + .caddy_compile() + .caddy_admin_socket + .clone() + .ok_or("no caddy_admin_socket is configured")?; + let text = std::fs::read(&cfg.caddy.config) + .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; + crate::caddy_link::load(Path::new(&sock), &text).await?; + if !crate::caddy_link::runs(Path::new(&sock), &text).await? { + return Err("Caddy took caddy.json but does not run it".to_owned()); + } + Ok::<_, String>(()) + } + .await; + match loaded { + Ok(()) => { + let _ = std::fs::rename(&reverting, path(dir, ".expired")); + log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config"); + Ok(true) + } + Err(e) => { + let _ = std::fs::rename(&reverting, path(dir, "")); + Err(format!("{why}, but Caddy could not be put back yet: {e}")) + } + } +} + +/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once +/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no +/// Caddy trial: a deadline left behind is cleared and nothing fails. +pub async fn revert_after_stop(cfg: &Config) -> Result { + let dir = &cfg.state_dir; + if !caddy_serves(cfg) { + disarm(dir); + return Ok(false); + } + resume_half_done(dir); + let mut wait = 1; + loop { + let r = match verdict( + armed(dir).as_ref(), + confirmed(dir), + crate::util::now(), + true, + ) { + Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await, + Verdict::Nothing => Ok(false), + }; + match r { + Err(e) if wait <= 8 => { + log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s"); + tokio::time::sleep(std::time::Duration::from_secs(wait)).await; + wait *= 2; + } + other => return other, + } + } +} + +/// One tick of `ianitor-control caddy-guard`. +pub async fn tick(cfg: &Config) -> Result { + let dir = &cfg.state_dir; + if !caddy_serves(cfg) { + return Ok(false); + } + resume_half_done(dir); + match verdict( + armed(dir).as_ref(), + confirmed(dir), + crate::util::now(), + false, + ) { + Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await, + Verdict::Nothing => Ok(false), + } +} + +/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries +/// again with a growing pause (2, 4, … 30 s). +pub async fn run(cfg: Config) -> Result<(), String> { + log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display()); + let mut pause = 1u64; + loop { + match tick(&cfg).await { + Ok(_) => pause = 1, + Err(e) => { + pause = (pause * 2).min(30); + log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s"); + } + } + tokio::time::sleep(std::time::Duration::from_secs(pause)).await; + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn d(deadline: u64) -> TrialDeadline { + TrialDeadline { + apply_id: "ch_1".into(), + deadline, + } + } + + #[test] + fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() { + assert_eq!(verdict(None, false, 100, false), Verdict::Nothing); + assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing); + assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert); + assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing); + } + + #[test] + fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() { + assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert); + assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing); + assert_eq!(verdict(None, false, 1, true), Verdict::Nothing); + } + + #[test] + fn control_and_the_guard_cannot_both_have_the_deadline() { + let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + arm(&dir, "ch_1", 10).unwrap(); + assert_eq!(armed(&dir), Some(d(10))); + // The guard took it (as `revert` does): control's claim fails. + std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap(); + assert!(!claim(&dir)); + disarm(&dir); + // Control claims first: nothing is left for the guard. + arm(&dir, "ch_1", 10).unwrap(); + assert!(claim(&dir)); + assert!(armed(&dir).is_none()); + assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err()); + disarm(&dir); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs new file mode 100644 index 0000000..4dcc777 --- /dev/null +++ b/crates/control/src/caddy_link.rs @@ -0,0 +1,366 @@ +// 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 Caddy fallback while it serves (Mark, 2026-11-08: changes keep +//! working under Caddy): loading a config through Caddy's admin API on its Unix socket +//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host +//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch, +//! judged like edge's), and the certificate Caddy serves. + +use std::net::SocketAddr; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const TIMEOUT: Duration = Duration::from_secs(10); + +/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). +async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec), String> { + #[cfg(unix)] + { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let exchange = async { + let mut s = tokio::net::UnixStream::connect(socket).await?; + s.write_all(request).await?; + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await?; + Ok::<_, std::io::Error>(buf) + }; + let buf = tokio::time::timeout(TIMEOUT, exchange) + .await + .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? + .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; + let split = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("no answer from Caddy's admin API")?; + let head = String::from_utf8_lossy(&buf[..split]); + let status: u16 = head + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or("no answer from Caddy's admin API")?; + Ok((status, buf[split + 4..].to_vec())) + } + #[cfg(not(unix))] + { + let _ = (socket, request); + Err("Caddy's admin socket needs Unix".into()) + } +} + +/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the +/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as +/// the running one, so certificate and device files are read again (without it an identical +/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`). +pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { + let mut req = format!( + "POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", + config.len() + ) + .into_bytes(); + req.extend_from_slice(config); + let (status, body) = admin(socket, &req).await?; + if (200..300).contains(&status) { + Ok(()) + } else { + Err(format!( + "Caddy refused the config ({status}): {}", + String::from_utf8_lossy(&body) + .trim() + .chars() + .take(400) + .collect::() + )) + } +} + +/// The config Caddy runs now. +pub async fn running_config(socket: &Path) -> Result { + let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?; + if status != 200 { + return Err(format!( + "Caddy's admin API answered {status} to GET /config/" + )); + } + serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}")) +} + +/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter). +pub async fn runs(socket: &Path, config: &[u8]) -> Result { + let want: serde_json::Value = + serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?; + Ok(running_config(socket).await? == want) +} + +/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Probe { + /// The status Caddy answered with (its own 502/503 when the upstream is down). + Status(u16), + /// No answer at all (connection, TLS or timeout). + NoAnswer(String), +} + +/// The probe does not check Caddy's certificate: it talks to this machine's own listener +/// on loopback to see whether the *upstream* answers through it, nothing else. +#[derive(Debug)] +struct AnyCert; + +impl rustls::client::danger::ServerCertVerifier for AnyCert { + fn verify_server_cert( + &self, + _end_entity: &rustls_pki_types::CertificateDer<'_>, + _intermediates: &[rustls_pki_types::CertificateDer<'_>], + _server_name: &rustls_pki_types::ServerName<'_>, + _ocsp: &[u8], + _now: rustls_pki_types::UnixTime, + ) -> Result { + Ok(rustls::client::danger::ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + _message: &[u8], + _cert: &rustls_pki_types::CertificateDer<'_>, + _dss: &rustls::DigitallySignedStruct, + ) -> Result { + Ok(rustls::client::danger::HandshakeSignatureValid::assertion()) + } + fn verify_tls13_signature( + &self, + _message: &[u8], + _cert: &rustls_pki_types::CertificateDer<'_>, + _dss: &rustls::DigitallySignedStruct, + ) -> Result { + Ok(rustls::client::danger::HandshakeSignatureValid::assertion()) + } + fn supported_verify_schemes(&self) -> Vec { + rustls::crypto::ring::default_provider() + .signature_verification_algorithms + .supported_schemes() + } +} + +pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let started = Instant::now(); + let run = async { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyCert)) + .with_no_client_auth(); + let name = + rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?; + let tcp = tokio::net::TcpStream::connect(addr) + .await + .map_err(|e| e.to_string())?; + let mut tls = tokio_rustls::TlsConnector::from(Arc::new(cfg)) + .connect(name, tcp) + .await + .map_err(|e| e.to_string())?; + let req = format!( + "GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: ianitor-watch\r\nConnection: close\r\n\r\n" + ); + tls.write_all(req.as_bytes()) + .await + .map_err(|e| e.to_string())?; + let mut head = [0u8; 64]; + let mut n = 0; + while n < 13 { + let k = tls.read(&mut head[n..]).await.map_err(|e| e.to_string())?; + if k == 0 { + break; + } + n += k; + } + let line = String::from_utf8_lossy(&head[..n]); + line.split(' ') + .nth(1) + .and_then(|s| s.parse::().ok()) + .ok_or_else(|| "no HTTP status".to_owned()) + }; + match tokio::time::timeout(Duration::from_secs(5), run).await { + Ok(Ok(s)) => Probe::Status(s), + Ok(Err(e)) => Probe::NoAnswer(e), + Err(_) => Probe::NoAnswer(format!( + "no answer within {} s", + started.elapsed().as_secs() + )), + } +} + +/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether +/// Caddy really read the certificate files again (the backstop for B1). +pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result { + let run = async { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyCert)) + .with_no_client_auth(); + let name = + rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?; + let tcp = tokio::net::TcpStream::connect(addr) + .await + .map_err(|e| e.to_string())?; + let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg)) + .connect(name, tcp) + .await + .map_err(|e| e.to_string())?; + let (_, conn) = tls.get_ref(); + let leaf = conn + .peer_certificates() + .and_then(|c| c.first()) + .ok_or("Caddy sent no certificate")?; + Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref())) + }; + tokio::time::timeout(Duration::from_secs(5), run) + .await + .map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())? +} + +/// One health probe of an upstream, made by control while Caddy serves, with edge's rules +/// (crates/edge/src/health.rs): a host with a health check gets `GET ` with the upstream +/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as +/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpstreamProbe { + pub ok: bool, + pub kind: Option<&'static str>, + pub status: Option, + pub latency_ms: Option, +} + +fn status_kind(status: u16) -> &'static str { + match status { + 300..=399 => "redirect", + 401 | 403 => "sign_in", + 404 => "not_found", + 500..=599 => "server_error", + _ => "bad_answer", + } +} + +fn io_kind(e: &std::io::Error) -> &'static str { + use std::io::ErrorKind as K; + match e.kind() { + K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => { + "refused" + } + K::TimedOut => "timeout", + _ if e.to_string().contains("lookup") => "name", + _ => "refused", + } +} + +/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`, +/// else the usual Debian/NixOS path), read once. +fn system_roots() -> Arc { + static ROOTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + ROOTS + .get_or_init(|| { + let mut store = rustls::RootCertStore::empty(); + let path = std::env::var("SSL_CERT_FILE") + .unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into()); + if let Ok(pem) = std::fs::read_to_string(path) { + for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() { + let _ = store.add(rustls_pki_types::CertificateDer::from(der)); + } + } + Arc::new(store) + }) + .clone() +} + +pub async fn probe_upstream( + u: &ianitor_core::Upstream, + path: &str, + host_header: &str, + watch_only: bool, +) -> UpstreamProbe { + use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + let started = Instant::now(); + let fail = |kind: &'static str| UpstreamProbe { + ok: false, + kind: Some(kind), + status: None, + latency_ms: None, + }; + async fn ask( + mut s: S, + req: &[u8], + ) -> Result, std::io::Error> { + s.write_all(req).await?; + let mut head = [0u8; 64]; + let mut n = 0; + while n < 13 { + let k = s.read(&mut head[n..]).await?; + if k == 0 { + break; + } + n += k; + } + Ok(String::from_utf8_lossy(&head[..n]) + .split(' ') + .nth(1) + .and_then(|x| x.parse::().ok())) + } + let req = format!( + "GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n" + ); + let run = async { + let tcp = match tokio::net::TcpStream::connect(u.authority()).await { + Ok(t) => t, + Err(e) => return Err(io_kind(&e)), + }; + if u.scheme == ianitor_core::Scheme::Https { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let Ok(b) = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + else { + return Err("tls"); + }; + let cfg = b + .with_root_certificates(system_roots()) + .with_no_client_auth(); + let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else { + return Err("name"); + }; + let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg)) + .connect(name, tcp) + .await + { + Ok(t) => t, + Err(_) => return Err("tls"), + }; + ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e)) + } else { + ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e)) + } + }; + match tokio::time::timeout(Duration::from_secs(5), run).await { + Err(_) => fail("timeout"), + Ok(Err(kind)) => fail(kind), + Ok(Ok(None)) => fail("bad_answer"), + Ok(Ok(Some(status))) => { + let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let ok = if watch_only { + (100..500).contains(&status) + } else { + (200..300).contains(&status) + }; + UpstreamProbe { + ok, + kind: (!ok).then(|| status_kind(status)), + status: Some(status), + latency_ms: Some(latency), + } + } + } +} diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index a35e23a..ac2736e 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)] @@ -100,6 +110,12 @@ pub struct Compile { pub access_log: String, pub caddy_credentials_dir: String, pub caddy_admin: Option, + /// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves. + #[serde(default)] + pub caddy_admin_socket: Option, + /// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy). + #[serde(default)] + pub trusted_proxies: Vec, } impl Compile { @@ -112,6 +128,8 @@ impl Compile { access_log: self.access_log.clone(), caddy_credentials_dir: self.caddy_credentials_dir.clone(), caddy_admin: self.caddy_admin, + caddy_admin_socket: self.caddy_admin_socket.clone(), + trusted_proxies: self.trusted_proxies.clone(), } } } @@ -213,6 +231,15 @@ impl Config { "routes.push_credential must be a plain credential name".into(), )); } + // The keys at rest are only as strong as this; only test builds may lower it. + if let Some(p) = &self.pki + && p.kdf_iterations < MIN_KDF_ITERATIONS + && !cfg!(feature = "test-hooks") + { + return Err(ConfigError::Invalid(format!( + "pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}" + ))); + } if let Some(m) = empty_model() { for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) { ianitor_core::compile::edge(&m, &c.options()) @@ -280,3 +307,79 @@ fn empty_model() -> Option { ) .ok() } + +/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256). +pub const MIN_KDF_ITERATIONS: u32 = 600_000; + +#[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, + /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". + #[serde(default)] + pub logout_url: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[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/crash.rs b/crates/control/src/crash.rs index b85bbe4..22870d7 100644 --- a/crates/control/src/crash.rs +++ b/crates/control/src/crash.rs @@ -3,11 +3,17 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! 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. +//! environment, control exits at once with status 134 (no cleanup in Ianitor's code, like a +//! kill -9) when an apply reaches that stage. It does not raise SIGABRT: a signal would make +//! the kernel log a register dump per crash test and could hand the process to the host's +//! core-dump handler, and the tests must not reach into the host's systemd. //! //! `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,14 +28,23 @@ 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"); - std::process::abort(); + log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: exiting on purpose"); + std::process::exit(134); } } +#[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 +57,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(()) +} diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 70930e6..2b59ad6 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -18,42 +18,17 @@ 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 +100,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())?; @@ -172,8 +148,28 @@ pub async fn run(args: &[String]) -> Result<(), String> { access_log: s("logs/access.log"), caddy_credentials_dir: s("creds"), caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: Vec::new(), }, compile_caddy: None, + pki: Some(ianitor_control::config::PkiConfig { + root_cert: dir.join("offline-root/domi-root.crt"), + password_credential: "pki-password".into(), + approval: "manual".into(), + // Fast in test builds; the real floor in a release build. + kdf_iterations: if cfg!(feature = "test-hooks") { + 10_000 + } else { + ianitor_control::config::MIN_KDF_ITERATIONS + }, + }), + ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig { + hostname: None, + proof_credential: None, + static_dir: Some(PathBuf::from(d)), + logout_url: None, + }), + engine: None, }; cfg.check().map_err(|e| e.to_string())?; Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) @@ -183,6 +179,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)?); @@ -192,16 +203,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); 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..e49bf61 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -15,6 +15,8 @@ // A refusal is built once per failed request or apply; boxing it buys nothing. #![allow(clippy::result_large_err)] +mod caddy_apply; + use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -141,6 +143,14 @@ pub struct Control { pub tokens: Tokens, pub shares: Shares, 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]`. + pub units: Option>, records: Mutex>, queue: Mutex>, wake: Notify, @@ -151,7 +161,14 @@ 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<()>, + /// Held while an engine is switched or told to reload its device or certificate files. + pub(crate) engine_lock: tokio::sync::Mutex<()>, + /// Serialises reading the device records and writing the device files (never held + /// across an apply or a switch). + pub(crate) devices_lock: tokio::sync::Mutex<()>, + /// Why the device files are not (yet) in force, until a retry succeeds. + pub devices_problem: Mutex>, } const MAX_RECORDS: usize = 1000; @@ -207,6 +224,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 +249,25 @@ 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 + .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(), @@ -226,8 +277,16 @@ impl Control { paused: Mutex::new(paused), pause_saved: std::sync::atomic::AtomicBool::new(true), apply_lock: tokio::sync::Mutex::new(()), + engine_lock: tokio::sync::Mutex::new(()), + devices_lock: tokio::sync::Mutex::new(()), + devices_problem: Mutex::new(None), 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) } @@ -619,6 +678,31 @@ impl Control { errors: fe, } })?; + // The UI proof belongs to the [ui] host only (core already demands forward-auth for it). + let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref()); + for h in model.hosts() { + let proof = h.request_headers.iter().any(|r| { + matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET) + }); + if proof && ui_host != Some(h.hostname.as_str()) { + let p = messages::params([("hostname", h.hostname.to_string())]); + let fe = FieldError { + code: "host.header.proof_host".into(), + message: message("host.header.proof_host", &p), + field: Some("request_headers".into()), + params: p.clone(), + detail: None, + }; + return Err(Fail { + status: 422, + reason: reason( + "apply.failed.validation", + messages::params([("first_error", fe.message.clone())]), + ), + errors: vec![fe], + }); + } + } Ok(Plan { kind, verb: host_verb(kind), @@ -863,6 +947,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"); @@ -969,6 +1058,13 @@ impl Control { r.step("reload", "running"); }); + // Caddy serves: load the trial into Caddy and watch through it (Mark, 2026-11-08). + if self.engine_running() == "caddy" { + return self + .run_under_caddy(&id, j, &plan, &caddy_text, &job.change) + .await; + } + // Which hosts to judge: those this change adds or changes, not those it removes. let watch_hosts: Vec = plan .hosts @@ -1411,7 +1507,8 @@ impl Control { /// The idempotent part of a revert. Returns the revert commit, if one was needed. async fn finish_revert(&self, j: &Journal) -> Result, String> { - if self.edge.attached() { + let caddy = self.engine_running() == "caddy"; + if self.edge.attached() && !caddy { match self.edge.abort().await { Ok(_) => {} // Edge down: it starts from edge.json, which is still the last good config. @@ -1447,6 +1544,15 @@ impl Control { for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] { remove_if_exists(&p).map_err(|e| e.to_string())?; } + if caddy { + // Caddy must run caddy.json again, the last good config (with the device files as + // they are now); then no trial is out any more. Under the engine lock, so a device + // change that saw the trial and left the reload to this point is not lost. + let _engine = self.engine_lock.lock().await; + self.caddy_reload().await?; + crate::caddy_guard::disarm(&self.cfg.state_dir); + return Ok(rev); + } // Edge must now run edge.json, the last good config. If it confirmed the trial after // all (an answer lost on the way) it does not: reload it. If edge cannot be asked, // this is not a finished revert (a restart asks again). @@ -1605,6 +1711,16 @@ impl Control { self.unpause(); self.sync_files().await; } + if self.engine_running() == "caddy" { + match self.caddy_reload().await { + Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir), + Err(e) => { + log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}") + } + } + } else { + crate::caddy_guard::disarm(&self.cfg.state_dir); + } if let Err(e) = self.shares.ensure_revocation_file() { log::error!(target: "ianitor::share", "{e}"); } diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs new file mode 100644 index 0000000..9b61bee --- /dev/null +++ b/crates/control/src/engine/caddy_apply.rs @@ -0,0 +1,466 @@ +// 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/. + +//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same +//! pipeline and journal as with edge; only the trial, the watch and the revert differ: +//! +//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed +//! (crate::caddy_guard: a crashed or hung control cannot leave it serving); +//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams +//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers +//! at all (any status counts, also its auth redirect, 401, 403 or 421); +//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it); +//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline, +//! then promotes, loads caddy.json and checks that Caddy runs it. + +use std::net::SocketAddr; + +use super::*; +use crate::caddy_guard; +use crate::caddy_link::{self, Probe}; + +/// Where control reaches Caddy's HTTPS listener (its own machine). +fn local(addr: SocketAddr) -> SocketAddr { + if addr.ip().is_unspecified() { + let ip: std::net::IpAddr = if addr.is_ipv6() { + std::net::Ipv6Addr::LOCALHOST.into() + } else { + std::net::Ipv4Addr::LOCALHOST.into() + }; + SocketAddr::new(ip, addr.port()) + } else { + addr + } +} + +/// How one host is probed (edge's rules, crates/edge/src/health.rs). +struct Rule { + upstreams: Vec, + path: String, + has_check: bool, +} + +impl Control { + /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). + pub fn caddy_socket(&self) -> Option { + self.cfg + .caddy_compile() + .caddy_admin_socket + .as_ref() + .map(std::path::PathBuf::from) + } + + /// Load caddy.json (the last good config) into the running Caddy, even when it is the + /// config Caddy already runs (so it reads its files again), and check that it runs it. + pub async fn caddy_reload(&self) -> Result<(), String> { + let sock = self + .caddy_socket() + .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; + let text = std::fs::read(&self.cfg.caddy.config) + .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; + caddy_link::load(&sock, &text).await?; + if !caddy_link::runs(&sock, &text).await? { + return Err("Caddy took the config but does not run it".into()); + } + Ok(()) + } + + /// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve + /// the certificate that is on disk now for a Domi host (it proves the files were read). + pub async fn caddy_reload_checked(&self) -> Result<(), String> { + self.caddy_reload().await?; + let Ok((_, _, model)) = self.head_model() else { + return Ok(()); + }; + let Some(h) = model + .hosts() + .iter() + .find(|h| h.tls == ianitor_core::TlsMode::Domi) + else { + return Ok(()); + }; + let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir) + .join(format!("{}.crt", h.hostname)); + let want = std::fs::read_to_string(&file) + .ok() + .and_then(|pem| ianitor_core::pki::chain_der(&pem).ok()) + .and_then(|c| c.into_iter().next()) + .map(|der| crate::util::sha256_hex(&der)) + .ok_or_else(|| format!("cannot read {}", file.display()))?; + let addr = local(self.cfg.caddy_compile().https_listen); + let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?; + if got != want { + return Err(format!( + "Caddy still serves an older certificate for {} after the reload", + h.hostname + )); + } + Ok(()) + } + + fn caddy_rules(&self, plan: &Plan) -> BTreeMap { + plan.model + .hosts() + .iter() + .map(|h| { + ( + h.hostname.to_string(), + Rule { + upstreams: h.upstreams.clone(), + path: h + .health_check + .as_ref() + .map_or("/".to_owned(), |c| c.path.clone()), + has_check: h.health_check.is_some(), + }, + ) + }) + .collect() + } + + /// One round of edge-style upstream probes for one host; `(address, probe)` per upstream. + async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> { + let mut out = Vec::new(); + for u in &r.upstreams { + let host_header = if r.has_check { + u.authority() + } else { + hostname.to_owned() + }; + let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await; + out.push((u.authority(), p)); + } + out + } + + pub(super) async fn run_under_caddy( + &self, + id: &str, + mut j: Journal, + plan: &Plan, + caddy_text: &str, + change: &Change, + ) { + let fail = |code: &str, detail: String| { + let mut r = reason(code, messages::params([("engine", "Caddy".into())])); + r.detail = Some(detail); + r + }; + let Some(sock) = self.caddy_socket() else { + let r = fail( + "apply.failed.reload", + "no caddy_admin_socket is configured".into(), + ); + return self.revert(id, &j, r, "failed").await; + }; + let watch_hosts: Vec = plan + .hosts + .iter() + .filter(|h| plan.target.host(h).is_some()) + .cloned() + .collect(); + let addr = local(self.cfg.caddy_compile().https_listen); + let rules = self.caddy_rules(plan); + // A host whose upstreams already failed before the change is no reason to revert + // (edge: `down_hosts`). Judged by the upstreams, as edge does. + let existed: BTreeSet = self + .repo + .tree(&j.base) + .map(|t| { + watch_hosts + .iter() + .filter(|h| t.host(h).is_some()) + .cloned() + .collect() + }) + .unwrap_or_default(); + let mut was_down = BTreeSet::new(); + for h in &existed { + if let Some(r) = rules.get(h) + && !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok) + { + was_down.insert(h.clone()); + } + } + + let window = self.cfg.watch_secs; + // The deadline goes out before the trial does (crate::caddy_guard). + let deadline = now() + window + self.cfg.trial_margin_secs + 5; + // Under the engine lock: a device change that looked a moment ago saw no trial and + // reloads caddy.json; it must not land after the trial is in. + let loaded = { + let _engine = self.engine_lock.lock().await; + match caddy_guard::arm(&self.cfg.state_dir, id, deadline) { + Err(e) => { + let mut r = reason("internal", Params::new()); + r.detail = Some(e); + Err((r, "failed")) + } + Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes()) + .await + .map_err(|e| (fail("apply.failed.reload", e), "failed")), + } + }; + if let Err((r, state)) = loaded { + return self.revert(id, &j, r, state).await; + } + j.stage = "trial_loaded".into(); + if let Err(e) = self.journal(&j) { + let mut r = reason("internal", Params::new()); + r.detail = Some(e); + return self.revert(id, &j, r, "failed").await; + } + crash::point("trial_loaded"); + self.update(id, |r| r.step("reload", "done")); + + let judged: Vec = watch_hosts + .iter() + .filter(|h| !was_down.contains(*h)) + .cloned() + .collect(); + let mut kept_reason = if watch_hosts.is_empty() { + reason( + "apply.kept.removed", + messages::params([("hostname", plan.hosts.join(", "))]), + ) + } else { + reason( + "apply.kept", + messages::params([ + ("hostname", watch_hosts.join(", ")), + ("seconds", window.to_string()), + ]), + ) + }; + let ends = now() + window; + if judged.is_empty() { + self.update(id, |r| r.step("watch", "skipped")); + } else { + self.update(id, |r| { + r.state = "watching".into(); + r.step("watch", "running"); + r.watch = Some(Watch { + ends, + hosts: judged + .iter() + .map(|h| WatchHost { + hostname: h.clone(), + ..Default::default() + }) + .collect(), + }); + }); + } + if let Err(r) = self + .caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends) + .await + { + return self.revert(id, &j, r, "reverted").await; + } + if !judged.is_empty() { + let no_check: Vec = judged + .iter() + .filter(|h| rules.get(*h).is_some_and(|r| !r.has_check)) + .cloned() + .collect(); + if !no_check.is_empty() && no_check.len() == judged.len() { + kept_reason = reason( + "apply.kept.no_watch", + messages::params([("hostname", no_check.join(", "))]), + ); + } + self.update(id, |r| r.step("watch", "done")); + } + crash::point("watched"); + // Confirmed first, then the deadline is claimed (fix round 3): a crash in between + // leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert + // leave the trial alone and recovery promotes it. The other order would leave a window + // with nothing armed and nothing confirmed, where nobody reverts Caddy. + j.stage = "confirmed".into(); + if let Err(e) = self.journal(&j) { + let mut r = reason("internal", Params::new()); + r.detail = Some(e); + return self.revert(id, &j, r, "failed").await; + } + crash::point("confirmed"); + // From the claim to Caddy running the promoted caddy.json, no device reload may load + // the old caddy.json in between. + let engine = self.engine_lock.lock().await; + // The guard may have reverted a trial that ran past its deadline (a stalled control): + // then this change is not kept. + if !caddy_guard::claim(&self.cfg.state_dir) { + drop(engine); + let mut r = reason("apply.interrupted", Params::new()); + r.detail = Some( + "the trial ran past its deadline, so Caddy went back to the last good config" + .into(), + ); + return self.revert(id, &j, r, "reverted").await; + } + if let Err(e) = self.promote() { + drop(engine); + log::error!(target: "ianitor::apply", "cannot write the config files: {e}"); + let mut p = reason("control.files_unwritten", Params::new()); + p.detail = Some(e.to_string()); + p.params.insert("apply_id".into(), id.to_owned()); + if let Err(pe) = self.pause(p) { + log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it"); + } + let push_step = self.push_step(); + self.update(id, |r| r.step("push", push_step)); + self.finish(id, "kept", Some(kept_reason), Vec::new()); + return; + } + crash::point("promoted"); + // caddy.json now holds the change: Caddy loads what was written (with the device and + // certificate files as they are now) and must run it. + if let Err(e) = self.caddy_reload().await { + log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}"); + } + drop(engine); + let push_step = self.push_step(); + self.update(id, |r| r.step("push", push_step)); + self.finish(id, "kept", Some(kept_reason), Vec::new()); + self.clear_journal(); + if self.paused().is_some() && matches!(change, Change::Restore { .. }) { + self.unpause(); + } + self.push_wake.notify_one(); + } + + /// The watch under Caddy until `ends`: the reason to revert, if any. + #[allow(clippy::too_many_arguments)] + async fn caddy_watch( + &self, + id: &str, + sock: &std::path::Path, + trial: &str, + judged: &[String], + rules: &BTreeMap, + plan: &Plan, + addr: SocketAddr, + ends: u64, + ) -> Result<(), Reason> { + let mut seen: HashMap<(String, String), BTreeMap> = HashMap::new(); + let mut seq = 0u64; + let mut silent: BTreeMap = BTreeMap::new(); + let paths: HashMap = rules + .iter() + .map(|(h, r)| (h.clone(), r.path.clone())) + .collect(); + let mut first = true; + loop { + // Anyone else's reload (a device change, a restart of caddy-fallback) drops the + // trial: then this is not a verdict on the change. + match caddy_link::runs(sock, trial.as_bytes()).await { + Ok(true) => {} + Ok(false) => { + let mut r = reason("apply.reverted.edge_lost", Params::new()); + r.detail = Some("Caddy no longer runs the trial config".into()); + return Err(r); + } + Err(e) => { + let mut r = reason("apply.reverted.edge_lost", Params::new()); + r.detail = Some(e); + return Err(r); + } + } + if first { + crash::point("watching"); + first = false; + } + let mut counts = Vec::new(); + for h in judged { + let Some(rule) = rules.get(h) else { continue }; + // Does Caddy answer for this host at all? Any status does. + match caddy_link::probe(addr, h, "/").await { + Probe::Status(_) => { + silent.remove(h); + } + Probe::NoAnswer(e) => { + let s = silent.entry(h.clone()).or_insert((0, String::new())); + s.0 += 1; + s.1 = e; + } + } + if let Some((n, e)) = silent.get(h) + && *n >= 3 + { + let mut r = reason( + "apply.reverted.no_answer", + messages::params([ + ("hostname", h.clone()), + ("verb", plan.verb.into()), + ("seconds", self.cfg.watch_secs.to_string()), + ]), + ); + r.hostname = Some(h.clone()); + r.detail = Some(format!("Caddy does not answer for {h}: {e}")); + return Err(r); + } + for (address, p) in Self::probe_host(h, rule).await { + seq += 1; + seen.entry((h.clone(), address)).or_default().insert( + seq, + Check { + seq, + at: now(), + ok: p.ok, + source: if rule.has_check { + "health_check".into() + } else { + "watch".into() + }, + kind: p.kind.map(str::to_owned), + status: p.status, + latency_ms: p.latency_ms, + }, + ); + } + let mut passed = 0u32; + let mut failed = 0u32; + let mut all_failing = !rule.upstreams.is_empty(); + for ((host, _), m) in &seen { + if host != h { + continue; + } + passed += m.values().filter(|c| c.ok).count() as u32; + failed += m.values().filter(|c| !c.ok).count() as u32; + if m.values().rev().take_while(|c| !c.ok).count() < 3 { + all_failing = false; + } + } + counts.push(WatchHost { + hostname: h.clone(), + passed, + failed, + total: passed + failed, + }); + if all_failing { + return Err(self.revert_reason(h, plan, &seen, &paths)); + } + } + self.update(id, |r| { + if let Some(w) = &mut r.watch { + w.hosts = counts; + } + }); + if now() >= ends { + break; + } + tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await; + } + // At the end, as with edge: every judged host needs an upstream whose last probe passed. + for h in judged { + let last_ok = seen + .iter() + .filter(|((host, _), _)| host == h) + .any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok)); + if !last_ok { + return Err(self.revert_reason(h, plan, &seen, &paths)); + } + } + Ok(()) + } +} 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 683a167..65d3279 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -7,6 +7,8 @@ //! edge keeps serving the last good config. pub mod api; +pub mod caddy_guard; +pub mod caddy_link; pub mod config; pub mod crash; pub mod edgelink; @@ -14,9 +16,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; @@ -36,6 +41,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..a5fc768 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`), @@ -25,7 +30,8 @@ fn usage() -> ExitCode { eprintln!( "usage: ianitor-control --config | --dev [--edge-bin ] | \ token create --name [--expires-days | --never] (--config | --state-dir ) | \ - token list (...) | token revoke (...) | openapi | check --config " + token list (...) | token revoke (...) | openapi | check --config | \ + caddy-revert --config | caddy-guard --config " ); ExitCode::from(2) } @@ -197,6 +203,174 @@ 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)?; + let name = r.name.clone().unwrap_or_default(); + eprintln!("Handed to control; waiting for it ..."); + let state = ianitor_control::pki::cli_wait(&dir, &r.id, now) + .map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?; + eprintln!( + "{} the request for \"{name}\" ({}).", + if state == "approved" { "Approved" } else { "Turned down" }, + 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 {}; waiting for control to install it ...", r.id); + ianitor_control::pki::cli_wait(&dir, &r.id, now) + .map_err(|e| format!("not installed: {e}"))?; + eprintln!("Installed. Server certificates are reissued from it now."); + 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,11 +389,34 @@ 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(()) } Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), + // Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard. + Some(verb @ ("caddy-revert" | "caddy-guard")) => match args + .iter() + .position(|a| a == "--config") + .and_then(|i| args.get(i + 1)) + { + Some(p) => match Config::load(&PathBuf::from(p)) { + Ok(cfg) if verb == "caddy-guard" => { + rt.block_on(ianitor_control::caddy_guard::run(cfg)) + } + Ok(cfg) => rt + .block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg)) + .map(|done| { + if done { + eprintln!("Caddy is back on the last good config."); + } + }), + Err(e) => Err(e.to_string()), + }, + None => return usage(), + }, Some("--dev") => rt.block_on(dev::run(&args[1..])), Some("--config") => match args.get(1) { Some(p) => match Config::load(&PathBuf::from(p)) { diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index 945f222..fe01126 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -228,6 +228,131 @@ 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 computer and check that its fingerprint matches (Sign by hand shows both), 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." + } + "host.header.proof" => { + "Only a host behind sign-in can send the ui-proof secret. Choose Sign in first, or remove the rule." + } + "host.header.proof_host" => { + "Only the web UI's admin host can send the ui-proof secret, and {hostname} is not it ([ui] hostname in control.toml)." + } + "pki.manual.not_ca" => { + "This certificate cannot sign other certificates. Sign it again with the signing settings file (.ext)." + } + "pki.manual.eku" => { + "This certificate is limited to some uses, so it could not issue both host and device certificates. Sign it again with the signing settings file (.ext)." + } + "pki.manual.dates" => { + "This certificate is not valid yet, has already expired, or lasts longer than the Domi root. Check the offline computer's clock and use -days 365." + } + "pki.devices_unwritten" => { + "The device list could not be saved or handed to the proxy, so the change is not in force yet. Ianitor keeps trying; try again in a moment." + } + "engine.not_ready" => { + "Caddy is not ready: its settings could not be built from the current routes." + } + // The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12). + "repo.duplicate_file" => { + "Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up." + } + "file.syntax" => { + "{file} in the routes repository has a typing mistake. Changes are paused until it is fixed." + } + "file.too_large" => { + "{file} in the routes repository is too large to read. Changes are paused until it is fixed." + } + "site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".", + "site.forward_auth" => { + "The sign-in settings in ianitor.toml cannot be used. Show details to see why." + } + "site.forward_auth.header" => { + "ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name." + } + "site.secret.name" => { + "\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores." + } + "site.acme" => { + "The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why." + } + "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..1586e3d --- /dev/null +++ b/crates/control/src/pki.rs @@ -0,0 +1,1255 @@ +// 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, or why the last approval or install for it was not used (plain + /// English, no secrets). A request that is still waiting can carry one. + #[serde(default)] + pub error: Option, + /// When `error` was last set for a request that is still waiting (the CLI waits for it). + #[serde(default)] + pub problem_at: 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) +} + +/// Private keys in `dir` that are not control's own: control refuses to run with one in its +/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any +/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys +/// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those +/// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link +/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`, +/// compressed history) is not read. +pub fn root_key_files(dir: &Path) -> Vec { + let allowed = |p: &Path| -> bool { + let Ok(rel) = p.strip_prefix(dir) else { + return false; + }; + let parts: Vec = rel + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + match parts + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + ["pki", "intermediate.key"] => true, + ["pki", f] => f.starts_with("pending-") && f.ends_with(".key"), + ["pki", "devices", f] => f.ends_with(".key"), + _ => false, + } + }; + let own_armour = |b: &[u8]| -> bool { + let t = String::from_utf8_lossy(b); + let begins = t.matches("-----BEGIN ").count(); + let ours = t.matches(OWN_BEGIN).count(); + begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2 + }; + 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(); + // symlink_metadata: a link is looked at, not followed. + let Ok(meta) = std::fs::symlink_metadata(&p) else { + continue; + }; + if meta.file_type().is_symlink() { + found.push(p); + continue; + } + if meta.is_dir() { + let git_objects = + e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git"); + if depth < 8 && !git_objects { + stack.push((p, depth + 1)); + } + continue; + } + if !meta.is_file() { + continue; + } + let read = || { + (meta.len() <= 1 << 20) + .then(|| std::fs::read(&p).ok()) + .flatten() + }; + if allowed(&p) { + // Control's own key files: one key, in control's encrypted armour. + if !read().is_some_and(|b| own_armour(&b)) { + found.push(p); + } + continue; + } + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + let by_name = name.contains("root") && name.contains("key"); + let by_content = + read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes())); + if by_name || by_content { + found.push(p); + } + } + } + found +} + +// Split so that this file does not match the pre-commit hook itself. +const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----"); +const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); + +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; + std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)) + .map_err(|e| format!("cannot make {} private: {e}", d.display()))?; + } + } + 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. + pub 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, + problem_at: 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"))?; + // Everything a hand-signed certificate can get wrong, before anything is reissued from it. + if let Some(problem) = pki::intermediate_problem(&first, &self.root_pem, now as i64) { + return Err(PkiFail::Code(match problem { + "not_root" => "pki.not_our_root", + "not_ca" => "pki.manual.not_ca", + "eku" => "pki.manual.eku", + "dates" => "pki.manual.dates", + _ => "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.error = None; + r.problem_at = None; + 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 mut allow: String = self + .devices()? + .iter() + .filter(|d| d.state(now) == "valid") + .map(|d| d.cert_pem.as_str()) + .collect(); + if allow.is_empty() { + // Caddy refuses an empty leaf list (and the whole config with it): the list + // holds a certificate no one has the key to. Made once, so the file stays put. + let p = self.dir.join("no-device.crt"); + allow = match std::fs::read_to_string(&p) { + Ok(pem) if pki::inspect(&pem).is_ok_and(|i| i.subject_cn == pki::NO_DEVICE_CN) => { + pem + } + _ => { + let pem = pki::no_device_placeholder(now as i64).map_err(|e| { + PkiFail::Internal(format!("cannot make the placeholder: {e}")) + })?; + write_atomic(&p, pem.as_bytes(), 0o644).map_err(io)?; + pem + } + }; + } + 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, + problem_at: 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}"); + self.note_problem(&rid, &e, now); + } 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}"); + self.note_problem(&rid, &e, now); + } + } + } + _ => { + 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) + } + + /// An approval or install for a waiting request was not used: say why on the request + /// (the UI and the CLI show it), and keep it open for another try. + fn note_problem(&self, rid: &str, e: &PkiFail, now: u64) { + let text = match e { + PkiFail::Code(c) => crate::messages::message(c, &crate::messages::Params::new()), + PkiFail::Internal(_) => { + crate::messages::message("internal", &crate::messages::Params::new()) + } + }; + let Ok(_g) = self.guard() else { return }; + let Ok(mut rs) = self.requests() else { return }; + if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") { + r.error = Some(text); + r.problem_at = Some(now); + if let Err(e) = self.save_requests(&rs) { + log::error!(target: "ianitor::pki", "cannot record the problem on {rid}: {e}"); + } + } + } + + 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.error = None; + r.problem_at = None; + 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. + /// Whether a one-time link is still unused and in time (the device name, for its page), + /// without using it up. + pub fn peek_bundle(&self, token: &str, now: u64) -> Option { + let device_id = { + let m = self.bundles.lock().ok()?; + let b = m.get(token)?; + if b.expires_at <= now { + return None; + } + b.device_id.clone() + }; + self.devices() + .ok()? + .into_iter() + .find(|d| d.id == device_id && d.state(now) == "valid") + .map(|d| d.name) + } + + 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") +} + +/// After `pki approve` or `pki install`: wait (up to 20 s) for control to act on it. `Ok` with +/// the request's new state, or `Err` with why it was not used. +pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result { + let path = requests_path(state_dir); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + let rs: Vec = read_json(&path)?.unwrap_or_default(); + match rs.iter().find(|r| r.id == rid) { + None => return Err("the request is gone (it may have expired)".into()), + Some(r) if r.state != "waiting" => { + return match (&r.error, r.state.as_str()) { + (Some(e), s) if s != "approved" => Err(e.clone()), + _ => Ok(r.state.clone()), + }; + } + Some(r) if r.problem_at.is_some_and(|t| t >= since) => { + return Err(r.error.clone().unwrap_or_else(|| "it was not used".into())); + } + Some(_) => {} + } + if std::time::Instant::now() >= deadline { + return Err( + "control has not acted on it within 20 s; is ianitor-control running? It still will when it starts" + .into(), + ); + } + std::thread::sleep(std::time::Duration::from_millis(250)); + } +} + +#[cfg(test)] +mod root_key_tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn allowed_paths_hold_only_our_armour_links_are_reported_and_git_objects_are_not_read() { + let dir = std::env::temp_dir().join(format!("ianitor-rk-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("pki/devices")).unwrap(); + std::fs::create_dir_all(dir.join("routes.git/objects/ab")).unwrap(); + let key = pki::generate_key().unwrap(); + let sealed = pki::encrypt_key_with(&key, b"pw", 1000).unwrap(); + let plain = key.serialize_pem(); + std::fs::write(dir.join("pki/intermediate.key"), &sealed).unwrap(); + std::fs::write(dir.join("pki/devices/d1.key"), &sealed).unwrap(); + // Git's store is not read (a blob could hold anything, compressed or not). + std::fs::write(dir.join("routes.git/objects/ab/cdef"), &plain).unwrap(); + assert!( + root_key_files(&dir).is_empty(), + "{:?}", + root_key_files(&dir) + ); + // A plain key, or a second block, in an allowed place is not ours. + std::fs::write(dir.join("pki/pending-x.key"), &plain).unwrap(); + std::fs::write(dir.join("pki/devices/d2.key"), format!("{sealed}{plain}")).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink("/nonexistent/domi-root.key", dir.join("pki/devices/d3.key")) + .unwrap(); + let found = root_key_files(&dir); + assert!(found.contains(&dir.join("pki/pending-x.key")), "{found:?}"); + assert!(found.contains(&dir.join("pki/devices/d2.key")), "{found:?}"); + #[cfg(unix)] + assert!(found.contains(&dir.join("pki/devices/d3.key")), "{found:?}"); + assert!( + !found.contains(&dir.join("pki/intermediate.key")), + "{found:?}" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/control/src/pki_ctl.rs b/crates/control/src/pki_ctl.rs new file mode 100644 index 0000000..7a104f7 --- /dev/null +++ b/crates/control/src/pki_ctl.rs @@ -0,0 +1,270 @@ +// 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" + | "pki.manual.not_ca" + | "pki.manual.eku" + | "pki.manual.dates" => 422, + "pki.devices_unwritten" => 503, + "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 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; + } + // Always: the files are tiny, and a list that failed to be written catches up here. + 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(); + // At start: bring the device files in line (a revocation that could not be written + // before a restart is in force now). + let _ = self.devices_changed().await; + 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; + } + let retry = self + .devices_problem + .lock() + .map(|p| p.is_some()) + .unwrap_or(false); + if changes.devices || retry { + let _ = 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. + /// + /// It never waits for an apply (fix round 3): the files go to disk at once and edge is told + /// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves + /// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now + /// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote, + /// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch + /// (engine lock busy for more than a second) the engine being started reads them anyway. + pub async fn devices_changed(&self) -> Result<(), String> { + let Some(p) = &self.pki else { return Ok(()) }; + let _files = self.devices_lock.lock().await; + let t = now(); + let mut result = Ok(()); + for dir in self.cert_dirs() { + if let Err(e) = p.write_device_files(dir, t) { + result = Err(format!( + "the device files in {} could not be written: {e}", + dir.display() + )); + } + } + // The engine lock is held for long only by a switch; an apply holds it for a moment + // (loading a trial, or from the claim to the promoted reload), so then this waits. + let engine = + match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await { + Ok(g) => Some(g), + Err(_) if self.engine_state().state == "switching" => None, + Err(_) => Some(self.engine_lock.lock().await), + }; + // Tell the serving engine every time, changed or not: a repeated Revoke nudges again. + // During a switch it is not told now, and never silently (QC round 4): the problem + // stays set, so the retry tells whichever engine serves once the switch is over (the + // switch itself also ends by telling it). + let mut pending = None; + if result.is_ok() { + if engine.is_none() { + pending = Some( + "an engine switch is under way; the engine that serves after it is told then" + .to_owned(), + ); + } else { + result = self.nudge_devices().await; + } + } + if let Ok(mut pr) = self.devices_problem.lock() { + *pr = result.as_ref().err().cloned().or(pending.clone()); + } + if let Some(p) = &pending { + log::info!(target: "ianitor::pki", "{p}"); + } + if let Err(e) = &result { + log::error!(target: "ianitor::pki", "{e}; retrying"); + } + result + } + + /// Tell the engine that serves to read the device files again. The caller holds the engine + /// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the + /// guard and caddy-revert all load caddy.json, which reads the files). + pub(crate) async fn nudge_devices(&self) -> Result<(), String> { + let caddy = self.engine_running() == "caddy"; + if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() { + log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends"); + Ok(()) + } else if caddy { + self.caddy_reload_checked() + .await + .map_err(|e| format!("Caddy did not reload the device list: {e}")) + } else if self.edge.attached() { + self.edge + .reload_devices() + .await + .map_err(|e| format!("edge did not re-read the device list: {e}")) + } else { + Ok(()) + } + } + + async fn reload_serving_engine(&self) { + let _engine = self.engine_lock.lock().await; + if self.engine_running() == "caddy" { + if let Err(e) = self.caddy_reload_checked().await { + log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {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..90ad0a6 --- /dev/null +++ b/crates/control/src/switch.rs @@ -0,0 +1,412 @@ +// 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, +//! and stop 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 keep working (Mark, 2026-11-08): an apply is loaded into Caddy +//! through its admin socket, watched through Caddy and kept or reverted (`engine/caddy_apply`). +//! - 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 reload Caddy's config through its admin socket. +//! +//! 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}; +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 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 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 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); + } + } + + /// 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 == "caddy" && !self.fallback_buildable() { + return Err(Fail::new(409, "engine.not_ready", 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 _engine = self.engine_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); + }); + } + } + // Still under the engine lock: whichever engine serves now reads the device files again + // (QC round 4). A device change during the switch only wrote them; a Caddy that was + // already running, or started before they changed, would keep the old list. + if self.pki.is_some() + && let Err(e) = self.nudge_devices().await + { + log::error!(target: "ianitor::engine", "after the switch: {e}; retrying"); + if let Ok(mut p) = self.devices_problem.lock() { + *p = Some(e); + } + } + } + + 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?; + // Edge reads edge.json when it starts; tell it again in case it kept running (changes + // kept under Caddy are in edge.json). + if target == "pingora" + && self.edge.attached() + && let Err(e) = self.edge.reload().await + { + log::warn!(target: "ianitor::engine", "edge did not reload edge.json after the switch: {e}"); + } + Ok(()) + } + + 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(()) + } + + /// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.) + pub fn fallback_buildable(&self) -> bool { + self.head_model().ok().is_some_and(|(_, _, m)| { + ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_ok() + }) + } + + /// Any reason changes wait now: Caddy serving, or a pause. + pub fn effective_pause(&self) -> Option { + self.paused() + } +} + +/// 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/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/common/mod.rs b/crates/control/tests/common/mod.rs index 7e5d1a9..041db6f 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(), } } } @@ -111,6 +114,8 @@ impl Env { access_log: dir.str("logs/access.log"), caddy_credentials_dir: dir.str("creds"), caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: Vec::new(), }; // Edge starts from an empty config; control brings it in line on its first start. let empty = load( @@ -202,7 +207,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 +259,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/engine_switch.rs b/crates/control/tests/engine_switch.rs new file mode 100644 index 0000000..42ddf4a --- /dev/null +++ b/crates/control/tests/engine_switch.rs @@ -0,0 +1,1234 @@ +// 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; + // On a loaded machine a switch takes longer: stay under the API's 120 calls a + // minute rather than fail on a 429. + if r.status == 429 { + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + } + 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(300)).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 go on (changes_apply_while_caddy_serves), share links wait. + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text); + assert!(ov.json["paused"].is_null(), "{}", ov.text); + assert_eq!(ov.json["site"]["share_links_available"], false); + 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); + } + + /// The fake systemctl that really runs Caddy for caddy-fallback.service (edge runs in this + /// process and keeps its own ports; Caddy gets others through [compile_caddy]). + fn fake_with_caddy(dir: &std::path::Path, caddy: &std::path::Path) -> String { + format!( + r#"#!/bin/sh +dir="{d}/fake/units" +mkdir -p "$dir" +[ "$1" = "--no-ask-password" ] && shift +echo "$*" >> "{d}/fake/calls.log" +case "$1:$2" in + start:caddy-fallback.service) + # Like systemd: starting a unit that is active does nothing. + [ -e "$dir/$2" ] && exit 0 + XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \ + nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 & + echo $! > "{d}/fake/caddy.pid" + # The NixOS module starts ianitor-caddy-guard with caddy-fallback (crate::caddy_guard). + if [ ! -e "{d}/fake/no-guard" ]; then + IANITOR_LOG=info nohup "{g}" caddy-guard --config "{d}/control.toml" >> "{d}/logs/caddy-guard.log" 2>&1 & + echo $! > "{d}/fake/guard.pid" + fi + # fake/start-delay: Caddy serves at once, the unit reports active only later (a switch + # that is still in wait_serving while Caddy has read its files). + if [ -f "{d}/fake/start-delay" ]; then + (sleep "$(cat "{d}/fake/start-delay")"; touch "$dir/$2") >/dev/null 2>&1 & + else + touch "$dir/$2" + fi ;; + stop:caddy-fallback.service) + # fake/stop-delay and fake/fail-stop: a slow stop, and one that fails (Caddy keeps running). + [ -f "{d}/fake/stop-delay" ] && sleep "$(cat "{d}/fake/stop-delay")" + grep -qx "$2" "{d}/fake/fail-stop" 2>/dev/null && exit 1 + [ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null + [ -f "{d}/fake/guard.pid" ] && kill "$(cat "{d}/fake/guard.pid")" 2>/dev/null + rm -f "$dir/$2" "{d}/fake/caddy.pid" "{d}/fake/guard.pid" ;; + start:*) touch "$dir/$2" ;; + stop:*) rm -f "$dir/$2" ;; + is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; + *) exit 2 ;; +esac +"#, + d = dir.display(), + c = caddy.display(), + g = env!("CARGO_BIN_EXE_ianitor-control"), + ) + } + + struct CaddyEnv { + env: Env, + https: std::net::SocketAddr, + } + + impl Drop for CaddyEnv { + fn drop(&mut self) { + for f in ["fake/caddy.pid", "fake/guard.pid"] { + if let Ok(p) = std::fs::read_to_string(self.env.dir.join(f)) { + let _ = std::process::Command::new("kill").arg(p.trim()).status(); + } + } + } + } + + async fn env_with_caddy() -> Option { + let caddy = ianitor_testkit::proc::require_binary("caddy")?; + 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::create_dir_all(env.dir.join("caddy-state")).unwrap(); + std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap(); + let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let d = |p: &str| env.dir.join(p).display().to_string(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + "\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n", + d("engine"), + fake.display(), + d("certs"), + d("caddy-state"), + d("logs/caddy-access.log"), + d("creds"), + d("caddy/admin.sock"), + ); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + Some(CaddyEnv { env, https }) + } + + async fn visit(env: &Env, at: std::net::SocketAddr, host: &str) -> u16 { + match ianitor_testkit::client::https( + at, + host, + env.ca.roots(), + &ianitor_testkit::client::Req::get(host, "/"), + ) + .await + { + Ok(r) => r.status, + Err(_) => 0, + } + } + + /// Mark, 2026-11-08: changes keep working while Caddy serves. An apply is loaded into + /// Caddy, watched through it, and kept, or reverted by loading the previous caddy.json; + /// Undo works the same way; share links stay off. Switching back brings edge up to date. + #[tokio::test(flavor = "multi_thread")] + async fn changes_apply_while_caddy_serves() { + let Some(ce) = env_with_caddy().await else { + return; + }; + let env = &ce.env; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let host = |h: &str, up: String| json!({"host": {"hostname": h, "upstreams": [up], "tls": "domi", "auth": "none", "share_links": true}}); + assert_eq!( + env.apply("POST", "/api/v1/hosts", Some(host("a.test", echo.url()))) + .await["state"], + "kept" + ); + + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + wait_engine(env, "caddy").await; + assert_eq!( + visit(env, ce.https, "a.test").await, + 200, + "{}", + env.control_log() + ); + + // No pause while Caddy serves. + let ov = env.call("GET", "/api/v1/overview", None).await; + assert!(ov.json["paused"].is_null(), "{}", ov.text); + + // Kept through Caddy. + let rec = env + .apply("POST", "/api/v1/hosts", Some(host("b.test", echo.url()))) + .await; + assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); + assert_eq!(visit(env, ce.https, "b.test").await, 200); + + // A broken change is reverted by loading the previous caddy.json. + let broken = json!({"host": {"hostname": "c.test", "upstreams": [format!("http://127.0.0.1:{}", ianitor_testkit::upstream::closed_port())], + "tls": "domi", "auth": "none", "health_check": {"path": "/", "interval_secs": 1}}}); + let rec = env.apply("POST", "/api/v1/hosts", Some(broken)).await; + assert_eq!(rec["state"], "reverted", "{rec}\n{}", env.control_log()); + let caddy_json = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap(); + assert!(!caddy_json.contains("c.test")); + assert_eq!(visit(env, ce.https, "a.test").await, 200); + assert_eq!(visit(env, ce.https, "b.test").await, 200); + + // Undo (removes b.test) works under Caddy too. + let u = env.call("GET", "/api/v1/undo", None).await; + let target = u.json["target"]["change_id"].as_str().unwrap().to_owned(); + let rec = env + .apply( + "POST", + "/api/v1/undo", + Some(json!({"target_change_id": target})), + ) + .await; + assert_eq!(rec["state"], "kept", "{rec}"); + assert_ne!(visit(env, ce.https, "b.test").await, 200); + + // Share links stay off. + let s = env + .call( + "POST", + "/api/v1/hosts/a.test/share-links", + Some(json!({"path_prefix": "/", "expires_in_s": 86400})), + ) + .await; + assert_eq!(s.status, 409, "{}", s.text); + assert_eq!(s.json["error"]["code"], "share.engine_caddy"); + + // Back to Pingora: edge serves what was kept under Caddy. + 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; + let edge = env.edge.as_ref().unwrap(); + assert_eq!(visit(env, edge.https, "a.test").await, 200); + assert_ne!(visit(env, edge.https, "b.test").await, 200); + let edge_json = std::fs::read_to_string(env.dir.join("edge/edge.json")).unwrap(); + assert!( + edge_json.contains("a.test") + && !edge_json.contains("b.test") + && !edge_json.contains("c.test") + ); + } + + // ---------------------------------------------------------------- QC round 2 + + async fn qc_env_with_caddy_site(site: String) -> Option { + let caddy = ianitor_testkit::proc::require_binary("caddy")?; + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + let fake = env.dir.join("fake/systemctl"); + std::fs::create_dir_all(env.dir.join("fake/units")).unwrap(); + std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap(); + std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap(); + let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let d = |p: &str| env.dir.join(p).display().to_string(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + "\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n", + d("engine"), + fake.display(), + d("certs"), + d("caddy-state"), + d("logs/caddy-access.log"), + d("creds"), + d("caddy/admin.sock"), + ); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + Some(CaddyEnv { env, https }) + } + + /// QC r2: a forward-auth host with a health check is kept under edge (edge checks the + /// upstream). Under Caddy the watch probes *through* Caddy without a session: Authelia's + /// redirect is not 2xx, so the same change is reverted. + #[tokio::test(flavor = "multi_thread")] + async fn qc_forward_auth_host_with_health_check_is_kept_under_caddy_as_under_edge() { + let auth = ianitor_testkit::authelia::MockAuthelia::start().await; + let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url()); + let Some(ce) = qc_env_with_caddy_site(site).await else { + return; + }; + let env = &ce.env; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let host = |h: &str| { + json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", + "auth": "forward-auth", "health_check": {"path": "/", "interval_secs": 1}}}) + }; + let rec = env + .apply("POST", "/api/v1/hosts", Some(host("a.test"))) + .await; + eprintln!("QC under edge: {}", rec["state"]); + 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); + wait_engine(env, "caddy").await; + let rec = env + .apply("POST", "/api/v1/hosts", Some(host("b.test"))) + .await; + eprintln!( + "QC under caddy: {} {}", + rec["state"], rec["reason"]["detail"] + ); + assert_eq!(rec["state"], "kept", "{rec}"); + } + + /// QC r2: control nudges Caddy (device list, renewed certificates) by POST /load of the + /// unchanged caddy.json. Caddy skips a load of an identical config, so the files it read at + /// start are not read again. + #[tokio::test(flavor = "multi_thread")] + async fn qc_reloading_the_same_caddy_json_rereads_the_certificate_files() { + let Some(ce) = env_with_caddy().await else { + return; + }; + let env = &ce.env; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let rec = env + .apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}))) + .await; + assert_eq!(rec["state"], "kept"); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202); + wait_engine(env, "caddy").await; + assert_eq!(visit(env, ce.https, "a.test").await, 200); + // Replace a.test's certificate with one from a root the client does not trust. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + let (root, rk) = ianitor_core::pki::create_root(now).unwrap(); + let k = ianitor_core::pki::generate_key().unwrap(); + let csr = + ianitor_core::pki::intermediate_csr(&k, ianitor_core::pki::INTERMEDIATE_CN).unwrap(); + let int = ianitor_core::pki::Intermediate::new( + &ianitor_core::pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), + k, + ) + .unwrap(); + let leaf = ianitor_core::pki::issue_server(&int, "a.test", now).unwrap(); + std::fs::write(env.dir.join("certs/a.test.key"), &leaf.key_pem).unwrap(); + std::fs::write(env.dir.join("certs/a.test.crt"), &leaf.chain_pem).unwrap(); + // What control does in devices_changed / reload_serving_engine under Caddy. + let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap(); + let r = ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &text).await; + assert!(r.is_ok(), "{r:?}"); + let after = visit(env, ce.https, "a.test").await; + eprintln!( + "QC after same-config load: visit = {after} (200 = old certificate still served)" + ); + assert_ne!( + after, 200, + "Caddy still serves the certificate it read at start" + ); + } + + /// QC r2: a control crash with a trial loaded into Caddy. Edge reverts an unconfirmed trial + /// by itself; Caddy has no deadline, so the unverified config keeps serving while control + /// is down. + #[tokio::test(flavor = "multi_thread")] + async fn qc_control_crash_mid_trial_under_caddy_leaves_the_last_good_config() { + let Some(mut ce) = env_with_caddy().await else { + return; + }; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let host = |h: &str| json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}); + assert_eq!( + ce.env + .apply("POST", "/api/v1/hosts", Some(host("a.test"))) + .await["state"], + "kept" + ); + let r = ce + .env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202); + wait_engine(&ce.env, "caddy").await; + ce.env.kill_control(); + ce.env.start_control(Some("trial_loaded")); + let r = ce + .env + .call("POST", "/api/v1/hosts", Some(host("b.test"))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let st = ce.env.wait_control_exit(Duration::from_secs(30)); + eprintln!("QC control exit: {st:?}"); + assert!(st.is_some()); + // Longer than edge's trial deadline would allow. + tokio::time::sleep(Duration::from_secs(15)).await; + let during = visit(&ce.env, ce.https, "b.test").await; + eprintln!("QC b.test through Caddy 15 s after the crash, control down: {during}"); + ce.env.start_control(None); + tokio::time::sleep(Duration::from_secs(3)).await; + let after = visit(&ce.env, ce.https, "b.test").await; + eprintln!("QC b.test after control restarted (recovery): {after}"); + assert_ne!(after, 200, "recovery must revert the trial"); + assert_ne!( + during, 200, + "Caddy served the unconfirmed trial while control was down" + ); + } + + // ---------------------------------------------------------------- fix round 2 + + /// Like `env_with_caddy`, with a chosen watch, and with or without the Caddy trial guard + /// (the fake systemctl starts it next to Caddy unless `fake/no-guard` exists). + async fn caddy_env(watch_secs: u64, guard: bool) -> Option { + let caddy = ianitor_testkit::proc::require_binary("caddy")?; + let mut env = Env::new(EnvSpec { + watch_secs, + ..Default::default() + }) + .await; + let fake = env.dir.join("fake/systemctl"); + std::fs::create_dir_all(env.dir.join("fake/units")).unwrap(); + std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap(); + if !guard { + std::fs::write(env.dir.join("fake/no-guard"), "").unwrap(); + } + std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap(); + let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port()); + let d = |p: &str| env.dir.join(p).display().to_string(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + "\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n", + d("engine"), + fake.display(), + d("certs"), + d("caddy-state"), + d("logs/caddy-access.log"), + d("creds"), + d("caddy/admin.sock"), + ); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + Some(CaddyEnv { env, https }) + } + + async fn to_caddy_with(env: &Env, echo: &ianitor_testkit::upstream::Echo) { + let rec = env + .apply( + "POST", + "/api/v1/hosts", + Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})), + ) + .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); + wait_engine(env, "caddy").await; + } + + async fn wait_state(env: &Env, id: &str, state: &str) { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let r = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + if r.json["state"] == state { + return; + } + assert!(Instant::now() < deadline, "never {state}: {}", r.text); + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + + fn b_host(echo: &ianitor_testkit::upstream::Echo) -> Value { + json!({"host": {"hostname": "b.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}) + } + + /// QC round 2, M2: something reloads Caddy during a trial's watch (a device change, a + /// restart of caddy-fallback). The trial is gone from Caddy; the watch must notice and + /// treat it as interrupted, not report it kept while Caddy serves the old config. + #[tokio::test(flavor = "multi_thread")] + async fn a_reload_of_caddy_during_the_watch_is_noticed() { + let Some(ce) = caddy_env(8, true).await else { + return; + }; + let env = &ce.env; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + to_caddy_with(env, &echo).await; + let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + wait_state(env, &id, "watching").await; + assert_eq!( + visit(env, ce.https, "b.test").await, + 200, + "the trial serves" + ); + // What a device change or a Caddy restart does: Caddy gets the last good config. + let good = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap(); + ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &good) + .await + .unwrap(); + let rec = env.wait_apply(&id).await; + assert_ne!(rec["state"], "kept", "{rec}"); + assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}"); + let now_good = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap(); + assert!(!now_good.contains("b.test"), "{now_good}"); + assert_ne!(visit(env, ce.https, "b.test").await, 200); + } + + /// QC round 2, minor 3: the `watching` crash point under Caddy. + #[tokio::test(flavor = "multi_thread")] + async fn a_crash_while_watching_under_caddy_is_reverted() { + let Some(mut ce) = caddy_env(4, true).await else { + return; + }; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + to_caddy_with(&ce.env, &echo).await; + ce.env.kill_control(); + ce.env.start_control(Some("watching")); + let r = ce + .env + .call("POST", "/api/v1/hosts", Some(b_host(&echo))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some()); + ce.env.start_control(None); + let rec = ce.env.wait_apply(&id).await; + assert_eq!(rec["state"], "reverted", "{rec}"); + assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200); + assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200); + } + + /// QC round 2, B2 (a): what systemd runs after control stops (ExecStopPost): with an + /// unconfirmed trial in the journal, Caddy goes back to the last good caddy.json at once, + /// without waiting for the guard's deadline. + #[tokio::test(flavor = "multi_thread")] + async fn caddy_revert_after_a_crash_loads_the_last_good_config() { + let Some(mut ce) = caddy_env(3, false).await else { + return; + }; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + to_caddy_with(&ce.env, &echo).await; + ce.env.kill_control(); + ce.env.start_control(Some("trial_loaded")); + let r = ce + .env + .call("POST", "/api/v1/hosts", Some(b_host(&echo))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some()); + assert_eq!( + visit(&ce.env, ce.https, "b.test").await, + 200, + "the trial was loaded" + ); + let config = ce.env.config_path(); + let revert = || { + std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) + .args(["caddy-revert", "--config"]) + .arg(&config) + .output() + .unwrap() + }; + let out = revert(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200); + assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200); + // After recovery there is no trial: it changes nothing and succeeds. + ce.env.start_control(None); + tokio::time::sleep(Duration::from_secs(2)).await; + let out = revert(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200); + } + + /// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads + /// caddy.json (must-revalidate); the revoked device must no longer get in, the newly + /// allowed one must. + #[tokio::test(flavor = "multi_thread")] + async fn qc_device_revoked_under_caddy_is_refused() { + use ianitor_core::pki; + use ianitor_testkit::client::{self, ClientCert, Req}; + let Some(ce) = env_with_caddy().await else { + return; + }; + let env = &ce.env; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + let (root, rk) = pki::create_root(now).unwrap(); + let k = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); + let int = + pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k) + .unwrap(); + let phone = pki::issue_device(&int, "phone", now).unwrap(); + let laptop = pki::issue_device(&int, "laptop", now).unwrap(); + std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap(); + std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap(); + let cc = |d: &pki::Issued| ClientCert { + chain_pem: d.chain_pem.clone(), + key_pem: d.key_pem.clone(), + tls12_only: false, + }; + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let rec = env + .apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}}))) + .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); + wait_engine(env, "caddy").await; + let visit_as = |d: &pki::Issued| { + let c = cc(d); + let roots = env.ca.roots(); + async move { + match client::https_with_cert( + ce.https, + "d.test", + roots, + &c, + &Req::get("d.test", "/"), + ) + .await + { + Ok(r) => r.status, + Err(_) => 0, + } + } + }; + let before = visit_as(&phone).await; + eprintln!("QC phone under Caddy before revocation: {before}"); + assert_eq!(before, 200); + // Revoke the phone, allow the laptop; tell Caddy the way control does. + std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap(); + let sock = env.dir.join("caddy/admin.sock"); + let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap(); + ianitor_control::caddy_link::load(&sock, &text) + .await + .unwrap(); + assert!( + ianitor_control::caddy_link::runs(&sock, &text) + .await + .unwrap() + ); + let phone_after = visit_as(&phone).await; + let laptop_after = visit_as(&laptop).await; + eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}"); + assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy"); + assert_eq!( + laptop_after, 200, + "newly allowed laptop is not let in under Caddy" + ); + } + + // ---------------------------------------------------------------- fix round 3 + + /// A control with the Domi CA, an intermediate signed by a test root, one device issued + /// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves. + struct PkiEnv { + ce: CaddyEnv, + roots: std::sync::Arc, + device_id: String, + device: ianitor_testkit::client::ClientCert, + } + + async fn pki_env(watch_secs: u64, caddy: bool) -> Option { + use ianitor_core::pki; + let ce = caddy_env(watch_secs, true).await?; + let mut ce = ce; + let env = &mut ce.env; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + let (root_pem, root_key) = pki::create_root(now).unwrap(); + std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap(); + std::fs::write( + env.dir.join("creds/pki-password"), + "round-three-password-123", + ) + .unwrap(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + "\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n", + env.dir.join("offline-root.crt").display() + ); + std::fs::write(env.config_path(), text).unwrap(); + env.kill_control(); + env.start_control(None); + let cli = |env: &Env, args: &[&str]| { + env.command() + .args(args) + .arg("--config") + .arg(env.config_path()) + .output() + .unwrap() + }; + // The intermediate, signed offline. + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); + let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap(); + std::fs::write(env.dir.join("int.crt"), signed).unwrap(); + let int_path = env.dir.join("int.crt").display().to_string(); + let out = cli(env, &["pki", "install", &int_path]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + // One device. + let r = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "phone", "kind": "phone"})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let code = r.json["match_code"].as_str().unwrap().to_owned(); + let out = cli(env, &["pki", "approve", &code]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let devices: Value = serde_json::from_str( + &std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(), + ) + .unwrap(); + let d = &devices[0]; + let device_id = d["id"].as_str().unwrap().to_owned(); + let sealed = + std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key"))) + .unwrap(); + let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap(); + let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap(); + let device = ianitor_testkit::client::ClientCert { + chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()), + key_pem: key.serialize_pem(), + tls12_only: false, + }; + let mut store = rustls::RootCertStore::empty(); + store + .add(rustls_pki_types::CertificateDer::from( + pki::chain_der(&root_pem).unwrap().remove(0), + )) + .unwrap(); + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let rec = env + .apply( + "POST", + "/api/v1/hosts", + Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})), + ) + .await; + assert_eq!(rec["state"], "kept", "{rec}"); + // The echo upstream must outlive this function: keep it running in the background. + std::mem::forget(echo); + if caddy { + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + wait_engine(env, "caddy").await; + } + Some(PkiEnv { + ce, + roots: std::sync::Arc::new(store), + device_id, + device, + }) + } + + impl PkiEnv { + async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 { + match ianitor_testkit::client::https_with_cert( + at, + "d.test", + self.roots.clone(), + &self.device, + &ianitor_testkit::client::Req::get("d.test", "/"), + ) + .await + { + Ok(r) => r.status, + Err(_) => 0, + } + } + + fn serving(&self, caddy: bool) -> std::net::SocketAddr { + if caddy { + self.ce.https + } else { + self.ce.env.edge.as_ref().unwrap().https + } + } + } + + /// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE + /// answers at once, the allow list is on disk at once, and the device is refused within + /// edge's backstop window although an apply is still watching. + async fn revoke_during_a_watch(caddy: bool) { + let Some(p) = pki_env(6, caddy).await else { + return; + }; + let env = &p.ce.env; + let at = p.serving(caddy); + assert_eq!(p.visit_as_device(at).await, 200, "the device gets in"); + let echo = ianitor_testkit::upstream::Echo::start("app").await; + let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + wait_state(env, &id, "watching").await; + let t = Instant::now(); + let d = env + .call( + "DELETE", + &format!("/api/v1/certs/devices/{}", p.device_id), + None, + ) + .await; + let took = t.elapsed(); + assert_eq!(d.status, 204, "{}", d.text); + assert!( + took < Duration::from_millis(1500), + "the DELETE waited {took:?}" + ); + let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); + let listed = p + .device + .chain_pem + .split("-----END CERTIFICATE-----") + .next() + .unwrap(); + assert!( + !allow.contains(listed.trim()), + "the revoked device is still on the list" + ); + if caddy { + // Caddy keeps the trial until the apply ends; then the device is out at once. + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "kept", "{rec}"); + assert_ne!( + p.visit_as_device(at).await, + 200, + "revoked device still gets in under Caddy" + ); + } else { + let deadline = Instant::now() + Duration::from_secs(6); + while p.visit_as_device(at).await == 200 { + assert!( + Instant::now() < deadline, + "revoked device still gets in under Pingora" + ); + tokio::time::sleep(Duration::from_millis(250)).await; + } + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "kept", "{rec}"); + } + let c = env.call("GET", "/api/v1/certs", None).await; + assert!(c.json["devices_problem"].is_null(), "{}", c.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() { + revoke_during_a_watch(false).await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() { + revoke_during_a_watch(true).await; + } + + /// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and + /// caddy-revert succeeds (the unit must not show failed). + #[tokio::test(flavor = "multi_thread")] + async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() { + let mut env = env().await; + env.kill_control(); + std::fs::write( + env.dir.join("state/caddy-trial.json"), + r#"{"apply_id":"ch_x","deadline":1}"#, + ) + .unwrap(); + let out = env + .command() + .args(["caddy-revert", "--config"]) + .arg(env.config_path()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(!env.dir.join("state/caddy-trial.json").exists()); + } + + // ---------------------------------------------------------------- fix round 4 + + async fn engine_view(env: &Env) -> Value { + env.call("GET", "/api/v1/engine", None).await.json + } + + async fn wait_switching(env: &Env) { + let deadline = Instant::now() + Duration::from_secs(10); + while engine_view(env).await["state"] != "switching" { + assert!(Instant::now() < deadline, "the switch never started"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + + async fn wait_switch_over(env: &Env) -> Value { + let deadline = Instant::now() + Duration::from_secs(40); + loop { + let e = engine_view(env).await; + if e["state"] == "running" { + return e; + } + assert!(Instant::now() < deadline, "the switch never ended: {e}"); + tokio::time::sleep(Duration::from_millis(300)).await; + } + } + + async fn revoke(env: &Env, id: &str) { + let t = Instant::now(); + let d = env + .call("DELETE", &format!("/api/v1/certs/devices/{id}"), None) + .await; + assert_eq!(d.status, 204, "{}", d.text); + assert!( + t.elapsed() < Duration::from_secs(3), + "the DELETE waited {:?}", + t.elapsed() + ); + } + + async fn refused_soon(p: &PkiEnv, at: std::net::SocketAddr, what: &str) { + let deadline = Instant::now() + Duration::from_secs(4); + while p.visit_as_device(at).await == 200 { + assert!(Instant::now() < deadline, "{what}"); + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + + /// QC round 4, case A: a device is revoked while a switch to Caddy is still waiting for + /// the unit, after Caddy has already read the allow list. The switch ends by telling + /// Caddy again, so the device is refused once Caddy serves. + #[tokio::test(flavor = "multi_thread")] + async fn a_revocation_during_a_switch_to_caddy_is_in_force_when_it_ends() { + let Some(p) = pki_env(2, false).await else { + return; + }; + let env = &p.ce.env; + std::fs::write(env.dir.join("fake/start-delay"), "5").unwrap(); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + wait_switching(env).await; + // Caddy is up and has read its files; the unit is not reported active yet. + let deadline = Instant::now() + Duration::from_secs(5); + while p.visit_as_device(p.ce.https).await != 200 { + assert!(Instant::now() < deadline, "Caddy did not come up"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + assert_eq!(engine_view(env).await["state"], "switching"); + revoke(env, &p.device_id).await; + let e = wait_switch_over(env).await; + assert_eq!(e["running"], "caddy", "{e}"); + refused_soon( + &p, + p.ce.https, + "the revoked device still gets in under Caddy after the switch", + ) + .await; + } + + /// QC round 4, case B: a switch away from Caddy fails before Caddy is stopped, and a + /// device was revoked meanwhile. The Caddy that kept serving must refuse it. + #[tokio::test(flavor = "multi_thread")] + async fn a_revocation_during_a_failed_switch_away_from_caddy_is_in_force() { + let Some(p) = pki_env(2, true).await else { + return; + }; + let env = &p.ce.env; + assert_eq!( + p.visit_as_device(p.ce.https).await, + 200, + "the device gets in" + ); + std::fs::write(env.dir.join("fake/stop-delay"), "4").unwrap(); + std::fs::write(env.dir.join("fake/fail-stop"), "caddy-fallback.service\n").unwrap(); + let r = env + .call("POST", "/api/v1/engine", Some(json!({"target": "pingora"}))) + .await; + assert_eq!(r.status, 202, "{}", r.text); + wait_switching(env).await; + revoke(env, &p.device_id).await; + let e = wait_switch_over(env).await; + assert_eq!(e["running"], "caddy", "{e}"); + assert!(!e["last_error"].is_null(), "{e}"); + refused_soon( + &p, + p.ce.https, + "the revoked device still gets in under the Caddy that kept serving", + ) + .await; + // Nothing is left pending. + let deadline = Instant::now() + Duration::from_secs(6); + loop { + let c = env.call("GET", "/api/v1/certs", None).await; + if c.json["devices_problem"].is_null() { + break; + } + assert!(Instant::now() < deadline, "{}", c.text); + tokio::time::sleep(Duration::from_millis(500)).await; + } + } +} diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs new file mode 100644 index 0000000..0b998f2 --- /dev/null +++ b/crates/control/tests/pki.rs @@ -0,0 +1,769 @@ +// 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"; + + /// Whether an allow list names any device (the placeholder that keeps it from being + /// empty is not one). + fn lists_a_device(allow: &str) -> bool { + pki::chain_der(allow) + .unwrap_or_default() + .iter() + .any(|d| pki::inspect_der(d).is_ok_and(|i| i.subject_cn != pki::NO_DEVICE_CN)) + } + + 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(); + let env = env_with_root(&root_pem).await; + (env, Offline { root_pem, root_key }) + } + + async fn env_with_root(root_pem: &str) -> Env { + // Only the root certificate goes next to control; the key stays in this test. + let extra = |dir: &Path| { + format!( + "\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 + } + + 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, + "{} +{} +{}", + 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"); + 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. (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() + .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[body.len() - 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!(lists_a_device(&allow)); + + // 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(""), "{}", g.text); + assert!(g.text.contains("Mark's phone"), "{}", g.text); + } + // No token needed for the download itself (the link is the secret) ... + let d = env.call_with("POST", &path, &[], None).await; + assert_eq!(d.status, 200, "{}", d.text); + assert_eq!(d.header("content-type"), Some("application/x-pkcs12")); + let ks = p12_keystore::KeyStore::from_pkcs12( + &d.body, + &password, + p12_keystore::Pkcs12ImportPolicy::Strict, + ) + .unwrap(); + let (_, chain) = ks.private_key_chain().unwrap(); + assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root"); + // ... and it works only once. + let d = env.call_with("POST", &path, &[], None).await; + assert_eq!(d.status, 410, "{}", d.text); + assert_eq!(d.json["error"]["code"], "pki.bundle_used"); + let g = env.call_with("GET", &path, &[], None).await; + assert_eq!(g.status, 410, "{}", g.text); + + // Revoke: off the allow list, no new install file. + let r = env + .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) + .await; + assert_eq!(r.status, 204, "{}", r.text); + let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); + assert!(!lists_a_device(&allow), "{allow}"); + assert!( + allow.contains("BEGIN CERTIFICATE"), + "never empty (Caddy refuses that)" + ); + let b = env + .call( + "POST", + &format!("/api/v1/certs/devices/{did}/bundle"), + Some(json!({"format": "p12"})), + ) + .await; + assert_eq!(b.status, 409, "{}", b.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() { + let (mut env, off) = env_with_pki().await; + env.kill_control(); + std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap(); + // A control that does not refuse would serve forever: give it 20 s, then kill it. + let mut child = env + .command() + .arg("--config") + .arg(env.config_path()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(s) = child.try_wait().unwrap() { + break Some(s); + } + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + std::thread::sleep(Duration::from_millis(50)); + }; + assert!( + status.is_some_and(|s| !s.success()), + "control started with a root key in its state dir" + ); + let mut err = String::new(); + std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut err).unwrap(); + assert!(err.contains("root"), "{err}"); + // And the message never prints the key. + assert!(!err.contains("PRIVATE KEY"), "{err}"); + } + + /// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl. + /// A root made with openssl signs control's CSR with the extensions file control serves, + /// and control installs the result. + #[tokio::test(flavor = "multi_thread")] + async fn an_intermediate_signed_with_openssl_is_installed() { + let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else { + return; + }; + let off = ianitor_testkit::proc::TempDir::new("openssl-root"); + let run = |args: &[&str]| { + let o = std::process::Command::new(&openssl) + .args(args) + .current_dir(off.join(".")) + .output() + .unwrap(); + assert!( + o.status.success(), + "openssl {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + run(&[ + "req", + "-x509", + "-new", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:P-256", + "-nodes", + "-keyout", + "domi-root.key", + "-out", + "domi-root.crt", + "-days", + "3653", + "-subj", + "/CN=Domi PKI Root/O=Fabrica Domi", + "-addext", + "basicConstraints=critical,CA:TRUE,pathlen:1", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + ]); + let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap(); + let env = env_with_root(&root_pem).await; + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let base = r.json["file_base"].as_str().unwrap().to_owned(); + let cmd = r.json["approve_command"].as_str().unwrap().to_owned(); + assert!(cmd.starts_with("openssl x509 -req"), "{cmd}"); + std::fs::write( + off.join(&format!("{base}.csr")), + r.json["csr_pem"].as_str().unwrap(), + ) + .unwrap(); + let ext = env + .call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None) + .await; + assert_eq!(ext.status, 200, "{}", ext.text); + std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap(); + // Exactly the command control shows. + let args: Vec<&str> = cmd.split_whitespace().skip(1).collect(); + run(&args); + let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap(); + let info = pki::inspect(&signed).unwrap(); + assert_eq!(info.path_len, Some(0)); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": signed})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["state"], "approved"); + } + + fn walk(dir: &Path) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + 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 if p.is_file() { + out.push(p); + } + } + } + out + } + + fn contains(hay: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) + } + + /// QC: the openssl step can produce intermediates that are CA + pathlen 0 but cannot + /// issue what control issues. Control installs them and reissues every Domi host. + #[tokio::test(flavor = "multi_thread")] + async fn qc_install_refuses_intermediates_that_cannot_issue() { + let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else { + return; + }; + let off = ianitor_testkit::proc::TempDir::new("qc-openssl-root"); + let run = |args: &[&str]| { + let o = std::process::Command::new(&openssl) + .args(args) + .current_dir(off.join(".")) + .output() + .unwrap(); + assert!( + o.status.success(), + "openssl {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + run(&[ + "req", + "-x509", + "-new", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:P-256", + "-nodes", + "-keyout", + "domi-root.key", + "-out", + "domi-root.crt", + "-days", + "3653", + "-subj", + "/CN=Domi PKI Root/O=Fabrica Domi", + "-addext", + "basicConstraints=critical,CA:TRUE,pathlen:1", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + ]); + let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap(); + let env = env_with_root(&root_pem).await; + let good = "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\n"; + let cases = [ + ( + "keyUsage without keyCertSign", + "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, digitalSignature\n", + "365", + ), + ( + "EKU serverAuth only (devices cannot chain)", + "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\nextendedKeyUsage = serverAuth\n", + "365", + ), + ("valid past the root (-days 4000)", good, "4000"), + ]; + let mut accepted = Vec::new(); + for (label, ext, days) in cases { + 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(); + std::fs::write(off.join("q.csr"), r.json["csr_pem"].as_str().unwrap()).unwrap(); + std::fs::write(off.join("q.ext"), ext).unwrap(); + run(&[ + "x509", + "-req", + "-in", + "q.csr", + "-CA", + "domi-root.crt", + "-CAkey", + "domi-root.key", + "-days", + days, + "-sha256", + "-extfile", + "q.ext", + "-out", + "q.crt", + ]); + let signed = std::fs::read_to_string(off.join("q.crt")).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": signed})), + ) + .await; + eprintln!("QC {label}: {} {}", r.status, r.json["state"]); + if r.status == 200 { + accepted.push(label); + } + } + assert!( + accepted.is_empty(), + "control installed unusable intermediates: {accepted:?}" + ); + } + + /// QC: the root key name that `ianitor-control ca init` and docs/pki.md's openssl + /// command write is `domi-root.key`. + #[test] + fn qc_root_key_check_finds_the_names_ianitor_itself_uses() { + let d = ianitor_testkit::proc::TempDir::new("qc-rootkey"); + let mut missed = Vec::new(); + for name in [ + "domi-root.key", + "offline/domi-root.key", + "Domi_Root_CA.pem", + "ca.key", + ] { + let p = d.join(name); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write( + &p, + // (Split so that this file does not match the pre-commit hook itself.) + concat!( + "-----BEGIN ", + "PRIVATE KEY-----\nx\n-----END ", + "PRIVATE KEY-----\n" + ), + ) + .unwrap(); + if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() { + missed.push(name); + } + std::fs::remove_file(&p).unwrap(); + } + assert!(missed.is_empty(), "root_key_files missed: {missed:?}"); + } + + /// QC M2: a revocation that cannot be written (or not told to edge) must not answer 204 and + /// be forgotten. It answers an error, the certificates screen says so, and once the disk + /// works again (here: a restart without the fault) the allow list catches up; a repeated + /// DELETE nudges again. + #[tokio::test(flavor = "multi_thread")] + async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() { + let (mut env, off) = env_with_pki().await; + install_intermediate(&env, &off).await; + let r = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "tablet", "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!(cli(&env, &["pki", "approve", &code]).status.success()); + let done = wait_request(&env, &rid, "approved").await; + let did = done["device_id"].as_str().unwrap().to_owned(); + let allow_file = env.dir.join("certs/domi-devices.pem"); + let on_list = || lists_a_device(&std::fs::read_to_string(&allow_file).unwrap_or_default()); + let deadline = Instant::now() + Duration::from_secs(10); + while !on_list() { + assert!( + Instant::now() < deadline, + "the device never reached the allow list" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + // From now on the allow list cannot be written. + env.kill_control(); + env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]); + let d = env + .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) + .await; + assert_eq!(d.status, 503, "{}", d.text); + assert_eq!( + d.json["error"]["code"], "pki.devices_unwritten", + "{}", + d.text + ); + // The certificates screen keeps saying so; the device is still on the list. + let c = env.call("GET", "/api/v1/certs", None).await; + assert_eq!( + c.json["devices_problem"]["code"], "pki.devices_unwritten", + "{}", + c.text + ); + assert!(on_list()); + // The disk works again: the list catches up by itself, without another Revoke. + env.kill_control(); + env.start_control(None); + let deadline = Instant::now() + Duration::from_secs(10); + while on_list() { + assert!(Instant::now() < deadline, "the revocation never caught up"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + // A repeated Revoke is fine and nudges the engine again. + let d = env + .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) + .await; + assert_eq!(d.status, 204, "{}", d.text); + let c = env.call("GET", "/api/v1/certs", None).await; + assert!(c.json["devices_problem"].is_null(), "{}", c.text); + } +} diff --git a/crates/control/tests/ui_auth.rs b/crates/control/tests/ui_auth.rs new file mode 100644 index 0000000..431c975 --- /dev/null +++ b/crates/control/tests/ui_auth.rs @@ -0,0 +1,283 @@ +// 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); + } + + /// QC: an admin host (the proof header rule) without forward-auth. Edge strips Remote-* + /// only on forward-auth hosts and sets the proof on every request, so any client that + /// can reach the host names any user. Control accepts such a host file. + #[tokio::test(flavor = "multi_thread")] + async fn qc_proof_on_a_host_without_forward_auth_is_refused() { + let env = env_for("secrets = [\"ui-proof\"]\n".into(), "a.test").await; + let host = json!({"host": { + "hostname": "a.test", "upstreams": [format!("http://{}", env.api)], + "tls": "domi", "auth": "none", + "request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}] + }}); + let r = env.call("POST", "/api/v1/hosts", Some(host)).await; + // Refused at the door: the proof belongs to the [ui] host behind forward-auth. + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!( + r.json["errors"][0]["code"], "host.header.proof", + "{}", + r.text + ); + assert!( + env.call("GET", "/api/v1/hosts/a.test", None).await.status == 404, + "the host went live" + ); + if r.status != 202 { + return; + } + let edge = env.edge.as_ref().unwrap(); + let r = client::https( + edge.https, + "a.test", + env.ca.roots(), + &Req::new("POST", "a.test", "/api/v1/tokens") + .body(br#"{"name":"pwned"}"#) + .header("content-type", "application/json") + .header("x-ianitor-ui", "1") + .header("remote-user", "mallory"), + ) + .await + .unwrap(); + eprintln!("QC POST /tokens as mallory: {} {}", r.status, r.text()); + assert_ne!( + r.status, + 201, + "a client minted an API token as mallory: {}", + r.text() + ); + } + + /// QC: signed in at Authelia (alice) but the client also sends a proof guess: edge must + /// replace, not append, the proof; and Remote-User must be Authelia's. + #[tokio::test(flavor = "multi_thread")] + async fn qc_signed_in_client_with_own_proof_and_user_is_alice() { + 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; + 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}"); + let edge = env.edge.as_ref().unwrap(); + let r = client::https( + edge.https, + "a.test", + env.ca.roots(), + &Req::get("a.test", "/api/v1/overview") + .header("cookie", "authelia_session=good") + .header("x-ianitor-proof", "guess") + .header("remote-user", "mallory") + .header("remote-name", "Mallory"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", r.text()); + eprintln!( + "QC viewer: {}", + r.text()[r.text().find("\"viewer\"").unwrap_or(0)..] + .chars() + .take(80) + .collect::() + ); + assert!(!r.text().contains("allory"), "{}", r.text()); + } +} 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/compile/caddy.rs b/crates/core/src/compile/caddy.rs index 2066cf7..3a34071 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, @@ -26,9 +26,13 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { root.insert( "admin".into(), - match o.caddy_admin { - Some(addr) => json!({ "listen": addr.to_string() }), - None => json!({ "disabled": true }), + match (&o.caddy_admin_socket, o.caddy_admin) { + // Only the ianitor group (control) can reach it; no TCP port for local processes. + (Some(s), _) => { + json!({ "listen": format!("unix//{}|0660", s.trim_start_matches('/')) }) + } + (None, Some(addr)) => json!({ "listen": addr.to_string() }), + (None, None) => json!({ "disabled": true }), }, ); root.insert( @@ -52,13 +56,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!({})); @@ -75,6 +89,18 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { }), ); https.insert("protocols".into(), json!(["h1", "h2"])); + if !o.trusted_proxies.is_empty() { + // Like edge: X-Forwarded-For from these peers names the client (logs, `client_ip`). + https.insert( + "trusted_proxies".into(), + json!({ + "source": "static", + "ranges": o.trusted_proxies.iter().map(ToString::to_string).collect::>() + }), + ); + https.insert("client_ip_headers".into(), json!(["X-Forwarded-For"])); + https.insert("trusted_proxies_strict".into(), json!(1)); + } if !logged.is_empty() { let names: Map = logged .iter() @@ -203,6 +229,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 +373,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..a486c44 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,15 @@ 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), + }), + trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(), forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth { upstream: upstream(&fa.upstream), path_and_query: fa.path_and_query.clone(), @@ -55,6 +64,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..c03b71c 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; @@ -36,6 +41,13 @@ pub struct CompileOptions { pub caddy_credentials_dir: String, /// Caddy admin endpoint; `None` disables the admin API. pub caddy_admin: Option, + /// Caddy admin endpoint on a Unix socket (mode 0660), which control uses to load a changed + /// config while Caddy serves. Takes precedence over `caddy_admin`. + pub caddy_admin_socket: Option, + /// Peers whose `X-Forwarded-For` is believed (a proxy in front, such as Caddy beside + /// Ianitor on loopback): the share-link throttle and the access log then see the real + /// client. Empty (the default): only the connection's own address counts. + pub trusted_proxies: Vec, } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -68,6 +80,12 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result Result<(), CompileError> { + if let Some(s) = &o.caddy_admin_socket { + check_path(s).map_err(|reason| CompileError::BadOption { + option: "caddy_admin_socket", + reason, + })?; + } for (option, value) in [ ("cert_dir", &o.cert_dir), ("state_dir", &o.state_dir), diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index fdece67..b8d6869 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,11 @@ 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, + /// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub trusted_proxies: Vec, /// Sorted by hostname. pub hosts: Vec, } @@ -106,4 +111,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/error.rs b/crates/core/src/error.rs index a371155..e4dbc84 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -170,6 +170,10 @@ pub enum ValidationError { BadHealthCheck { file: String, reason: &'static str }, #[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")] ForwardAuthNotConfigured { file: String }, + #[error( + "{file}: only a host behind sign-in (auth = \"forward-auth\") may send the `ui-proof` secret; it is the web UI's admin host" + )] + ProofWithoutSignIn { file: String }, #[error("{file}: forward_auth is not usable: {reason}")] BadForwardAuth { file: String, reason: &'static str }, #[error("{file}: acme is not usable: {reason}")] @@ -211,6 +215,7 @@ impl ValidationError { | E::BadHeaderRule { file, .. } | E::BadHealthCheck { file, .. } | E::ForwardAuthNotConfigured { file } + | E::ProofWithoutSignIn { file } | E::BadForwardAuth { file, .. } | E::BadAcme { file, .. } => file, E::DuplicateHostname { second, .. } => second, @@ -296,6 +301,7 @@ impl ValidationError { } E::BadHealthCheck { .. } => "host.health.path", E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured", + E::ProofWithoutSignIn { .. } => "host.header.proof", E::BadForwardAuth { .. } => "site.forward_auth", E::BadAcme { .. } => "site.acme", } @@ -331,6 +337,7 @@ impl ValidationError { } E::BadHealthCheck { .. } => Some("health_check.path".into()), E::ForwardAuthNotConfigured { .. } => Some("auth".into()), + E::ProofWithoutSignIn { .. } => Some("auth".into()), _ => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c3536b0..83e19de 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,7 @@ pub mod compile; pub mod edge_config; mod error; mod model; +pub mod pki; pub mod routes; pub mod share; pub mod time; @@ -21,6 +22,7 @@ pub use error::{ValidationError, ValidationErrors}; pub use model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES, - MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, + MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, + UpstreamHost, }; pub use validate::{SourceFile, load}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 72e43c2..b4822af 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`). @@ -217,6 +219,10 @@ impl Model { } } +/// The secret that carries the web UI's per-boot proof (docs/api.md, "Sign-in"). Only the admin +/// host, behind forward-auth, may send it. +pub const UI_PROOF_SECRET: &str = "ui-proof"; + /// Let's Encrypt production directory, the default when `[acme] directory` is not set. pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory"; /// Let's Encrypt staging directory. diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs new file mode 100644 index 0000000..72e4445 --- /dev/null +++ b/crates/core/src/pki.rs @@ -0,0 +1,853 @@ +// 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 §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"; +/// 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("the certificate cannot be read: {0}")] + BadCertificate(String), + #[error("the certificate signing request cannot be read or its signature is wrong")] + BadCsr, + #[error("the request's subject must start with \"{INTERMEDIATE_CN}\"")] + CsrSubject, + #[error("the private key cannot be read")] + BadKey, + #[error("the certificate is not a CA certificate")] + NotCa, + #[error("the private key does not belong to the certificate")] + KeyMismatch, + #[error("the issuing certificate has expired or is not valid yet")] + IssuerExpired, + #[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(…)") + } +} + +impl KeyPair { + /// 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 { + 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)) +} + +/// Common name of [`no_device_placeholder`]. +pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed"; + +/// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty +/// leaf list (and with it the whole config), so the list is never empty: this self-signed +/// certificate's key is dropped right here, so no client can ever present it, and it is not +/// issued by the Domi intermediate, so edge refuses it too. +pub fn no_device_placeholder(now: i64) -> Result { + let key = generate_key()?; + let mut p = CertificateParams::default(); + p.distinguished_name = dn(NO_DEVICE_CN); + p.is_ca = IsCa::ExplicitNoCa; + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.not_before = time(now - BACKDATE_SECS)?; + p.not_after = time(now + 100 * 365 * DAY)?; + p.serial_number = Some(serial()?); + let cert = p.self_signed(&key.0).map_err(build)?; + drop(key); + Ok(cert.pem()) +} + +/// 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) +} + +/// The extensions for signing an intermediate with openssl on the offline machine (the +/// accepted manual step until Custos can sign, docs/pki.md): the same profile as +/// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile `. +pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\ +keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\ +subjectKeyIdentifier = hash\n\ +authorityKeyIdentifier = keyid:always\n"; + +/// The openssl command that signs a renewal on the offline machine (files named after the +/// request). OpenSSL 3 picks a random serial. +pub fn openssl_sign_command(base: &str) -> String { + format!( + "openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt" + ) +} + +/// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's +/// public key and CN are used; the CN must start with [`INTERMEDIATE_CN`]. +pub fn sign_intermediate( + 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(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, + }) + } +} + +/// 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, + /// keyUsage: `None` when the extension is absent. + pub key_usage: Option, + /// extendedKeyUsage: `None` when the extension is absent (any use). + pub eku: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KeyUsageInfo { + pub key_cert_sign: bool, + pub crl_sign: bool, + pub digital_signature: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EkuInfo { + pub any: bool, + pub server_auth: bool, + pub client_auth: bool, +} + +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), + key_usage: c + .key_usage() + .map_err(|e| PkiError::BadCertificate(e.to_string()))? + .map(|k| KeyUsageInfo { + key_cert_sign: k.value.key_cert_sign(), + crl_sign: k.value.crl_sign(), + digital_signature: k.value.digital_signature(), + }), + eku: c + .extended_key_usage() + .map_err(|e| PkiError::BadCertificate(e.to_string()))? + .map(|e| EkuInfo { + any: e.value.any, + server_auth: e.value.server_auth, + client_auth: e.value.client_auth, + }), + }) +} + +/// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must +/// be signed by the root, a CA with path length 0 that may sign certificates (keyCertSign), +/// allowed to issue both server and device certificates (no extendedKeyUsage, or one that +/// allows both), valid now, and no longer than the root. +pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> { + let Ok(info) = inspect(cert_pem) else { + return Some("not_certificate"); + }; + let Ok(root) = inspect(root_pem) else { + return Some("not_root"); + }; + if !issued_by(cert_pem, root_pem).unwrap_or(false) { + return Some("not_root"); + } + if !info.is_ca || info.path_len != Some(0) || !info.subject_cn.starts_with(INTERMEDIATE_CN) { + return Some("not_ca"); + } + if !info + .key_usage + .is_some_and(|k| k.key_cert_sign && k.crl_sign) + { + return Some("not_ca"); + } + if info + .eku + .is_some_and(|e| !e.any && !(e.server_auth && e.client_auth)) + { + return Some("eku"); + } + if info.not_before > now + 300 + || info.not_after <= now + || info.not_after > root.not_after + || info.not_before < root.not_before - 300 + { + return Some("dates"); + } + None +} + +/// 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 + ) +} + +/// 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()) { + 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::*; + + /// 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/src/validate.rs b/crates/core/src/validate.rs index d00e3f3..d9fb9ac 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r}; use crate::model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model, - Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, + Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost, }; /// One route file handed in by the caller (core does no I/O). @@ -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)] @@ -500,6 +502,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } }); + // The web UI's per-boot proof (docs/api.md, "Sign-in") may only ride on a host whose + // visitors were checked by forward-auth: edge strips client `Remote-*` headers only there. + let sends_proof = request_headers.iter().any(|r| { + matches!(r, HeaderRule::Set { value: HeaderValue::Secret(s), .. } if s.as_str() == UI_PROOF_SECRET) + }); + if sends_proof && auth != AuthMode::ForwardAuth { + errors.push(E::ProofWithoutSignIn { file: f() }); + } + if errors.len() != before { return None; } @@ -517,6 +528,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..584cd5d 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -72,6 +72,8 @@ fn options() -> CompileOptions { access_log: "/var/log/ianitor/access.log".into(), caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: Vec::new(), } } @@ -149,6 +151,29 @@ fn caddy_output_is_valid_json_with_servers() { assert_eq!(v["admin"]["disabled"], serde_json::json!(true)); } +#[test] +fn trusted_proxies_reach_both_engines_only_when_set() { + let edge = compile::edge(&model(false), &options()).unwrap(); + let caddy = compile::caddy(&model(false), &options()).unwrap(); + assert!(!edge.contains("trusted_proxies") && !caddy.contains("trusted_proxies")); + let mut o = options(); + o.trusted_proxies = vec!["127.0.0.1".parse().unwrap()]; + let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap(); + assert_eq!(cfg.trusted_proxies, vec!["127.0.0.1".to_owned()]); + let v: serde_json::Value = + serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap(); + let servers = v["apps"]["http"]["servers"].as_object().unwrap(); + let https = servers + .values() + .find(|s| s["listen"][0] == "0.0.0.0:443") + .unwrap(); + assert_eq!( + https["trusted_proxies"], + serde_json::json!({"source": "static", "ranges": ["127.0.0.1"]}) + ); + assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1)); +} + #[test] fn outputs_reference_secrets_by_name_only() { let edge = compile::edge(&model(false), &options()).unwrap(); @@ -277,3 +302,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/pki.rs b/crates/core/tests/pki.rs new file mode 100644 index 0000000..7fbbb73 --- /dev/null +++ b/crates/core/tests/pki.rs @@ -0,0 +1,359 @@ +// 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. + const { 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()); + } +} 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"); 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/src/admin.rs b/crates/edge/src/admin.rs index 9ffd085..73f6a88 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(); @@ -331,7 +335,10 @@ impl BackgroundService for RevocationPoller { loop { tokio::select! { _ = shutdown.changed() => return, - _ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(), + _ = tokio::time::sleep(Duration::from_secs(5)) => { + self.shared.poll_revocations(); + self.shared.poll_device_trust(); + } } } } diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 66d4ea5..a7292bb 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -121,13 +121,18 @@ 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(); https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); + https + .endpoints() + .set_pre_tls_callback(Arc::new(tls::HandshakeStart)); let mut http = Service::new( "ianitor http".to_owned(), diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 6b07927..f79e8cd 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -75,11 +75,46 @@ pub fn hostname(host_header: &str) -> String { name.to_ascii_lowercase() } -pub fn client_ip(session: &Session) -> Option { - session - .client_addr() - .and_then(|a| a.as_inet()) - .map(|a| a.ip()) +/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost +/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's +/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored. +/// An IPv4 address carried as IPv6 (`::ffff:127.0.0.1`) is the IPv4 address. +fn canonical(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), + v4 => v4, + } +} + +pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option { + let peer = canonical( + session + .client_addr() + .and_then(|a| a.as_inet()) + .map(|a| a.ip())?, + ); + let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip); + if !trusted_ip(&peer) { + return Some(peer); + } + let mut last = peer; + for v in session + .req_header() + .headers + .get_all("x-forwarded-for") + .iter() + .rev() + { + let Ok(s) = v.to_str() else { return Some(last) }; + for part in s.rsplit(',') { + match part.trim().parse::().map(canonical) { + Ok(ip) if trusted_ip(&ip) => last = ip, + Ok(ip) => return Some(ip), + Err(_) => return Some(last), + } + } + } + Some(last) } /// A response with an empty body, like Caddy's `static_response` and error responses. @@ -131,17 +166,33 @@ impl ProxyHttp for EdgeProxy { let rt = self.shared.current(); ctx.rt = Some(rt.clone()); ctx.host_header = host_header(session.req_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. + 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); }; ctx.host = Some(host.clone()); + 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?; + return Ok(true); + } + let mut shared_access = false; if !host.cfg.share_links { share::strip_any_token(session)?; } else { - let ip = client_ip(session); + let ip = client_ip(session, &rt.trusted_proxies); let revs = self.shared.revocations(); match share::handle( session, @@ -159,6 +210,16 @@ impl ProxyHttp for EdgeProxy { } } + if host.sends_proof { + // Control trusts Remote-* only next to its proof; a client never supplies either. + let req = session.req_header_mut(); + for name in ianitor_core::AUTHELIA_COPY_HEADERS + .iter() + .chain(&["X-Ianitor-Proof"]) + { + req.remove_header(*name); + } + } if host.cfg.forward_auth { let fa = rt.forward_auth.as_ref().ok_or_else(|| { Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured") @@ -172,7 +233,7 @@ impl ProxyHttp for EdgeProxy { // A valid share link stands in for the sign-in on its prefix. return self.after_auth(session, &host).await; } - let ip = client_ip(session).map(|i| i.to_string()); + let ip = client_ip(session, &rt.trusted_proxies).map(|i| i.to_string()); let outcome = match forward_auth::check( &self.connector, fa, @@ -296,7 +357,12 @@ impl ProxyHttp for EdgeProxy { } req.insert_header(header::HOST, ctx.host_header.as_str())?; // Forwarding headers are always edge's own; client-supplied values are replaced. - match client_ip(session) { + let trusted = ctx + .rt + .as_ref() + .map(|r| r.trusted_proxies.as_slice()) + .unwrap_or(&[]); + match client_ip(session, trusted) { Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?, None => { req.remove_header("X-Forwarded-For"); @@ -389,7 +455,13 @@ impl ProxyHttp for EdgeProxy { method: req.method.as_str(), path: req.uri.path(), status: session.response_written().map_or(0, |r| r.status.as_u16()), - remote_ip: client_ip(session).map(|i| truncate_ip(i).to_string()), + remote_ip: client_ip( + session, + ctx.rt + .as_ref() + .map_or(&[], |r| r.trusted_proxies.as_slice()), + ) + .map(|i| truncate_ip(i).to_string()), duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX), }); } @@ -412,6 +484,31 @@ 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. +fn has_allowed_device_cert(session: &Session, shared: &crate::shared::Shared) -> bool { + let Some(trust) = shared.devices.current() 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) } @@ -420,6 +517,14 @@ pub fn contains(hay: &[u8], needle: &[u8]) -> bool { mod tests { use super::*; + #[test] + fn an_ipv4_mapped_address_is_the_ipv4_address() { + let m = IpAddr::V6(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped()); + assert_eq!(canonical(m), IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)); + let v6 = IpAddr::V6(std::net::Ipv6Addr::LOCALHOST); + assert_eq!(canonical(v6), v6); + } + #[test] fn hostname_strips_port_and_case() { assert_eq!(hostname("App.Test:8443"), "app.test"); diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 952da7d..c6e0416 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -97,6 +97,9 @@ pub struct HostRt { pub response_ops: Vec, /// Values of the secrets this host injects; a response header containing one is dropped. pub secret_values: Vec>, + /// The host sends control's UI proof upstream: whatever the client says about who it is + /// (Remote-*) or about the proof is dropped first, with or without forward-auth. + pub sends_proof: bool, } pub struct ForwardAuthRt { @@ -118,6 +121,10 @@ 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>, + /// Peers whose X-Forwarded-For names the client. + pub trusted_proxies: Vec, /// 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, @@ -376,6 +383,9 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result) -> 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)?, @@ -429,15 +472,27 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result"), + message: format!("trusted_proxies: {s:?} is not an IP address"), + }) + }) + .collect::, _>>()?; Ok(Runtime { cfg, + trusted_proxies, hosts, forward_auth, access_log, file_certs, file_cert_expiry, share_key, + device_trust, sha256: String::new(), }) } diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index 9fc6d19..fb3a787 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -94,6 +94,12 @@ pub enum AdminError { pub struct Shared { current: ArcSwap, pub certs: Arc, + /// The listener's device-certificate check; its trust follows the runtime. + pub devices: Arc, + /// Serialises building the device trust with installing a runtime. + trust_lock: Mutex<()>, + /// Size and mtime of the device files when they were last read. + device_stamp: Mutex>, generation: AtomicU64, changed: tokio::sync::watch::Sender, trial: Mutex>, @@ -133,10 +139,15 @@ 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, + trust_lock: Mutex::new(()), + device_stamp: Mutex::new(None), generation: AtomicU64::new(1), changed, trial: Mutex::new(None), @@ -182,7 +193,21 @@ impl Shared { fn install(&self, rt: Arc) { self.certs.replace_files(rt.file_certs.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() + } + }; + // Trust and runtime change together (reload_device_trust checks the runtime under the + // same lock). + let guard = self.trust_lock.lock(); + self.devices.replace(trust); self.current.store(rt); + drop(guard); self.generation.fetch_add(1, Ordering::SeqCst); self.notify(); self.acme_wake.notify_one(); @@ -490,3 +515,78 @@ 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 { + // Built from the runtime that serves when it is installed: if a reload swapped the + // runtime meanwhile, build again from the new one (its host set may differ). + for _ in 0..5 { + let rt = self.current(); + let t = fresh_trust(&rt)?; + let n = t.as_ref().map_or(0, |t| t.allowed()); + let _g = self + .trust_lock + .lock() + .map_err(|_| "device lock".to_owned())?; + if Arc::ptr_eq(&rt, &self.current()) { + self.devices.replace(t); + log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed"); + return Ok(n); + } + } + Err("the config changed while the device certificates were read; try again".into()) + } + + /// The backstop for revocations (every 5 s, like the share deny list): re-read the device + /// files when they changed on disk, so a revocation counts even if control's nudge is lost. + pub fn poll_device_trust(&self) { + let rt = self.current(); + let Some(dc) = &rt.cfg.device_certs else { + return; + }; + let stamp = |p: &str| { + std::fs::metadata(p) + .ok() + .map(|m| (m.len(), m.modified().ok())) + }; + let now = (stamp(&dc.ca), stamp(&dc.allow)); + let changed = match self.device_stamp.lock() { + Ok(mut s) => { + let c = s.as_ref() != Some(&now); + *s = Some(now); + c + } + Err(_) => true, + }; + if changed && let Err(e) = self.reload_device_trust() { + // Fail closed: an unreadable list lets no device in until it is fixed. + log::error!(target: "ianitor::tls", "{e}; no device certificate is accepted until it is fixed"); + self.devices.replace(None); + } + } +} + +type FileStamp = Option<(u64, Option)>; +type DeviceStamp = (FileStamp, FileStamp); diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 68e17f5..51e72dc 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; @@ -47,11 +48,17 @@ impl CertStore { impl ResolvesServerCert for CertStore { fn resolve(&self, hello: ClientHello<'_>) -> Option> { // No SNI or an unknown name: no certificate, the handshake fails (as with Caddy). + // Whatever an earlier handshake on this thread left is not this one's. + let _ = take_hello_sni(); 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 +84,246 @@ 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()) +} + +/// Call before each TLS handshake, on the thread that creates its `ServerConnection` (edge +/// does it in a pre-TLS hook): a handshake that ended after the certificate resolver but +/// before the certificate request (failed, or resumed) leaves its name behind, and rustls asks +/// the verifier once more when the next connection is created, before that connection's +/// hello is read. A stale name there would turn off the TLS 1.2 transcript a client +/// certificate needs. +pub fn begin_handshake() { + let _ = take_hello_sni(); +} + +/// The pre-TLS hook that calls [`begin_handshake`]. +pub struct HandshakeStart; + +#[async_trait::async_trait] +impl pingora::listeners::PreTlsProcess for HandshakeStart { + async fn process( + &self, + _stream: &mut pingora::protocols::l4::stream::Stream, + ) -> pingora::Result<()> { + begin_handshake(); + Ok(()) + } +} + +/// 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 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)) + } +} + +/// 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 { + // 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] { + // 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()) +} + +/// 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/common/mod.rs b/crates/edge/tests/common/mod.rs index 7ba05b6..e4cf978 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -108,6 +108,10 @@ 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)>, + /// Peers whose X-Forwarded-For edge believes. + pub trusted_proxies: Vec, } impl Default for EdgeSpec<'_> { @@ -119,6 +123,8 @@ impl Default for EdgeSpec<'_> { log_level: "info", extra_args: Vec::new(), http_port: None, + files: Vec::new(), + trusted_proxies: Vec::new(), } } } @@ -165,6 +171,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(); } @@ -184,6 +193,8 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { access_log: dir.str("logs/access.log"), caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: spec.trusted_proxies.clone(), }; let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts); std::fs::write(dir.join("edge.json"), &config_text).unwrap(); diff --git a/crates/edge/tests/device_certs.rs b/crates/edge/tests/device_certs.rs new file mode 100644 index 0000000..28db0a9 --- /dev/null +++ b/crates/edge/tests/device_certs.rs @@ -0,0 +1,339 @@ +// 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_refused_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; + 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: + // 421, as Caddy answers once client certificates are configured. + let r = client::https( + edge.https, + "open.test", + edge.roots(), + &Req::get("locked.test", "/"), + ) + .await + .unwrap(); + assert_eq!(r.status, 421); + 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() + ); + } + + /// QC M2: a revocation must not depend on control's nudge reaching edge. Edge re-reads the + /// allow list by itself (like the share deny list), within 5 s. + #[tokio::test(flavor = "multi_thread")] + async fn edge_rereads_the_allow_list_by_itself() { + let echo = Echo::start("app").await; + let p = pki(); + let (phone, phone_pem) = device(&p, "phone"); + 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(), &phone, &req).await; + assert_eq!(r.unwrap().status, 200); + std::fs::write(edge.dir.join("certs/domi-devices.pem"), "").unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8); + loop { + let r = client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req) + .await; + if r.is_err() { + break; + } + assert!( + std::time::Instant::now() < deadline, + "edge still accepts a revoked device" + ); + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + } + + /// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that + /// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake. + #[tokio::test(flavor = "multi_thread")] + async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() { + use std::sync::Arc; + let echo = Echo::start("app").await; + let p = pki(); + let (phone, phone_pem) = device(&p, "phone"); + let edge = setup(&echo, &p, &[&phone_pem]).await; + let roots = edge.roots(); + let req = Req::get("locked.test", "/"); + let mut failures = Vec::new(); + let mut poisoned = 0; + for i in 0..40 { + let addr = edge.https; + let r2 = roots.clone(); + let failed = tokio::task::spawn_blocking(move || { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(r2) + .with_no_client_auth(); + cfg.alpn_protocols = vec![b"foo".to_vec()]; + let mut conn = rustls::ClientConnection::new( + Arc::new(cfg), + rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(), + ) + .unwrap(); + let mut sock = std::net::TcpStream::connect(addr).unwrap(); + sock.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + let mut r = Ok((0, 0)); + for _ in 0..5 { + r = conn.complete_io(&mut sock); + if r.is_err() || !conn.is_handshaking() { + break; + } + } + r.is_err() + }) + .await + .unwrap(); + if failed { + poisoned += 1; + } + match client::https_with_cert( + edge.https, + "locked.test", + roots.clone(), + &tls12(&phone), + &req, + ) + .await + { + Ok(r) if r.status == 200 => {} + other => failures.push(format!("{i}: {other:?}")), + } + } + eprintln!( + "QC poison handshakes that failed: {poisoned}/40; device failures: {}", + failures.len() + ); + assert_eq!(poisoned, 40, "the poison handshake must fail"); + assert!( + failures.is_empty(), + "{} of 40 TLS 1.2 device handshakes failed: {:?}", + failures.len(), + failures.first() + ); + } +} diff --git a/crates/edge/tests/qc_sni_stale.rs b/crates/edge/tests/qc_sni_stale.rs new file mode 100644 index 0000000..c2e23d4 --- /dev/null +++ b/crates/edge/tests/qc_sni_stale.rs @@ -0,0 +1,210 @@ +// 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 per-SNI certificate request (QC, fix round 1): the thread-local name that +//! DeviceVerifier::offer_client_auth reads, with in-memory rustls handshakes on ONE thread and +//! edge's own CertStore and DeviceVerifier. Each connection starts with +//! `tls::begin_handshake()`, as edge's pre-TLS hook does before Pingora creates the +//! `ServerConnection`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use ianitor_core::pki::{self, Intermediate}; +use ianitor_edge::tls::{CertStore, DeviceTrust, DeviceVerifier, certified_key}; +use rustls::{ClientConfig, ClientConnection, RootCertStore, ServerConfig, ServerConnection}; +use rustls_pki_types::pem::PemObject; +use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName}; + +fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 +} + +struct World { + server: Arc, + root_pem: String, + dev_chain: String, + dev_key: String, +} + +fn world() -> World { + 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 = Intermediate::new(&int_pem, k).unwrap(); + let store = Arc::new(CertStore::default()); + let mut files = HashMap::new(); + for h in ["open.test", "locked.test"] { + let s = pki::issue_server(&int, h, now()).unwrap(); + files.insert( + h.to_owned(), + Arc::new(certified_key(s.chain_pem.as_bytes(), s.key_pem.as_bytes()).unwrap()), + ); + } + store.replace_files(files); + let dev = pki::issue_device(&int, "phone", now()).unwrap(); + let trust = DeviceTrust::new( + int.cert_pem().as_bytes(), + dev.cert_pem.as_bytes(), + HashSet::from(["locked.test".to_owned()]), + ) + .unwrap(); + let v = Arc::new(DeviceVerifier::default()); + v.replace(Some(Arc::new(trust))); + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut sc = ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS12, &rustls::version::TLS13]) + .unwrap() + .with_client_cert_verifier(v) + .with_cert_resolver(store); + sc.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + World { + server: Arc::new(sc), + root_pem: root, + dev_chain: dev.chain_pem, + dev_key: dev.key_pem, + } +} + +fn client(w: &World, tls12_only: bool, cert: bool, alpn: &[&[u8]]) -> Arc { + let mut roots = RootCertStore::empty(); + roots + .add(CertificateDer::from_pem_slice(w.root_pem.as_bytes()).unwrap()) + .unwrap(); + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let versions: &[&rustls::SupportedProtocolVersion] = if tls12_only { + &[&rustls::version::TLS12] + } else { + &[&rustls::version::TLS13, &rustls::version::TLS12] + }; + let b = ClientConfig::builder_with_provider(provider) + .with_protocol_versions(versions) + .unwrap() + .with_root_certificates(roots); + let mut c = if cert { + let chain: Vec> = + CertificateDer::pem_slice_iter(w.dev_chain.as_bytes()) + .collect::>() + .unwrap(); + let key = PrivateKeyDer::from_pem_slice(w.dev_key.as_bytes()).unwrap(); + b.with_client_auth_cert(chain, key).unwrap() + } else { + b.with_no_client_auth() + }; + c.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect(); + Arc::new(c) +} + +/// Returns whether the server saw a client certificate. +fn handshake(sc: &Arc, cc: &Arc, name: &str) -> Result { + ianitor_edge::tls::begin_handshake(); + let mut server = ServerConnection::new(sc.clone()).unwrap(); + let mut client = + ClientConnection::new(cc.clone(), ServerName::try_from(name.to_owned()).unwrap()).unwrap(); + for _ in 0..30 { + let mut buf = Vec::new(); + while client.wants_write() { + client.write_tls(&mut buf).unwrap(); + } + let mut r = &buf[..]; + while !r.is_empty() { + server.read_tls(&mut r).unwrap(); + } + server + .process_new_packets() + .map_err(|e| format!("server: {e}"))?; + let mut buf = Vec::new(); + while server.wants_write() { + server.write_tls(&mut buf).unwrap(); + } + let mut r = &buf[..]; + while !r.is_empty() { + client.read_tls(&mut r).unwrap(); + } + client + .process_new_packets() + .map_err(|e| format!("client: {e}"))?; + if !client.is_handshaking() && !server.is_handshaking() && !server.wants_write() { + return Ok(server.peer_certificates().is_some()); + } + } + Err("handshake did not finish".into()) +} + +#[test] +fn baseline_tls12_device_handshake_on_a_fresh_thread() { + let w = world(); + let got = handshake( + &w.server, + &client(&w, true, true, &[b"http/1.1"]), + "locked.test", + ); + assert_eq!(got, Ok(true), "baseline"); +} + +#[test] +fn after_a_failed_handshake_on_this_thread_a_tls12_device_still_gets_in() { + let w = world(); + // A client offers only an ALPN the server does not speak: rustls fails after the + // certificate resolver ran (SNI set) and before offer_client_auth (SNI never taken). + let bad = handshake(&w.server, &client(&w, false, false, &[b"foo"]), "open.test"); + assert!(bad.is_err(), "poison handshake should fail: {bad:?}"); + let got = handshake( + &w.server, + &client(&w, true, true, &[b"http/1.1"]), + "locked.test", + ); + assert_eq!( + got, + Ok(true), + "TLS 1.2 device after a stale SNI on this thread" + ); +} + +#[test] +fn after_a_resumed_handshake_on_this_thread_a_tls12_device_still_gets_in() { + let w = world(); + let c13 = client(&w, false, false, &[b"http/1.1"]); + assert_eq!(handshake(&w.server, &c13, "open.test"), Ok(false)); + // Same client config: resumes (no certificate request, so the SNI is never taken). + assert_eq!(handshake(&w.server, &c13, "open.test"), Ok(false)); + let got = handshake( + &w.server, + &client(&w, true, true, &[b"http/1.1"]), + "locked.test", + ); + assert_eq!( + got, + Ok(true), + "TLS 1.2 device after a resumption on this thread" + ); +} + +#[test] +fn a_stale_device_name_never_opens_a_plain_host_without_a_request() { + // The fail-open direction: stale "locked.test", then a TLS 1.3 device host handshake + // without a cert must still fail. + let w = world(); + let bad = handshake( + &w.server, + &client(&w, false, false, &[b"foo"]), + "locked.test", + ); + assert!(bad.is_err()); + let r = handshake( + &w.server, + &client(&w, false, false, &[b"http/1.1"]), + "locked.test", + ); + assert!( + r.is_err(), + "no-cert handshake to the device host must fail: {r:?}" + ); +} diff --git a/crates/edge/tests/trusted_proxies.rs b/crates/edge/tests/trusted_proxies.rs new file mode 100644 index 0000000..51782be --- /dev/null +++ b/crates/edge/tests/trusted_proxies.rs @@ -0,0 +1,84 @@ +// 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/. + +//! `trusted_proxies` (off by default): behind a proxy on loopback (Caddy beside Ianitor), the +//! client named in X-Forwarded-For is the one edge forwards and logs; without the option a +//! client-sent X-Forwarded-For is ignored. + +#![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::{EdgeSpec, host_file, start}; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + + async fn forwarded_for(trusted: Vec, xff: &str) -> (String, String) { + let echo = Echo::start("app").await; + let edge = start(EdgeSpec { + hosts: vec![host_file( + "app.test", + &format!( + "upstreams = [\"{}\"]\naccess_log = \"truncated\"\n", + echo.url() + ), + )], + trusted_proxies: trusted, + ..Default::default() + }); + let r = client::https( + edge.https, + "app.test", + edge.roots(), + &Req::get("app.test", "/").header("x-forwarded-for", xff), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); + let seen = echo.proxied(); + let got = String::from_utf8(seen[0].header("x-forwarded-for").unwrap().to_vec()).unwrap(); + // The access line is written after the response; give it a moment. + let mut log = String::new(); + for _ in 0..50 { + log = edge.access_log(); + if log.contains("app.test") { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + (got, log) + } + + #[tokio::test(flavor = "multi_thread")] + async fn without_the_option_a_client_sent_forwarded_for_is_ignored() { + let (xff, log) = forwarded_for(Vec::new(), "203.0.113.7").await; + assert_eq!(xff, "127.0.0.1"); + assert!(!log.contains("203.0.113"), "{log}"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_trusted_proxy_names_the_client_rightmost_first() { + // The leftmost entry is what a client could forge; the rightmost untrusted one counts. + let (xff, log) = forwarded_for( + vec!["127.0.0.1".parse().unwrap()], + "198.51.100.9, 203.0.113.7, 127.0.0.1", + ) + .await; + assert_eq!(xff, "203.0.113.7"); + assert!(log.contains("203.0.113.0"), "the real /24 is logged: {log}"); + assert!(!log.contains("198.51.100"), "{log}"); + } +} diff --git a/deploy/nixos/module.nix b/deploy/nixos/module.nix new file mode 100644 index 0000000..34699d1 --- /dev/null +++ b/deploy/nixos/module.nix @@ -0,0 +1,435 @@ +# 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/. + +# services.ianitor: ianitor-edge (the only public listener), ianitor-control (loopback), +# caddy-fallback (the same routes as Caddy JSON), the engine-select unit, the per-boot UI proof, +# and a polkit rule that lets control start and stop exactly the two engine units. While Caddy +# serves, control loads changes into it through its admin socket (/run/caddy-fallback/admin.sock, +# group ianitor, 0660). +# +# Secrets never enter the Nix store: every credential is a *path string* to a file outside the +# store (sops-nix, agenix, Custos provisioning, ...), loaded with systemd LoadCredential; an +# assertion refuses any /nix/store path. +self: +{ config, lib, pkgs, ... }: + +let + cfg = config.services.ianitor; + inherit (lib) mkOption mkEnableOption mkIf types; + pkg = cfg.package; + stateRoot = "/var/lib/ianitor"; + runProof = "/run/ianitor-proof"; + toml = pkgs.formats.toml { }; + + isStore = p: lib.hasPrefix builtins.storeDir (toString p); + # Every credential file the units load, by credential name. + edgeCreds = + cfg.credentials + // lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; }; + controlCreds = + lib.optionalAttrs (cfg.shareLinkKeyFile != null) { "share-link-key" = cfg.shareLinkKeyFile; } + // lib.optionalAttrs (cfg.pki.enable) { "pki-password" = cfg.pki.passwordFile; } + // lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push = cfg.routes.pushCredentialFile; }; + userCreds = edgeCreds // controlCreds; + loadCreds = creds: lib.mapAttrsToList (n: p: "${n}:${p}") creds; + + compile = { + http_listen = cfg.edge.httpListen; + https_listen = cfg.edge.httpsListen; + cert_dir = "${stateRoot}/certs"; + state_dir = "${stateRoot}/edge-state"; + access_log = "/var/log/ianitor/access.log"; + caddy_credentials_dir = "/run/credentials/caddy-fallback.service"; + trusted_proxies = cfg.edge.trustedProxies; + }; + + controlToml = toml.generate "control.toml" ( + { + listen = cfg.control.listen; + state_dir = "${stateRoot}/control"; + git = "${pkgs.git}/bin/git"; + watch_secs = cfg.watchSeconds; + routes = + { + repo = "${stateRoot}/control/routes.git"; + remote_name = cfg.routes.remoteName; + push_username = cfg.routes.pushUsername; + } + // lib.optionalAttrs (cfg.routes.remote != null) { remote = cfg.routes.remote; } + // lib.optionalAttrs (cfg.routes.pushCredentialFile != null) { push_credential = "push"; }; + edge = { + config = "${stateRoot}/edge/edge.json"; + admin_socket = "/run/ianitor-edge/admin.sock"; + share_revocations = "${stateRoot}/edge/share-revocations.json"; + }; + caddy.config = "${stateRoot}/caddy/caddy.json"; + inherit compile; + # Caddy keeps its own storage and access log; the listeners and certificates are the same. + compile_caddy = compile // { + state_dir = "${stateRoot}/caddy-state"; + access_log = "/var/log/ianitor/caddy-access.log"; + # Changes keep working under Caddy: control loads them through this socket. + caddy_admin_socket = "/run/caddy-fallback/admin.sock"; + }; + ui = + { + proof_credential = "ui-proof"; + static_dir = "${pkg}/share/ianitor/web"; + } + // lib.optionalAttrs (cfg.ui.hostname != null) { hostname = cfg.ui.hostname; } + // lib.optionalAttrs (cfg.ui.logoutUrl != null) { logout_url = cfg.ui.logoutUrl; }; + engine = { + file = "${stateRoot}/engine"; + systemctl = "${config.systemd.package}/bin/systemctl"; + }; + } + // lib.optionalAttrs cfg.pki.enable { + pki = { + root_cert = toString cfg.pki.rootCertificate; + password_credential = "pki-password"; + }; + } + ); + + hardening = { + NoNewPrivileges = true; + PrivateTmp = true; + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + ProtectClock = true; + ProtectHostname = true; + RestrictSUIDSGID = true; + RestrictNamespaces = true; + LockPersonality = true; + MemoryDenyWriteExecute = true; + SystemCallArchitectures = "native"; + RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ]; + UMask = "0027"; + }; +in +{ + options.services.ianitor = { + enable = mkEnableOption "Ianitor Domi, the reverse proxy on Pingora with its control plane"; + + package = mkOption { + type = types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.ianitor; + defaultText = lib.literalExpression "ianitor.packages.\${system}.ianitor"; + description = "The release build (test hooks off)."; + }; + + caddyPackage = mkOption { + type = types.package; + # The Caddy the differential tests run against (Ianitor's own pinned nixpkgs), not the host's: + # the Caddy JSON is only proven equal for that version. + default = self.inputs.nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system}.caddy; + defaultText = lib.literalExpression "ianitor.inputs.nixpkgs.legacyPackages..caddy"; + description = "The Caddy that runs the fallback."; + }; + + edge = { + httpListen = mkOption { + type = types.str; + default = "0.0.0.0:80"; + description = "Plain-HTTP listener (ACME HTTP-01, redirects). The only public listeners are edge's."; + }; + httpsListen = mkOption { + type = types.str; + default = "0.0.0.0:443"; + description = "TLS listener serving every host by SNI."; + }; + openFirewall = mkOption { + type = types.bool; + default = false; + description = "Open edge's two ports in the firewall."; + }; + trustedProxies = mkOption { + type = types.listOf types.str; + default = [ ]; + example = [ "127.0.0.1" ]; + description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md)."; + }; + }; + + control.listen = mkOption { + type = types.str; + default = "127.0.0.1:7878"; + description = "The API and UI. Loopback only (an assertion refuses anything else)."; + }; + + watchSeconds = mkOption { + type = types.ints.between 1 3600; + default = 60; + description = "How long the health watch after an apply lasts."; + }; + + defaultEngine = mkOption { + type = types.enum [ "pingora" "caddy" ]; + default = "pingora"; + description = "The engine at first boot; afterwards the UI's choice in ${stateRoot}/engine."; + }; + + routes = { + remote = mkOption { + type = types.nullOr types.str; + default = null; + example = "https://gitea.example/mnovak/ianitor-routes.git"; + description = "Where kept changes are pushed."; + }; + remoteName = mkOption { + type = types.str; + default = "Gitea"; + description = "Shown in the UI."; + }; + pushUsername = mkOption { + type = types.str; + default = "ianitor"; + description = "User name for HTTPS pushes."; + }; + pushCredentialFile = mkOption { + type = types.nullOr types.str; + default = null; + description = "File (outside the Nix store) holding the push token."; + }; + }; + + shareLinkKeyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = "File (outside the Nix store) with the share-link key, at least 32 characters. Without it, share links are off."; + }; + + credentials = mkOption { + type = types.attrsOf types.str; + default = { }; + example = { wiki_token = "/run/secrets/wiki-token"; }; + description = "Secrets that header rules reference, by name: files outside the Nix store, loaded into edge and caddy-fallback with LoadCredential."; + }; + + pki = { + enable = mkEnableOption "the Domi CA (docs/pki.md)"; + rootCertificate = mkOption { + type = types.path; + description = "The Domi root certificate (public; it may be in the store). The root key never comes to the server."; + }; + passwordFile = mkOption { + type = types.str; + description = "File (outside the Nix store) with the password that encrypts the intermediate and device keys at rest."; + }; + }; + + ui = { + hostname = mkOption { + type = types.nullOr types.str; + default = null; + example = "ianitor.example"; + description = "The admin host edge serves the UI on (a host in the routes repository with forward-auth and the X-Ianitor-Proof rule, docs/api.md)."; + }; + logoutUrl = mkOption { + type = types.nullOr types.str; + default = null; + example = "https://auth.example/logout"; + description = "Authelia's logout address, for the UI's Sign out."; + }; + }; + }; + + config = mkIf cfg.enable { + assertions = + [ + { + assertion = lib.any (p: lib.hasPrefix p cfg.control.listen) [ "127." "[::1]:" "localhost:" ]; + message = "services.ianitor.control.listen must be a loopback address; only ianitor-edge binds public ports."; + } + ] + ++ lib.mapAttrsToList (n: p: { + assertion = !isStore p; + message = "services.ianitor: the credential ${n} points into the Nix store (${toString p}); secrets must come from systemd credentials, never the store."; + }) userCreds; + + users.groups.ianitor = { }; + # Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it. + users.groups.ianitor-caddy-admin = { }; + users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; }; + users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; }; + users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; }; + + systemd.tmpfiles.rules = [ + "d ${stateRoot} 0755 ianitor-control ianitor - -" + "d ${stateRoot}/control 0700 ianitor-control ianitor - -" + "d ${stateRoot}/edge 0750 ianitor-control ianitor - -" + "d ${stateRoot}/caddy 0750 ianitor-control ianitor - -" + "d ${stateRoot}/certs 0750 ianitor-control ianitor - -" + "d ${stateRoot}/edge-state 0700 ianitor-edge ianitor - -" + "d ${stateRoot}/caddy-state 0700 caddy-fallback ianitor - -" + "f ${stateRoot}/engine 0644 ianitor-control ianitor - ${cfg.defaultEngine}" + "d /var/log/ianitor 0770 ianitor-edge ianitor - -" + ]; + + environment.systemPackages = [ pkg ]; + # The non-secret config, so the CLI (token, pki) finds it: --config /etc/ianitor/control.toml. + environment.etc."ianitor/control.toml".source = controlToml; + + # A new secret every boot, readable by root only; edge and control load it as a credential. + systemd.services.ianitor-ui-proof = { + description = "Ianitor: per-boot proof for the admin host"; + before = [ "ianitor-edge.service" "ianitor-control.service" "caddy-fallback.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + RuntimeDirectory = "ianitor-proof"; + RuntimeDirectoryMode = "0700"; + RuntimeDirectoryPreserve = true; + UMask = "0077"; + }; + script = '' + head -c 32 /dev/urandom | ${pkgs.coreutils}/bin/base64 -w0 > ${runProof}/ui-proof + ''; + }; + + systemd.services.ianitor-control = { + description = "Ianitor control (API and UI on loopback)"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + environment.IANITOR_LOG = "info"; + serviceConfig = hardening // { + User = "ianitor-control"; + Group = "ianitor"; + ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}"; + # After every stop, a crash included: a trial still loaded into Caddy goes back to the + # last good caddy.json at once (ianitor_control::caddy_guard). It runs after a crash + # too, so no separate OnFailure= unit is needed. + ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}"; + LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; + ReadWritePaths = [ stateRoot ]; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + + systemd.services.ianitor-edge = { + description = "Ianitor edge (Pingora)"; + # Never give up restarting the only public listener. + startLimitIntervalSec = 0; + after = [ "network-online.target" "ianitor-control.service" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + conflicts = [ "caddy-fallback.service" ]; + environment.IANITOR_LOG = "info"; + serviceConfig = hardening // { + User = "ianitor-edge"; + Group = "ianitor"; + ExecStart = lib.concatStringsSep " " [ + "${pkg}/bin/ianitor-edge" + "--config ${stateRoot}/edge/edge.json" + "--admin-socket /run/ianitor-edge/admin.sock" + "--share-revocations ${stateRoot}/edge/share-revocations.json" + ]; + LoadCredential = loadCreds edgeCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; + RuntimeDirectory = "ianitor-edge"; + RuntimeDirectoryMode = "0750"; + ReadWritePaths = [ "${stateRoot}/edge-state" "/var/log/ianitor" ]; + AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; + CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; + # The first start may come before control has written edge.json. + Restart = "always"; + RestartSec = 2; + # The Pingora runtime needs W^X off for nothing; keep the default hardening. + LimitNOFILE = 65536; + }; + }; + + systemd.services.caddy-fallback = { + description = "Ianitor fallback: Caddy with the same routes"; + after = [ "network-online.target" "ianitor-ui-proof.service" ]; + wants = [ "network-online.target" ]; + requires = [ "ianitor-ui-proof.service" ]; + conflicts = [ "ianitor-edge.service" ]; + environment = { + XDG_DATA_HOME = "${stateRoot}/caddy-state"; + XDG_CONFIG_HOME = "${stateRoot}/caddy-state"; + HOME = "${stateRoot}/caddy-state"; + }; + serviceConfig = hardening // { + User = "caddy-fallback"; + # The admin socket (and its runtime directory) belong to this group; "ianitor" for the + # certificates and logs. + Group = "ianitor-caddy-admin"; + SupplementaryGroups = [ "ianitor" ]; + ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json"; + LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ]; + RuntimeDirectory = "caddy-fallback"; + RuntimeDirectoryMode = "0750"; + ReadWritePaths = [ "${stateRoot}/caddy-state" "/var/log/ianitor" ]; + AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; + CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; + # Go needs W^X for its runtime on some platforms. + MemoryDenyWriteExecute = false; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + + # The deadline of a trial under Caddy, outside control (a hung control included): once a + # second it reverts a trial past its deadline to the last good caddy.json. Runs with Caddy. + systemd.services.ianitor-caddy-guard = { + description = "Ianitor: deadline for changes tried on Caddy"; + partOf = [ "caddy-fallback.service" ]; + after = [ "caddy-fallback.service" ]; + wantedBy = [ "caddy-fallback.service" ]; + environment.IANITOR_LOG = "info"; + serviceConfig = hardening // { + User = "ianitor-control"; + Group = "ianitor"; + ExecStart = "${pkg}/bin/ianitor-control caddy-guard --config ${controlToml}"; + ReadWritePaths = [ "${stateRoot}/control" ]; + Restart = "always"; + RestartSec = 1; + }; + }; + + # At boot: start the engine the UI chose last (ROADMAP §3). + systemd.services.ianitor-engine-select = { + description = "Ianitor: start the chosen engine"; + wantedBy = [ "multi-user.target" ]; + after = [ "ianitor-control.service" "systemd-tmpfiles-setup.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = '' + engine=$(cat ${stateRoot}/engine 2>/dev/null || echo ${cfg.defaultEngine}) + case "$engine" in + caddy) exec ${config.systemd.package}/bin/systemctl start --no-block caddy-fallback.service ;; + *) exec ${config.systemd.package}/bin/systemctl start --no-block ianitor-edge.service ;; + esac + ''; + }; + + # Control may start and stop exactly the two engine units, nothing else. (polkit is new on a + # server that had no other use for it.) + security.polkit.enable = true; + security.polkit.extraConfig = '' + polkit.addRule(function (action, subject) { + if (action.id == "org.freedesktop.systemd1.manage-units" && subject.user == "ianitor-control") { + var unit = action.lookup("unit"); + var verb = action.lookup("verb"); + if ((unit == "ianitor-edge.service" || unit == "caddy-fallback.service") && + (verb == "start" || verb == "stop")) { + return polkit.Result.YES; + } + } + }); + ''; + + networking.firewall.allowedTCPPorts = mkIf cfg.edge.openFirewall ( + map (a: lib.toInt (lib.last (lib.splitString ":" a))) [ cfg.edge.httpListen cfg.edge.httpsListen ] + ); + }; +} diff --git a/deploy/nixos/package.nix b/deploy/nixos/package.nix new file mode 100644 index 0000000..65aae88 --- /dev/null +++ b/deploy/nixos/package.nix @@ -0,0 +1,54 @@ +# 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 release build: ianitor-edge and ianitor-control with --no-default-features, so the +# crash and write-failure test hooks (IANITOR_TEST_*) are not in the binaries. The built web UI +# goes to share/ianitor/web, where control serves it. +{ lib, rustPlatform, cmake, ianitor-web }: + +rustPlatform.buildRustPackage { + pname = "ianitor"; + version = "0.1.0"; + + src = lib.fileset.toSource { + root = ../..; + fileset = lib.fileset.unions [ + ../../Cargo.toml + ../../Cargo.lock + ../../crates + ../../tests/diff + ../../tests/support + ]; + }; + + cargoLock.lockFile = ../../Cargo.lock; + # libz-ng-sys (Pingora's compression) builds zlib-ng with CMake. + nativeBuildInputs = [ cmake ]; + dontUseCmakeConfigure = true; + cargoBuildFlags = [ "-p" "ianitor-edge" "-p" "ianitor-control" ]; + buildNoDefaultFeatures = true; + # The test suites need Caddy, Pebble and loopback servers; they run in `cargo test` and in + # the NixOS VM tests, not inside this sandboxed build. + doCheck = false; + + postInstall = '' + mkdir -p $out/share/ianitor + cp -r ${ianitor-web} $out/share/ianitor/web + ''; + + # The release binaries must not carry the test hooks. + postFixup = '' + if grep -q IANITOR_TEST_CRASH_AT $out/bin/ianitor-control; then + echo "the release ianitor-control still has the test hooks" >&2 + exit 1 + fi + ''; + + meta = { + description = "Ianitor Domi: a reverse proxy on Pingora with a small Domi CA, a web UI and an API"; + license = lib.licenses.mpl20; + mainProgram = "ianitor-control"; + platforms = lib.platforms.linux; + }; +} diff --git a/deploy/nixos/tests/default.nix b/deploy/nixos/tests/default.nix new file mode 100644 index 0000000..f239d08 --- /dev/null +++ b/deploy/nixos/tests/default.nix @@ -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/. + +# NixOS VM tests, ROADMAP §5 layer 4: a failed apply auto-reverts; switching to Caddy and back +# keeps a host reachable; intermediate renewal with a test root; control unreachable from +# outside loopback. They need KVM (`nix flake check` on Linux with /dev/kvm). +{ pkgs, self }: + +let + ianitor = self.packages.${pkgs.stdenv.hostPlatform.system}.ianitor; + + # A test root made at build time with the release binary, as on the offline machine. A test + # root may live in the store; a real one never does (docs/pki.md). + testRoot = pkgs.runCommand "ianitor-test-root" { } '' + mkdir -p $out + printf 'test-root-passphrase-0123' > pass + ${ianitor}/bin/ianitor-control ca init --out $out --passphrase-file pass + cp pass $out/passphrase + ''; + + # Secrets for the VM, written by tmpfiles to paths outside the store (the module refuses + # store paths for credentials). Test values only. + secrets = [ + "d /var/lib/ianitor-secrets 0700 root root - -" + "f /var/lib/ianitor-secrets/share-link-key 0600 root root - vm-test-share-link-key-0123456789abcdef0123" + "f /var/lib/ianitor-secrets/pki-password 0600 root root - vm-test-pki-password-0123456789" + ]; + + server = + { ... }: + { + imports = [ self.nixosModules.ianitor ]; + virtualisation.memorySize = 2048; + networking.firewall.enable = true; + services.ianitor = { + enable = true; + package = ianitor; + edge.openFirewall = true; + watchSeconds = 8; + shareLinkKeyFile = "/var/lib/ianitor-secrets/share-link-key"; + pki = { + enable = true; + rootCertificate = "${testRoot}/domi-root.crt"; + passwordFile = "/var/lib/ianitor-secrets/pki-password"; + }; + }; + systemd.tmpfiles.rules = secrets; + # A test upstream. + systemd.services.upstream = { + wantedBy = [ "multi-user.target" ]; + serviceConfig.ExecStart = "${pkgs.python3}/bin/python3 -m http.server 8000 --bind 127.0.0.1 --directory /etc"; + }; + environment.systemPackages = [ pkgs.curl pkgs.jq pkgs.openssl ]; + }; + + # Python helpers shared by the test scripts. + helpers = '' + import json, shlex, time + + def setup(m): + m.wait_for_unit("ianitor-control.service") + m.wait_for_unit("ianitor-engine-select.service") + m.wait_until_succeeds("test -S /run/ianitor-edge/admin.sock") + m.wait_for_unit("upstream.service") + return m.succeed( + "runuser -u ianitor-control -- ianitor-control token create --name vm --config /etc/ianitor/control.toml" + ).strip() + + def api(m, token, method, path, body=None, ok=True): + cmd = f"curl -s -X {method} -H 'Authorization: Bearer {token}' http://127.0.0.1:7878/api/v1{path}" + if body is not None: + cmd += " -H 'Content-Type: application/json' -d " + shlex.quote(json.dumps(body)) + out = m.succeed(cmd) + return json.loads(out) if out.strip() else {} + + def wait_apply(m, token, apply_id): + for _ in range(120): + a = api(m, token, "GET", f"/applies/{apply_id}") + if a.get("state") in ("kept", "reverted", "failed", "needs_attention"): + return a + time.sleep(1) + raise Exception(f"apply {apply_id} did not finish") + + def install_intermediate(m, token): + r = api(m, token, "POST", "/certs/intermediate/renewal", {}) + m.succeed("install -d -m 0700 /root/offline") + m.succeed("cat > /root/offline/req.csr << 'EOF'\n" + r["csr_pem"] + "EOF") + # The offline step (docs/pki.md), with the test root. + m.succeed( + "ianitor-control ca sign --root ${testRoot} --csr /root/offline/req.csr " + "--out /root/offline/int.crt --yes --passphrase-file ${testRoot}/passphrase" + ) + m.succeed("install -m 0644 /root/offline/int.crt /tmp/int.crt") + m.succeed("runuser -u ianitor-control -- ianitor-control pki install /tmp/int.crt --config /etc/ianitor/control.toml") + for _ in range(30): + if api(m, token, "GET", f"/pki-requests/{r['request_id']}")["state"] == "approved": + return + time.sleep(1) + raise Exception("the intermediate was not installed") + + def visit(m, host): + return m.succeed( + f"curl -s -o /dev/null -w '%{{http_code}}' --cacert ${testRoot}/domi-root.crt " + f"--resolve {host}:443:127.0.0.1 https://{host}/" + ).strip() + ''; + + test = + name: script: + pkgs.testers.runNixOSTest { + name = "ianitor-${name}"; + nodes.server = server; + testScript = helpers + script; + }; +in +{ + vm-apply-reverts = test "apply-reverts" '' + start_all() + t = setup(server) + install_intermediate(server, t) + before = server.succeed("sha256sum /var/lib/ianitor/edge/edge.json") + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "broken.test", "upstreams": ["http://127.0.0.1:9"], "tls": "domi", "auth": "none", + "health_check": {"path": "/", "interval_secs": 1}}}) + a = wait_apply(server, t, r["apply"]["id"]) + assert a["state"] == "reverted", a + # edge and its file never left the last good config. + assert server.succeed("sha256sum /var/lib/ianitor/edge/edge.json") == before + server.fail("grep -q broken.test /var/lib/ianitor/edge/edge.json") + # The routes repository holds the change and its revert. + history = server.succeed("runuser -u ianitor-control -- git -C /var/lib/ianitor/control/routes.git log --oneline") + assert "broken.test" in history, history + ''; + + vm-engine-switch = test "engine-switch" '' + start_all() + t = setup(server) + install_intermediate(server, t) + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}}) + assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" + assert visit(server, "app.test") == "200" + + api(server, t, "POST", "/engine", {"target": "caddy"}) + server.wait_until_succeeds( + f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"caddy\" and .state == \"running\"'" + ) + server.wait_for_unit("caddy-fallback.service") + server.fail("systemctl is-active ianitor-edge.service") + assert server.succeed("cat /var/lib/ianitor/engine").strip() == "caddy" + server.wait_until_succeeds("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve app.test:443:127.0.0.1 https://app.test/ | grep -q 200") + + # Changes keep working while Caddy serves: loaded through its admin socket and watched. + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "two.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}}) + assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" + server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200") + + # The trial's deadline under Caddy does not depend on control (fix round 2, B2): the guard + # runs with Caddy, only control may use Caddy's admin socket, and a control killed during + # the watch leaves Caddy on the last good config (ExecStopPost=caddy-revert). + server.succeed("systemctl is-active ianitor-caddy-guard.service") + server.fail("runuser -u ianitor-edge -- test -w /run/caddy-fallback/admin.sock") + server.succeed("runuser -u ianitor-control -- test -w /run/caddy-fallback/admin.sock") + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "three.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}}) + three = r["apply"]["id"] + for _ in range(60): + if api(server, t, "GET", f"/applies/{three}").get("state") == "watching": + break + time.sleep(0.5) + assert visit(server, "three.test") == "200", "the trial serves" + server.succeed("systemctl kill --signal=KILL ianitor-control.service") + server.wait_until_fails("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve three.test:443:127.0.0.1 https://three.test/ | grep -q 200", timeout=10) + server.wait_for_unit("ianitor-control.service") + server.wait_until_succeeds(f"curl -sf -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/overview") + assert wait_apply(server, t, three)["state"] == "reverted" + assert visit(server, "two.test") == "200" + + api(server, t, "POST", "/engine", {"target": "pingora"}) + server.wait_until_succeeds( + f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'" + ) + server.wait_for_unit("ianitor-edge.service") + server.fail("systemctl is-active caddy-fallback.service") + assert visit(server, "app.test") == "200" + + # The choice survives a reboot (engine-select). + api(server, t, "POST", "/engine", {"target": "caddy"}) + server.wait_until_succeeds("grep -qx caddy /var/lib/ianitor/engine") + server.wait_for_unit("caddy-fallback.service") + server.shutdown() + server.start() + server.wait_for_unit("ianitor-engine-select.service") + server.wait_for_unit("caddy-fallback.service") + server.wait_until_succeeds("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve app.test:443:127.0.0.1 https://app.test/ | grep -q 200") + + # polkit lets control manage exactly the two engine units, nothing else. + server.fail("runuser -u ianitor-control -- systemctl --no-ask-password restart upstream.service") + server.fail("runuser -u ianitor-control -- systemctl --no-ask-password stop ianitor-control.service") + ''; + + vm-intermediate-renewal = test "intermediate-renewal" '' + start_all() + t = setup(server) + ov = api(server, t, "GET", "/overview") + assert ov["intermediate"]["state"] == "missing", ov["intermediate"] + install_intermediate(server, t) + first = server.succeed("cat /var/lib/ianitor/control/pki/intermediate.crt") + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}}) + assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" + assert visit(server, "app.test") == "200" + # Renew: a new intermediate, the host certificate reissued, still trusted by the root. + install_intermediate(server, t) + assert server.succeed("cat /var/lib/ianitor/control/pki/intermediate.crt") != first + server.wait_until_succeeds( + "openssl verify -CAfile ${testRoot}/domi-root.crt -untrusted /var/lib/ianitor/control/pki/intermediate.crt " + "<(openssl x509 -in /var/lib/ianitor/certs/app.test.crt) | grep -q OK" + ) + assert visit(server, "app.test") == "200" + # The intermediate key is encrypted at rest, and no root key is on the server. + server.succeed("grep -q 'IANITOR ENCRYPTED' /var/lib/ianitor/control/pki/intermediate.key") + server.fail("grep -rqs 'BEGIN PRIVATE KEY' /var/lib/ianitor/control") + server.fail("find /var/lib/ianitor -name 'domi-root.key' | grep -q .") + ''; + + vm-control-loopback = pkgs.testers.runNixOSTest { + name = "ianitor-control-loopback"; + nodes.server = server; + nodes.client = { environment.systemPackages = [ pkgs.curl ]; }; + testScript = helpers + '' + start_all() + setup(server) + client.wait_for_unit("multi-user.target") + # Only edge listens beyond loopback. + listen = server.succeed("ss -Hltn") + assert "127.0.0.1:7878" in listen, listen + assert "0.0.0.0:7878" not in listen and "*:7878" not in listen and "[::]:7878" not in listen, listen + client.fail("curl -s -m 5 http://server:7878/api/v1/overview") + # Edge answers from outside (404 for an unknown host). + code = client.succeed("curl -s -o /dev/null -w '%{http_code}' -m 10 http://server/").strip() + assert code == "404", code + ''; + }; +} diff --git a/deploy/nixos/web.nix b/deploy/nixos/web.nix new file mode 100644 index 0000000..f42e8a5 --- /dev/null +++ b/deploy/nixos/web.nix @@ -0,0 +1,44 @@ +# 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 web UI (apps/web with packages/ui), built with pnpm from the lockfile. No outside +# requests at runtime: the fonts are bundled. +{ lib, stdenv, nodejs_22, pnpm_11, fetchPnpmDeps, pnpmConfigHook }: + +stdenv.mkDerivation (finalAttrs: { + pname = "ianitor-web"; + version = "0.1.0"; + + src = lib.fileset.toSource { + root = ../..; + fileset = lib.fileset.unions [ + ../../package.json + ../../pnpm-workspace.yaml + ../../pnpm-lock.yaml + ../../apps/web + ../../packages/ui + ]; + }; + + nativeBuildInputs = [ nodejs_22 pnpm_11 pnpmConfigHook ]; + + pnpmDeps = fetchPnpmDeps { + inherit (finalAttrs) pname version src; + pnpm = pnpm_11; + fetcherVersion = 4; + hash = "sha256-Hq6LE6Bwb1AeMSMDF0RUbCSX+mMAl8uLt9rPwV6tKBs="; + }; + + buildPhase = '' + runHook preBuild + pnpm --filter web build + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + cp -r apps/web/dist $out + runHook postInstall + ''; +}) diff --git a/deploy/test-access.sh b/deploy/test-access.sh new file mode 100755 index 0000000..a12e4fb --- /dev/null +++ b/deploy/test-access.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# After every server change (CLAUDE.md): the hosts still answer as they should, protected hosts +# still send strangers to Authelia, and Ianitor's control is not reachable from outside. +# Run it from another machine on the LAN, not from the server (loopback would hide exactly the +# exposure this looks for). Read-only: it sends GET requests and nothing else. +# +# deploy/test-access.sh --server 192.168.100.166 \ +# --public flowers.stage.marek-novak.cz --public esp32.stage.marek-novak.cz \ +# --protected wiki.example --auth-host auth.example \ +# --via-ianitor flowers.stage.marek-novak.cz --via-ianitor esp32.stage.marek-novak.cz +# +# --server ADDR the server's LAN address (requests go there, whatever DNS says) +# --public HOST must answer 2xx or 3xx (not a sign-in redirect) +# --protected HOST without a session, must redirect to --auth-host (302/303) or answer 401 +# --auth-host HOST Authelia's portal name, for --protected +# --via-ianitor HOST must answer 2xx/3xx with "X-Served-By: ianitor": the trial hosts set that +# response header in their Ianitor route (configuration-server.patch), so +# an answer Caddy gives on its own fails +# --control-port N control's port (default 7878): must NOT answer from outside +# --insecure accept a certificate the client does not trust (staging: tls internal) +# +# Exit status: 0 when every check passes, 1 otherwise. Each check prints one line. + +set -u +server="" +auth_host="" +control_port=7878 +insecure=() +public=() +protected=() +via=() + +while [ $# -gt 0 ]; do + case "$1" in + --server) server="$2"; shift 2 ;; + --public) public+=("$2"); shift 2 ;; + --protected) protected+=("$2"); shift 2 ;; + --auth-host) auth_host="$2"; shift 2 ;; + --via-ianitor) via+=("$2"); shift 2 ;; + --control-port) control_port="$2"; shift 2 ;; + --insecure) insecure=(-k); shift ;; + -h|--help) sed -n '2,26p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +if [ -z "$server" ]; then + echo "--server is required" >&2 + exit 2 +fi +if [ ${#protected[@]} -gt 0 ] && [ -z "$auth_host" ]; then + echo "--protected needs --auth-host" >&2 + exit 2 +fi + +failures=0 +pass() { printf 'ok %s\n' "$1"; } +fail() { printf 'FAIL %s\n' "$1"; failures=$((failures + 1)); } + +# the response head of https://HOST/ sent to the server +probe() { + curl -sS -o /dev/null -D - --max-time 15 "${insecure[@]}" \ + --resolve "$1:443:$server" "https://$1/" 2>/dev/null | tr -d '\r' +} + +for h in "${public[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + loc=$(printf '%s\n' "$head" | awk 'tolower($1)=="location:" {print $2}') + if [[ "$code" =~ ^[23][0-9][0-9]$ ]] && { [ -z "$auth_host" ] || [[ "$loc" != *"$auth_host"* ]]; }; then + pass "public $h answers $code" + else + fail "public $h answers '${code:-nothing}'${loc:+ -> $loc}" + fi +done + +for h in "${protected[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + loc=$(printf '%s\n' "$head" | awk 'tolower($1)=="location:" {print $2}') + if { [[ "$code" =~ ^30[23]$ ]] && [[ "$loc" == *"$auth_host"* ]]; } || [ "$code" = "401" ]; then + pass "protected $h sends strangers to sign-in ($code)" + else + fail "protected $h answers '${code:-nothing}'${loc:+ -> $loc} without a session" + fi +done + +for h in "${via[@]}"; do + head=$(probe "$h") + code=$(printf '%s\n' "$head" | awk 'NR==1 {print $2}') + served=$(printf '%s\n' "$head" | awk 'tolower($1)=="x-served-by:" {print tolower($2)}') + if [[ "$code" =~ ^[23][0-9][0-9]$ ]] && [ "$served" = "ianitor" ]; then + pass "through Ianitor $h answers $code (X-Served-By: ianitor)" + elif [[ "$code" =~ ^[23][0-9][0-9]$ ]]; then + fail "$h answers $code, but not through Ianitor (no X-Served-By: ianitor)" + else + fail "through Ianitor $h answers '${code:-nothing}'" + fi +done + +# Control must not answer from outside loopback, on any address of the server. +if curl -sS -o /dev/null --max-time 5 "http://$server:$control_port/api/v1/overview" 2>/dev/null; then + fail "control answers on $server:$control_port from outside loopback" +else + pass "control is not reachable on $server:$control_port" +fi +# Nor Ianitor edge's loopback listeners in the beside-Caddy setup. +for p in 18080 18443; do + if curl -sS -o /dev/null --max-time 5 -k "https://$server:$p/" 2>/dev/null || + curl -sS -o /dev/null --max-time 5 "http://$server:$p/" 2>/dev/null; then + fail "Ianitor edge's loopback port $p answers from outside" + else + pass "port $p is not reachable from outside" + fi +done + +if [ "$failures" -gt 0 ]; then + echo "$failures check(s) failed" + exit 1 +fi +echo "all checks passed" diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a6adcfa..fd63b7b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -64,7 +64,10 @@ Main screen: host list with health dots, engine chip, intermediate-expiry banner | API token: ⚙ → API → New token | 3 | Accepted exceptions [M 2026-11-07]: copying a new API token and installing a device certificate may take a 4th click -(deliberate secret-handling steps). +(deliberate secret-handling steps). A share link on a host with links off takes 4 clicks (⋯ → Share link → Turn on +share links → Copy, after the apply is kept; no `turn_on` API change). Signing the intermediate by hand on the offline +machine (openssl) is outside the 1-click Renew budget while Custos lacks the operation (§8.6). Share links are off +while Caddy serves (v1); a validator Caddy calls through forward_auth comes before v1.1's monthly switch rehearsal. ## 5. Test layers (all run in an Artifex pipeline by phase 4) 1. Differential: the same request corpus against Ianitor and Caddy; status, selected headers and body compared. @@ -133,6 +136,7 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit 5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1) **Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy] 6. Custos CSR-signing operation with match-code approval. (phase 3) + **Answer: Custos has none (desktop 0.8.0, CustosPublic v0.13.0).** Its `sign` op signs only minisign, SHA256SUMS manifests, Authenticode digests and deploy approvals, refuses any request against `domi-root` (the RSA-3072 Authenticode root), and no path takes a CSR. Its server reach is the factor-service sign mailbox (`POST /api/sign/requests`, Bearer sign token, answers sealed to a one-time X25519 key, 5-minute match-code card on the PC with a push to the phone). So, per §6: the operation is written as a ticket, [custos-ticket.md](custos-ticket.md) (a new key `domi-pki-root`, ECDSA P-256; a sign kind `x509_csr` through the same mailbox that builds the intermediate from a fixed profile and takes only the CSR's key and CN; the match code computed from the CSR on both screens), not filed. Until then the intermediate is signed **by hand on the offline machine with openssl** ([pki.md](pki.md); Mark accepted it as a §4 exception, 2026-11-07) and device certificates are approved on the server with `sudo -u ianitor-control ianitor-control pki approve ` (Q5). API tokens: Custos stores them as "Local app credential" items with a `domi-ref`; the intended import is Provisio's `offer` (the server seals the value to the PC's key and Mark accepts a match-code card), or copy and paste in the item editor. [S Custos docs/09_signing.md, 07_domi_identity.md, 10_provisio.md, apps/desktop/src-tauri/src/signing.rs] Configuration_Server findings (domains, Caddy, sops-nix secrets, the two trial hosts): [deploy/beside-caddy.md](deploy/beside-caddy.md). **Mark, 2026-11-08:** production runs Authelia, configured outside Configuration_Server, so forward-auth stays (the admin UI host must be behind it; control refuses the ui-proof header on any other host); the trial hosts flowers.stage and esp32.stage on the hyperv-infra mirror are confirmed; and changes keep working while Caddy serves (applies, Undo and Restore are loaded into Caddy through its admin socket, watched through Caddy and reverted by reloading the previous caddy.json; only share links are off). 7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark) ## 9. Status @@ -140,13 +144,44 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit |:--|:--|:--| | 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). | | 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. | -| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system, approved). Carries the Let's Encrypt staging check, on the first low-risk host beside Caddy. | +| 3 Web UI, PKI, NixOS | Built and merged; Done criteria pending Mark | Merged to main 2026-11-08 (PR 5): web UI (murex palette), Domi CA and device mTLS, UI sign-in behind Authelia, runtime engine switch with changes under Caddy, NixOS flake, module and VM tests. Click smoke test green. Not yet done: VM tests run on a KVM host, Mark's nixos-rebuild on the staging mirror, deploy/test-access.sh there, the LE staging check. | | 4 Hardening and release | Not started | Known gaps carried here: see Handover. | ## 10. Handover (Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.) -**2026-11-07: Phase 2, control plane.** +**2026-11-08: Phase 3, web UI, PKI, NixOS.** +- **Changed:** + - apps/web and packages/ui: Svelte 5 UI from the designer's hand-off (docs/ui-handoff.md, decisions in docs/ui-decisions.md), murex palette, self-hosted fonts, no outside requests (CSP). vitest click smoke test for every §4 flow, with the accepted 4th clicks. + - Domi CA in core and control (docs/pki.md): ECDSA P-256; root made offline by `ianitor-control ca init`; intermediate key encrypted at rest; server certificates 90 days, device certificates 1 year and never past the intermediate; control refuses to start with a private key it does not expect in its state dir. Device mTLS in edge and Caddy (`device_certs` hosts, allow list, 421 on SNI/Host mismatch). + - §8.6 answered: Custos has no CSR signing; ticket written (docs/custos-ticket.md, not filed); interim manual openssl signing and `pki approve` on the server. + - UI sign-in (G14): a per-boot `ui-proof` secret that only the admin host behind Authelia sends; control trusts Remote-User only with it. + - Engine switch at runtime through polkit (start/stop of exactly two units). Changes keep working under Caddy: trials loaded through its admin socket, watched by probing upstreams with edge's rules, reverted by control, a deadline guard unit, or ExecStopPost after a crash. Share links are off under Caddy. + - Test hooks moved behind the default `test-hooks` feature; the Nix release build is checked to contain none. + - flake.nix (`.#ianitor`, `.#ianitor-web`, `nixosModules.ianitor`), deploy/nixos with four VM tests, deploy/test-access.sh; docs/deploy/configuration-server.patch and beside-caddy.md (flowers.stage and esp32.stage on the staging mirror, the LE staging check). + - Tests: core 103, edge 57, control 75, diff 4, testkit 1 (240); vitest 15; svelte-check clean; hook self-test 55. Four QC rounds and two design reviews; every finding fixed or listed below. +- **Deployed:** nothing. The server is unchanged. The prepared change is docs/deploy/configuration-server.patch; Mark runs it (beside-caddy.md). +- **Not verified:** + - The four NixOS VM tests: written and their drivers build, but never run (no /dev/kvm in WSL2). + - Real systemd, polkit, LoadCredential, Authelia, Gitea push and Caddy under systemd; the module against hyperv-infra's nixpkgs 24.11. + - The caddy guard retrying a failed load (code reading only). + - PKCS#12 (AES-256) install on older iOS and macOS; a screen reader; a real clipboard copy in Chrome, Firefox and iOS Safari. + - https upstreams: Caddy-path probes use the system CA bundle; not compared with Pingora's roots. +- **Known gaps for later phases:** + - Edge beside Caddy listens on loopback TCP, so any local process could forge X-Forwarded-For; `trustedProxies` stays off there. A Unix-socket listener is the fix. (phase 4) + - Control on a Unix socket only edge can reach (G14 option b). (phase 4) + - Share links under Caddy need a validator Caddy calls via forward_auth. (before v1.1) + - "All hosts answered" after a switch is not claimed: control does not check every host. + - A revocation during an engine switch reaches the engine at the end of the switch (or by the 2 s retry), not at once. + - The open `apply_sequence` flake from phase 2 has not recurred, but its cause is still unknown. +- **Decided by Mark (2026-11-07/08):** the share link on a host with links off keeps 4 clicks; UI sign-in by a secret header from edge; the switch to Caddy is allowed with differences shown; share links off under Caddy for v1; device approval falls back to `pki approve`; manual intermediate signing is a §4 exception; device certificates last 1 year; confirmations on Stop all and Revoke; hidden tabs stop polling after 15 minutes; token lifetime choice; "Open to anyone" chip; production runs Authelia outside Configuration_Server; trial hosts flowers.stage and esp32.stage; changes keep working under Caddy. +- **Still open:** + - Mark: add hyperv-infra/ianitor/domi-root.crt (made offline), apply the patch with the merged commit hash, deploy to the staging mirror, run deploy/test-access.sh, then the LE staging check (it needs a new public name on production). + - Run the VM tests on a machine with KVM (`nix flake check`). + - (e) Delete F:\pwt and the merged remote branches. +- **Next step:** Mark's staging deploy and the VM tests close Phase 3; then Phase 4. + +**2026-11-07: Phase 2, control plane** (kept for its open items). - **Changed:** - Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/.toml` loader in core. - docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end). diff --git a/docs/api.md b/docs/api.md index 0589e4c..8674ae6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -10,9 +10,12 @@ Everything below was run end to end on loopback against `--dev` with a real edge ## Ground rules -- **Token.** Every call needs `Authorization: Bearer `. Nothing else identifies a - caller (no `Remote-User`). Without a valid token: `401` with `token.missing`, - `token.unknown`, `token.expired` or `token.revoked`. 120 calls a minute per token. +- **Token or sign-in.** A script sends `Authorization: Bearer `. The web UI sends + no token: it comes through edge on the admin host, behind Authelia (see "Sign-in" below). + Without either: `401` with `token.missing`, `token.unknown`, `token.expired` or + `token.revoked`; a `Remote-*` header without edge's proof is `401 ui.no_proof`, whatever + else the request carries. 120 calls a minute per token or user. The one exception is the + one-time device download (`/device-bundles/{token}`), where the link is the secret. - **Host header.** Only `127.0.0.1:`, `localhost:`, `[::1]:` and the configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or `Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF). @@ -232,6 +235,122 @@ curl -s -H "$H" -X DELETE "$API/tokens/" # 204; anything using it sto curl -s "$API/overview" | jq .error.code # "token.missing" ``` +## Sign-in (the web UI, G14) + +The UI is served by control (`[ui] static_dir`) and reached through edge on the **admin host**, +a host in the routes repository with forward-auth to Authelia and one header rule: + +```toml +# hosts/ianitor.example.toml +hostname = "ianitor.example" +upstreams = ["http://127.0.0.1:7878"] +tls = "domi" +auth = "forward-auth" + +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" # listed in ianitor.toml: secrets = ["ui-proof"] +``` + +- `ui-proof` is a **per-boot secret**: the `ianitor-ui-proof` unit writes 32 random bytes to + `/run/ianitor-proof/ui-proof` (root only), and edge, caddy-fallback and control load it with + `LoadCredential`. No other process can read it. +- Edge strips every client-sent `Remote-*` header on forward-auth hosts, asks Authelia, copies + Authelia's `Remote-User` (and `Remote-Name`, …) onto the request, and *sets* `X-Ianitor-Proof` + (replacing anything the client sent) only on requests Authelia allowed. +- Control (`[ui] proof_credential = "ui-proof"`, `hostname = "ianitor.example"`) trusts + `Remote-User` only on a request whose `X-Ianitor-Proof` matches (constant-time compare). Then + `Remote-User` is the actor (history, logs) and `Remote-Name` the name the UI shows. Every write + also needs `X-Ianitor-UI: 1` (CSRF; the session is a cookie). +- Any request with a `Remote-*` header but without the proof is `401 ui.no_proof`, so a local + process on loopback cannot claim a user; the proof without `Remote-User` is `401 ui.no_user`. + Tested in `crates/control/tests/ui_auth.rs`, including end to end through edge and a mock Authelia. +- `[ui] logout_url` (Authelia's logout address) becomes `overview.site.auth_logout_url`, the UI's + "Sign out". A Unix socket only edge can reach is Phase 4 hardening (decision Q2). + +Why not the Unix socket now: edge's upstreams are `host:port` in the schema; a socket upstream is a +schema and compiler change in both engines, and the proof header needs neither. + +## Certificates (the Domi CA) + +Everything is in [pki.md](pki.md); the calls: + +```sh +curl -s -H "$H" "$API/certs" | jq '{intermediate: .intermediate.state, root: .root.offline, devices: [.devices[].name]}' +curl -s -H "$H" -X POST "$API/certs/intermediate/renewal" | jq '{request_id, match_code, approve_command}' +curl -s -H "$H" "$API/pki-requests/$ID/csr" > req.csr; curl -s -H "$H" "$API/pki-requests/$ID/ext" > req.ext +curl -s -H "$H" -H 'Content-Type: application/json' -X PUT "$API/pki-requests/$ID/certificate" \ + -d "$(jq -n --rawfile c int.crt '{certificate_pem: $c}')" | jq .state # "approved" +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices" \ + -d '{"name": "Mark'\''s phone", "kind": "phone"}' | jq '{request_id, match_code, approve_command}' +# on the server: sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices/$DEV/bundle" \ + -d '{"format": "p12"}' | jq '{download_url, one_time_password}' +curl -s -X POST -o phone.p12 "$DOWNLOAD_URL" # once; a second try is 410 pki.bundle_used (GET is only its page) +curl -s -H "$H" -X DELETE "$API/certs/devices/$DEV" # 204, off the allow list at once +``` + +`overview.intermediate` is `{state ("ok"|"due"|"urgent"|"expired"|"missing"), subject, not_after, +days_left, renewal, banner}`, or `null` without `[pki]`. With `[pki]` configured, control issues +the server certificate of every `tls = "domi"` host before an apply is committed, renews it with 30 +days left, and an apply with a Domi host and no intermediate fails with `pki.no_intermediate`. + +## Engine switch (G18) + +```sh +curl -s -H "$H" "$API/engine" | jq '{running, state, switchable}' +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/engine" -d '{"target": "caddy"}' # 202 +# poll GET /engine until state = "running"; last_error says why if it went back +``` + +Control writes `/var/lib/ianitor/engine` first, stops the serving unit, starts the other one (polkit +allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start and stop) and +waits until it serves; if it does not within 20 s, it starts the old one again and reports +`engine.switch_failed`. The switch waits for a running apply (same lock, first come first +served: a queued switch runs right after the apply in progress, before any apply queued after +it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. Every +switch, kept or gone back, ends by telling the engine that serves to read the device files again; +a device change during a switch only writes them and shows `devices_problem` ("an engine switch is +under way") until then, and the 2 s retry tells the serving engine too. +Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`, +`engine.not_ready` (Caddy's settings cannot be built from the current routes). + +While Caddy serves (decisions Q3, Q4; Mark 2026-11-08): +- **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs + are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix + socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS, + group `ianitor-caddy-admin`: control and Caddy, not edge), and a revert loads the previous + `caddy.json` again. Every load sends `Cache-Control: must-revalidate`, so Caddy reads its + certificate and device files again even when the config is unchanged. The watch judges health + as edge does: control probes the upstreams itself with edge's rules (health check: `GET `, + Host = the upstream, 2xx; none: `GET /`, Host = the hostname, below 500), and a probe *through* + Caddy only asks that Caddy answers at all (any status, its sign-in redirect included). Each + round also checks that Caddy still runs the trial (`GET /config/`); if anything else reloaded it, + the change is undone as `apply.reverted.edge_lost`. Without `caddy_admin_socket` an apply under + Caddy fails with `apply.failed.reload` and nothing changes; +- **an unconfirmed trial never outlives control**, as with edge: control arms a deadline + (`caddy-trial.json` in its state directory: watch + margin) before loading the trial and claims + it right after the journal says `confirmed` (a crash in between leaves both, and recovery + promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is + retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. `ianitor-caddy-guard` (a unit that runs with caddy-fallback, + `ianitor-control caddy-guard`) reverts a trial past its deadline, which covers a hung control; + ianitor-control's `ExecStopPost=ianitor-control caddy-revert` reverts at once after any stop or + crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted; +- device issues and revocations never wait for an apply: the files are written and edge is told + at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk + for a Domi host (else `devices_problem`, retried), except while a trial is out: then the end + of that apply (promote or revert, both load caddy.json) brings the new files in; +- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the + normal sign-in (fails closed). Caddy cannot check a share token and control never serves + visitors; a validator Caddy calls through `forward_auth` is planned before v1.1; + +A revocation is in force only once the serving engine has the new list. If the list cannot be +written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503 +pki.devices_unwritten` (the revocation itself is recorded), `GET /certs` carries +`devices_problem` until it is fixed, and control retries every 2 s; repeating the DELETE is +safe and nudges the engine again. Edge also re-reads the device files by itself every 5 s. + ## All calls | Call | Does | @@ -248,4 +367,9 @@ curl -s "$API/overview" | jq .error.code # "token.missing" | `GET/POST /tokens`, `PATCH/DELETE /tokens/{id}` | API tokens | | `POST /hosts/{h}/share-links`, `GET /share-links`, `DELETE /share-links/{id}`, `POST /share-links/stop-all` | share links | | `GET /health` | edge reachability, config hash, trial, paused state, hosts | +| `GET /certs`, `POST /certs/devices`, `DELETE /certs/devices/{id}`, `POST /certs/devices/{id}/bundle` | the Domi CA screen, device requests, revocation, one-time install files | +| `POST /certs/intermediate/renewal`, `GET/DELETE /pki-requests/{id}`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`, `PUT /pki-requests/{id}/certificate` | renewals and approvals | +| `GET /device-bundles/{token}` | the link's page with a Download button (uses nothing up: link previews only GET) | +| `POST /device-bundles/{token}` | the one-time PKCS#12 download (no token; the link is the secret) | +| `GET /engine`, `POST /engine` | which engine serves; switch | | `GET /openapi.json` | the OpenAPI document | 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`. diff --git a/docs/deploy/beside-caddy.md b/docs/deploy/beside-caddy.md new file mode 100644 index 0000000..1aa6e03 --- /dev/null +++ b/docs/deploy/beside-caddy.md @@ -0,0 +1,150 @@ +# Ianitor beside Caddy on two low-risk hosts + +ROADMAP §1.12 and §6 Phase 3: Ianitor runs beside Caddy on two low-risk hosts before any +cut-over. This is **prepared, not applied**: Mark runs every command below himself. + +## What was found in Configuration_Server (read-only, 2026-11-07) + +- `hyperv-infra/` is the active flake (`nixosConfigurations.hyperv-vm`, the staging mirror on + 192.168.100.166), pinned to production's nixpkgs (24.11, rev 50ab793). Production (.217) is a + classic-channels install whose real config is not in the repository; `nixos-live/` is a + snapshot. +- Caddy is the only listener on 80/443 and the only service beyond loopback (decision D-21a); + every backend binds 127.0.0.1. Secrets come from sops-nix (`/run/secrets/...`). +- Authelia is not in the repository: production runs it, configured outside Configuration_Server + (Mark, 2026-11-08). Ianitor keeps forward-auth; the admin UI's host must sit behind it, and + control refuses a ui-proof header rule on any other host. The two trial hosts use no sign-in + (their applications have none today). +- The module turns on `security.polkit` (control may start and stop exactly `ianitor-edge` and + `caddy-fallback`). The server had no other use for polkit, so that service is new there. +- Lowest-risk hosts: `flowers.stage.marek-novak.cz` (a static presentation app, nginx on + 127.0.0.1:8091) and `esp32.stage.marek-novak.cz` (a static web IDE, 127.0.0.1:8093, used only + by Mark). Both are on the staging mirror, "the one machine safe to break". + +## The shape + +```text +visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edge ── the app +``` + +- Ianitor edge listens on **loopback only** (127.0.0.1:18080 and :18443), so D-21a holds: + nothing new is reachable from the LAN. Control is on 127.0.0.1:7878. +- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor + serves them with Domi certificates, which Caddy checks against the Domi root (a public file). +- Every other host is untouched. Rollback: revert the patch and switch (below). +- Visitor addresses: Ianitor sees every visit coming from 127.0.0.1 (Caddy), so the share-link + throttle counts all visitors together and the visit log shows 127.0.0.0. The option + `services.ianitor.edge.trustedProxies = [ "127.0.0.1" ]` would make edge believe Caddy's + `X-Forwarded-For` instead, but edge listens on a TCP port on loopback that **any local user or + process can reach**, and any of them could then claim any address. It stays **off** for the + trial (the two hosts have no share links and no visit log); turn it on only on a machine where + every local account is trusted. (A Unix-socket listener for edge, which Caddy alone could reach, + is the proper fix; not built yet.) + +## The patch + +[configuration-server.patch](configuration-server.patch), against Configuration_Server `main` +(5124e9d): adds the `ianitor` flake input, `hyperv-infra/modules/ianitor.nix`, and routes the two +vhosts in `hyperv-infra/modules/caddy.nix` through Ianitor. No secret is in it. + +## Commands (Mark) + +On the offline machine (once; see [../pki.md](../pki.md)): + +```sh +openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 \ + -keyout domi-root.key -out domi-root.crt -days 3653 \ + -subj "/CN=Domi PKI Root/O=Fabrica Domi" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:1" -addext "keyUsage=critical,keyCertSign,cRLSign" +``` + +In Configuration_Server, on a branch, per the repository's workflow: + +```sh +git switch -c feature/ianitor-beside-caddy +git apply /path/to/Ianitor/docs/deploy/configuration-server.patch +mkdir -p hyperv-infra/ianitor && cp /path/to/domi-root.crt hyperv-infra/ianitor/domi-root.crt +# Two new secrets, generated and piped (never in a command line, a file in the repository or +# the shell history). Needs `sops set --value-stdin`; with an older sops, use `sops edit`: +cd hyperv-infra +for k in share-link-key pki-password; do + { printf '"'; head -c 32 /dev/urandom | base64 -w0; printf '"'; } | + sops set --value-stdin secrets/secrets.yaml "[\"ianitor\"][\"$k\"]" +done +# Pin Ianitor to the reviewed commit (the patch carries MERGED_COMMIT as a placeholder): +sed -i "s/MERGED_COMMIT//" flake.nix +nix flake lock --update-input ianitor +nix flake check --no-build +git add -A && git commit +``` + +Deploy to the staging mirror (build first, as the repository's rules say): + +```powershell +scripts/staging/Deploy-Staging.ps1 -Mode Build +scripts/staging/Deploy-Staging.ps1 -Mode Test +scripts/staging/Deploy-Staging.ps1 -Mode Switch +``` + +On the mirror, the first intermediate and the two hosts: + +```sh +sudo -u ianitor-control ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml +# -> save the token in Custos; then, from the laptop. The token goes into a header file that only +# you can read, so it is never in a command line (ps) or the shell history: +ssh -fN -L 7878:127.0.0.1:7878 mirror +H=@$HOME/.ianitor-header; API=http://127.0.0.1:7878/api/v1 +( umask 077; IFS= read -rs t; printf 'Authorization: Bearer %s\n' "$t" > ~/.ianitor-header ) # paste the token +curl -s -H "$H" -X POST "$API/certs/intermediate/renewal" | jq -r .csr_pem > req.csr +curl -s -H "$H" "$API/pki-requests/$(curl -s -H "$H" $API/overview | jq -r .intermediate.renewal.request_id)/ext" > req.ext +# offline: openssl x509 -req -in req.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile req.ext -out int.crt +scp int.crt mirror:/tmp/ && ssh mirror sudo -u ianitor-control ianitor-control pki install /tmp/int.crt --config /etc/ianitor/control.toml +for h in flowers esp32; do + curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \ + -d "$(jq -c --arg h "$h.stage.marek-novak.cz" '.[] | select(.hostname == $h) | {host: .}' /etc/ianitor/trial-hosts.json)" +done # each is kept or reverted within 60 s; GET $API/applies/ +``` + +(The web UI needs the admin host behind Authelia; for the trial, run it locally against the +tunnel. The token goes in through the environment, never the command line, and the dev proxy +adds it, so the browser never holds it: + + IANITOR_CONTROL=http://127.0.0.1:7878 \ + IANITOR_DEV_TOKEN="$(sed 's/^Authorization: Bearer //' ~/.ianitor-header)" pnpm --filter web dev +) + +Then, from the desktop (192.168.100.140): + +```sh +deploy/test-access.sh --server 192.168.100.166 --insecure \ + --public git.stage.marek-novak.cz --public ha.stage.marek-novak.cz \ + --via-ianitor flowers.stage.marek-novak.cz --via-ianitor esp32.stage.marek-novak.cz +``` + +`--insecure` because the stage names use Caddy's `tls internal` (or the stage wildcard). Each +`--via-ianitor` host must answer with `X-Served-By: ianitor` (set by its route in the patch), so +an answer from Caddy alone fails. It must print `all checks passed`; the two-week run (§1.12) +starts then. + +Rollback at any time: `git revert` the commit, `Deploy-Staging.ps1 -Mode Switch`. Ianitor's +state stays in /var/lib/ianitor and is ignored. + +## The Let's Encrypt staging check (moved to phase 3, Mark 2026-11-07) + +ACME HTTP-01 needs a name that resolves publicly to the machine that receives port 80, which is +production (.217; the mirror has no port forward). It is one documented check, not part of the +trial: + +1. At Forpsi, add `ianitor-le.marek-novak.cz` (A record, the public IP). +2. On production's Caddy, hand that name's challenge path to Ianitor (the rest of the name can 404): + ```caddy + http://ianitor-le.marek-novak.cz { + reverse_proxy /.well-known/acme-challenge/* 127.0.0.1:18080 + } + ``` +3. In Ianitor's routes, `ianitor.toml` gets `[acme] directory = "https://acme-staging-v02.api.letsencrypt.org/directory"` + and a host `ianitor-le.marek-novak.cz` with `tls = "letsencrypt"` and any upstream. +4. Check: `openssl s_client -connect 127.0.0.1:18443 -servername ianitor-le.marek-novak.cz Caddy :443 (tls as today) -> https://127.0.0.1:18443 Ianitor edge -> the app ++# ++# Ianitor edge listens on loopback only (18080/18443) and terminates TLS with a Domi certificate; ++# Caddy trusts the Domi root (a public certificate, ianitor/domi-root.crt) for that hop. Control ++# listens on 127.0.0.1:7878. Nothing new is reachable from the LAN. ++# ++# Secrets come from sops-nix (paths under /run/secrets, never the store); the module asserts it. ++# Rollback: remove this import and the two `viaIanitor` lines in caddy.nix, nixos-rebuild switch. ++ ++let ++ stage = "stage.marek-novak.cz"; ++in ++{ ++ imports = [ inputs.ianitor.nixosModules.ianitor ]; ++ ++ sops.secrets."ianitor/share-link-key" = { }; ++ sops.secrets."ianitor/pki-password" = { }; ++ ++ services.ianitor = { ++ enable = true; ++ edge = { ++ httpListen = "127.0.0.1:18080"; ++ httpsListen = "127.0.0.1:18443"; ++ openFirewall = false; ++ }; ++ control.listen = "127.0.0.1:7878"; ++ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path; ++ pki = { ++ enable = true; ++ rootCertificate = ../ianitor/domi-root.crt; ++ passwordFile = config.sops.secrets."ianitor/pki-password".path; ++ }; ++ }; ++ ++ # The trial hosts, as Ianitor route files. They are applied through the API after the first ++ # start (docs/deploy/beside-caddy.md in the Ianitor repo); listed here so the review sees them. ++ environment.etc."ianitor/trial-hosts.json".text = builtins.toJSON [ ++ { hostname = "flowers.${stage}"; upstreams = [ "http://127.0.0.1:8091" ]; tls = "domi"; auth = "none"; health_check = { path = "/"; interval_secs = 30; }; response_headers = [ { action = "set"; name = "X-Served-By"; value = "ianitor"; } ]; } ++ { hostname = "esp32.${stage}"; upstreams = [ "http://127.0.0.1:8093" ]; tls = "domi"; auth = "none"; health_check = { path = "/"; interval_secs = 30; }; response_headers = [ { action = "set"; name = "X-Served-By"; value = "ianitor"; } ]; } ++ ]; ++} diff --git a/docs/pki.md b/docs/pki.md new file mode 100644 index 0000000..65d1287 --- /dev/null +++ b/docs/pki.md @@ -0,0 +1,117 @@ +# The Domi CA + +ROADMAP §1.1, §1.2, §1.8, §3. Code: `crates/core/src/pki.rs` (the CA, pure), +`crates/control/src/pki.rs` (state, requests, devices), `crates/edge/src/tls.rs` (device +certificates in the handshake). + +```text +Domi PKI Root ~10 years, pathLen 1 offline; never on the server + └ Ianitor Domi Intermediate 1 year, pathLen 0 on the server, key encrypted at rest + ├ 90 days, serverAuth tls = "domi" hosts, renewed by control + └ 1 year, clientAuth mTLS for hosts with device_certs = true +``` + +All keys are ECDSA P-256. + +## Lifetimes, and why + +| Certificate | Lifetime | Why | +|:--|:--|:--| +| Root | 3653 days | ROADMAP §3 ("~10 years"). It signs once a year, offline. | +| Intermediate | 365 days | ROADMAP §3 ("~1 year"); renewed through the banner, signed by the root. | +| Server | 90 days, renewed at 30 days left | Control renews them by itself (hourly check), so a short life costs nothing and bounds a key read from the certificate directory; 30 days of slack survive a long control outage. | +| Device | 365 days, "renew soon" at 30 days | Installing is a deliberate manual step (§4 accepts its 4th click), so not more than once a year; a lost device is revoked (allow list) rather than waited out. Mark, 2026-11-07 (Q7). | + +No certificate is ever issued past its issuer's `notAfter`. + +## What is where on the server + +`/var/lib/ianitor/control/pki/` (mode 0700, owner ianitor-control): + +| File | What | +|:--|:--| +| `intermediate.crt`, `previous.crt` | the intermediate, and the one before while it is valid | +| `intermediate.key` | its key, `IANITOR ENCRYPTED PRIVATE KEY` (PBKDF2-HMAC-SHA256 600,000 rounds + AES-256-GCM), password from the `pki-password` credential | +| `pending-.key` | the new key of an open renewal, encrypted the same way | +| `devices.json`, `devices/.key` | issued device certificates; their keys, encrypted, kept to make an install file again until revoked | +| `requests.json`, `approvals/` | approval requests, and the manual approvals the CLI writes | + +`/var/lib/ianitor/certs/`: `.crt` (leaf + intermediate) and `.key` (0640, group +ianitor), `domi-devices-ca.pem` (the intermediates that issue device certificates) and +`domi-devices.pem` (the allow list: every issued, unrevoked, unexpired device certificate). Edge +and Caddy read these files; a presented device certificate must chain to the bundle **and** be +on the list, or the handshake fails. + +The root key is never here. Control refuses to start when a file named like a root key is in +its state directory (tested: `control_refuses_to_start_with_a_root_key_in_its_state_dir`). + +## Until Custos can sign: the manual offline step + +Custos has no CSR-signing operation yet (ROADMAP §8.6, [custos-ticket.md](custos-ticket.md)). +Mark accepted this as a §4 exception (2026-11-07, Q6): **the offline machine runs openssl.** + +### Once: the root, on the offline machine + +```sh +openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 \ + -keyout domi-root.key -out domi-root.crt -days 3653 \ + -subj "/CN=Domi PKI Root/O=Fabrica Domi" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:1" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" +# asks for a passphrase: domi-root.key is stored encrypted +openssl x509 -in domi-root.crt -noout -fingerprint -sha256 +``` + +(`ianitor-control ca init --out ` makes the same root with Ianitor's own encrypted key +format, on a machine that has Ianitor.) Copy **only `domi-root.crt`** to the server's +configuration (`services.ianitor.pki.rootCertificate`). `domi-root.key` and its passphrase stay +offline (and go into Custos once it can hold them). + +### Each year (and the first time): the intermediate + +1. In the UI: the banner's **Renew** (or **Set up**) makes a new key on the server and a CSR, and + shows the request's SHA-256 fingerprint. **Sign it by hand** downloads `domi-intermediate-.csr` and + `domi-intermediate-.ext` (the signing profile: CA, pathLen 0, keyCertSign + cRLSign). By + API: `POST /certs/intermediate/renewal`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`. +2. On the offline machine, check the request (the fingerprint must be the one the UI shows), then sign: + ```sh + openssl req -in domi-intermediate-.csr -outform DER | openssl dgst -sha256 + openssl req -in domi-intermediate-.csr -noout -subject # CN=Ianitor Domi Intermediate + openssl x509 -req -in domi-intermediate-.csr -CA domi-root.crt -CAkey domi-root.key \ + -days 365 -sha256 -extfile domi-intermediate-.ext -out domi-intermediate-.crt + ``` + (`ianitor-control ca sign --root --csr … --out …` does the same and asks for the match + code before it signs.) +3. Back on the server: upload the `.crt` in the UI (step 3), or + `sudo -u ianitor-control ianitor-control pki install domi-intermediate-.crt --config /etc/ianitor/control.toml`. + +Control checks that the certificate is signed by the configured root, is a CA with path length 0 +and keyUsage keyCertSign + cRLSign, has no extended key usage that would stop it issuing (none, +any, or both server and client auth), is valid now and ends no later than the root, and carries +the pending key; otherwise it refuses (`pki.manual.not_ca`, `pki.manual.eku`, `pki.manual.dates`, +`pki.wrong_key`, `pki.not_our_root`), says why on the request and in `pki install`, and keeps the +request open. Once it passes, control swaps the intermediate, reissues every `tls = "domi"` +certificate and reloads the engine that serves. Tested with real openssl +(`an_intermediate_signed_with_openssl_is_installed`). + +## Device certificates + +ROADMAP §4: Certificates → + Device → Issue (3 clicks), then install (the accepted 4th). + +1. `POST /certs/devices {name, kind}` opens a request with a six-digit match code, for 10 minutes. +2. Until Custos can approve (Mark, Q5): approve it on the server, comparing the code with the UI: + `sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml` + (`pki deny ` turns it down; `pki status` lists open requests). Control issues the + certificate within two seconds and puts it on the allow list; edge re-reads the list at once. +3. Install: `POST /certs/devices/{id}/bundle {format: "qr"|"p12"}` gives a one-time link (10 + minutes, one download) to a PKCS#12 file (AES-256, SHA-256 MAC) and a one-time password. When + `[ui] hostname` is set the link goes through edge on the admin host, as a share link when that + host has share links on, so a device without a sign-in can fetch it; the token is the secret. +4. Revoke: `DELETE /certs/devices/{id}`. It is off the allow list at once (edge: + `/v1/device-certs/reload`; Caddy: control restarts caddy-fallback, which reads the list at start). + +A host asks for device certificates with `device_certs = true` in its file. Only such hosts send a +certificate request in the TLS handshake (other hosts never prompt a browser). Without a +certificate, or with one not on the list, the handshake fails on both engines; a request whose +`Host` is another name than the connection's SNI is answered 421 once any host needs device +certificates (as Caddy does). diff --git a/docs/ui-api.md b/docs/ui-api.md index df49d2e..0d1cb08 100644 --- a/docs/ui-api.md +++ b/docs/ui-api.md @@ -508,3 +508,42 @@ written above. `share.not_found`, `share.replaces`, `share.password_long`, `share.too_many`, `request.in_progress`, `control.files_unwritten`, `token.not_found`, `token.name`, `token.expiry`, `file.*`, `site.*` (problems in `ianitor.toml`). + +## 7. Phase 3: the deferred items as built + +Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the calls. + +- **G7** (share links under Caddy): off for v1 (Mark, Q4). Minting is refused with + `409 share.engine_caddy` while Caddy serves, `overview.site.share_links_available` is false and + the engine popover, share dialog and Settings say so. Visitors fail closed (normal sign-in). +- **G12**: the token dialog keeps "Copy token" as the accepted 4th click (Mark); the POST answers + well under a second. Tokens never reach storage, URLs or logs (tested in the smoke test). +- **G13**: device install is the accepted 4th click. +- **G14**: edge's per-boot proof header on the admin host; control trusts `Remote-User` (actor) + and `Remote-Name` (shown) only with it; a forged `Remote-User` is `401 ui.no_proof`. + `overview.viewer {name, via}` and `overview.site.auth_logout_url` are new. +- **G15**: `POST /certs/devices/{id}/bundle` → one-time `/device-bundles/{token}` (GET shows a + page, its button POSTs the download, so link previews cannot use it up; 10 min, one use, + PKCS#12 with a one-time password, `qr_svg` for `format = "qr"`); through edge on the admin + host, as a share link when that host has share links on (never listed in `GET /share-links`). +- **G18**: `GET/POST /engine` (shape in docs/api.md). Difference from §1.9: control cannot run the + differential suite at runtime, so `fallback_ready {built_at, current, compared, matched, + differences[]}` counts *hosts*, not requests: `compared` hosts in the routes, `matched` those + with none of the suite's known differences (share links, forward-auth edge cases), and + `differences` says what differs in plain English (decision Q3: listed under "Show details"). + `overview.active_apply` also carries `kind`, `hosts` and `watch_ends_at`, so the bar writes the + heading and counts down every second. `GET /certs` has `device_valid_until` (a year, capped at + the intermediate's end, Q7) and renewal requests carry `csr_sha256` (what + `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints). Changes keep working while Caddy serves (Mark 2026-11-08): they are + loaded into Caddy and watched through it; only share links are off. +- **G19**: the UI shows "No websockets" only when off, and "Open to anyone" for `auth = none` (Q11). +- **PKI** (§1.7, §1.8, §3.6): built as drawn, with two differences while Custos lacks the + operations: device requests are approved on the server (`pki approve `, the UI shows the + command and the code; `message_code = "pki.waiting.manual"`), and renewals are signed by hand + with openssl (`approve_command`, `file_base`, `GET /pki-requests/{id}/ext`). Requests carry + `problem` (not `error`) for why they failed. Renewal requests stay open 7 days, device requests + 10 minutes. +- New host field `device_certs` (bool): only Domi device certificates on the allow list get in. +- `overview.paused_reason` gives the underlying code (`apply.needs_attention`, + `control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`, and + `overview.paused_detail` the technical detail behind it (for "Show details"). diff --git a/docs/ui-decisions.md b/docs/ui-decisions.md new file mode 100644 index 0000000..44c6226 --- /dev/null +++ b/docs/ui-decisions.md @@ -0,0 +1,15 @@ +# Mark's answers to open-questions.md (2026-11-07) + +- Q1 Share link on a host with links off: **keep the 4-click path** (button "Turn on share links", Copy appears when the apply is kept). No `turn_on` API change. Record it in ROADMAP §4 as an accepted 4th click. +- Q2 UI auth (G14): **(a) secret header from edge** on the admin host, from a systemd credential; control requires it, then trusts Remote-User/Remote-Name from Authelia. Keep X-Ianitor-UI against CSRF. Add `site.auth_logout_url` for "Sign out". Unix socket (b) is Phase 4 hardening. +- Q3 Engine switch: **allow with differences listed** under "Show details"; refuse only `engine.not_ready`. Switch waits in the same queue as applies. +- Q4 Share links under Caddy: **off for v1**, said plainly in the engine popover, the share dialog and Settings. Validator Caddy calls via forward_auth before v1.1 (note in ROADMAP). +- Q5 Device certificates without Custos: **server-command fallback** `sudo ianitor-control pki approve `, match code shown in the UI. +- Q6 Manual intermediate signing: **accepted as a §4 exception** while Custos lacks the operation; the offline machine runs openssl. +- Q7 Device certificate lifetime: **1 year**, "renew soon" 30 days before, never past the intermediate's end date. +- Q8 Inline confirmation on "Stop all share links" and on "Revoke" token: **yes**. +- Q9 Stop polling after 15 min in a hidden tab: **yes**. +- Q10 "New tokens expire after: 1 year | Never" choice, default 1 year: **yes**. +- Q11 "Open to anyone" chip on auth = none hosts: **yes**. +- Q12 Add the handoff's sentences for the 8 generic codes to control's messages.rs: yes (orchestrator default; no owner decision needed). +- Q13 Self-host the fonts in packages/ui: yes (orchestrator default; the UI makes no outside requests). 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. +`