[repo] Phase 3: web UI, Domi CA, NixOS module #5

Manually merged
mnovak merged 34 commits from phase-3 into main 2026-11-08 12:57:58 +01:00
123 changed files with 20548 additions and 148 deletions
Generated
+485 -7
View File
@@ -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"
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<!-- 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/. -->
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<meta name="referrer" content="no-referrer" />
<title>Hosts — Ianitor Domi</title>
</head>
<body class="ia">
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+22 -3
View File
@@ -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"
}
}
+175
View File
@@ -0,0 +1,175 @@
<!-- 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/. -->
<script lang="ts">
// The shell (handoff §2.16): sidebar on desktop, top and bottom bars on phone, the routes,
// the banners every screen starts with, toasts and the signed-out dialog (§10).
import { onMount } from "svelte";
import { Button, Dialog, Icon } from "@ianitor/ui";
import type { IconName } from "@ianitor/ui";
import EngineChip from "./components/EngineChip.svelte";
import EnginePopover from "./components/EnginePopover.svelte";
import TopBanners from "./components/TopBanners.svelte";
import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
import { remembered } from "./lib/applies";
import Certificates from "./views/Certificates.svelte";
import History from "./views/History.svelte";
import Hosts from "./views/Hosts.svelte";
import RenewByHand from "./views/RenewByHand.svelte";
import Settings from "./views/Settings.svelte";
import SignedIn from "./views/SignedIn.svelte";
const route = $derived.by(() => {
const u = new URL(app.path, "http://x");
const p = u.pathname.replace(/\/+$/, "") || "/";
const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
if (p === "/signed-in") return { view: "signed-in" as const };
if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] };
if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" };
if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" };
return { view: "hosts" as const, newHost: seg[0] === "hosts" && seg[1] === "new", edit: seg[0] === "hosts" && seg[2] === "edit" ? seg[1] : undefined };
});
const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [
{ href: "/", label: "Hosts", icon: "building", views: ["hosts"] },
{ href: "/history", label: "History", icon: "history", views: ["history"] },
{ href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] },
{ href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] },
];
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
$effect(() => {
document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`;
});
onMount(() => {
if (route.view === "signed-in") return;
const stop = startPolling();
// Resume an apply this tab was watching before a reload or a sign-in (§3).
const id = remembered();
if (id && route.view === "hosts") app.panel = { kind: "host", resume: id };
let ch: BroadcastChannel | undefined;
try {
ch = new BroadcastChannel("ianitor-auth");
ch.onmessage = (m) => {
if (m.data === "signed-in") {
app.signedOut = false;
void refresh();
}
};
} catch {
/* no BroadcastChannel: "I have signed in" still works */
}
return () => {
stop();
ch?.close();
};
});
function go(e: MouseEvent, href: string) {
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
e.preventDefault();
navigate(href);
}
function signIn() {
const w = window.open("/signed-in", "ianitor-sign-in");
if (!w) {
// The new tab was blocked: this tab goes to the sign-in, so an open form is saved first
// (sessionStorage, this tab only) and comes back after it (§10).
window.dispatchEvent(new Event("ianitor:save-draft"));
location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
}
}
async function signedInAgain() {
app.signedOut = false;
await refresh();
}
const viewer = $derived(app.overview?.viewer ?? null);
</script>
{#if route.view === "signed-in"}
<SignedIn />
{:else}
<a class="skip domi-btn" href="#main">Skip to content</a>
<div class="shell">
<nav class="sidebar" aria-label="Main">
<div class="ia-wordmark brand">IANITOR DOMI</div>
{#each NAV as n (n.href)}
<a href={n.href} class="nav" aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} />{n.label}</a>
{/each}
<div class="foot ia-muted">
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer ? `Using the API token "${viewer.name}"` : "Signed in through Authelia"}</p>
<p>Control on 127.0.0.1 only</p>
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
</div>
</nav>
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
<main id="main" tabindex="-1">
<TopBanners />
{#if route.view === "hosts"}
<Hosts route={{ newHost: route.newHost, edit: route.edit }} />
{:else if route.view === "history"}
{#key route.host}<History host={route.host} pick={route.pick} />{/key}
{:else if route.view === "certs"}
<Certificates newDevice={route.newDevice} />
{:else if route.view === "renew"}
<RenewByHand />
{:else if route.view === "settings"}
<Settings tab={route.tab} />
{/if}
</main>
<nav class="bottombar" aria-label="Main">
{#each NAV as n (n.href)}
<a href={n.href} aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} /><span>{n.label}</span></a>
{/each}
</nav>
</div>
{#if app.panel?.kind === "engine"}
<EnginePopover onclose={() => {
app.panel = null;
document.querySelector<HTMLElement>("[data-engine-chip]")?.focus();
}} />
{/if}
<div class="ia-toasts" role="status" aria-live="polite">
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
</div>
{#if app.signedOut}
<Dialog title="Your sign-in has ended" role="alertdialog" escape={false} closable={false} onclose={() => {}}>
<p>Sign in again; this page keeps what you typed.</p>
{#snippet footer()}
<Button onclick={signedInAgain}>I have signed in</Button>
<Button variant="primary" onclick={signIn} data-autofocus>Sign in</Button>
{/snippet}
</Dialog>
{/if}
{/if}
<style>
.shell { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); min-height: 100dvh; }
.sidebar { background: var(--colonnade); border-right: 1px solid var(--hairline); padding: 22px 14px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100dvh; }
.brand { padding: 4px 10px 18px; }
.nav { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-nav); text-decoration: none; border: 1px solid transparent; }
.nav:hover { background: var(--surface); color: var(--text); }
.nav[aria-current="page"] { background: var(--surface-2); color: var(--text); box-shadow: var(--inset-lit); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
.nav[aria-current="page"] :global(svg) { color: var(--accent); }
.foot { margin-top: auto; font-size: 0.82rem; display: flex; flex-direction: column; gap: 4px; padding: 0 10px; }
main { padding: var(--main-pad); display: flex; flex-direction: column; gap: 18px; min-width: 0; outline: none; }
.topbar, .bottombar { display: none; }
@media (max-width: 719.98px) {
.shell { grid-template-columns: minmax(0, 1fr); }
.sidebar { display: none; }
.topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; }
.topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; }
main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; }
.bottombar { display: grid; grid-template-columns: repeat(4, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
.bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; }
.bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); }
.bottombar a[aria-current="page"] :global(svg) { color: var(--accent); }
}
</style>
@@ -0,0 +1,80 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §7.1: the apply checklist, its countdown and the queued state.
import { Button, Icon, Progress } from "@ianitor/ui";
import type { ApplyView } from "../lib/types";
import { app, secondsLeft } from "../lib/app.svelte";
let { apply, oncancel }: { apply: ApplyView; oncancel?: () => void } = $props();
const engine = $derived(app.overview?.engine.running === "caddy" ? "Caddy" : "Pingora");
const watchSeconds = $derived(app.overview?.site?.watch_seconds ?? 60);
const left = $derived(apply.watch ? secondsLeft(apply.watch.ends_at) : watchSeconds);
const st = (k: string) => apply.steps.find((s) => s.key === k)?.state ?? "pending";
const merged = (a: string, b: string) => {
const x = st(a);
const y = st(b);
if (x === "failed" || y === "failed") return "failed";
if (x === "running" || y === "running") return "running";
if (x === "done" && (y === "done" || y === "skipped")) return "done";
return x;
};
const noWatch = $derived(apply.reason?.code === "apply.kept.no_watch");
const rows = $derived([
{ s: st("validate"), t: { pending: "Check the host file", running: "Checking the host file", done: "Checked the host file", failed: "The host file did not pass the check", skipped: "Check the host file" } },
{ s: merged("compile", "write"), t: { pending: "Build the Pingora and Caddy settings", running: "Building the Pingora and Caddy settings", done: "Built the Pingora and Caddy settings", failed: "Could not build the settings", skipped: "Build the Pingora and Caddy settings" } },
{ s: st("reload"), t: { pending: `Reload ${engine}`, running: `Reloading ${engine}`, done: `Reloaded ${engine}, no connections dropped`, failed: `${engine} did not take the new settings`, skipped: `Reload ${engine}` } },
{
s: st("watch"),
t: noWatch
? { pending: "Check that it answers", running: `Checking that it answers: ${left} s left`, done: "It answers", failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." }
: { pending: `Watch health checks for ${watchSeconds} s`, running: `Watching health checks: ${left} s left`, done: `Health checks passed for ${watchSeconds} s`, failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." },
},
]);
const prefix: Record<string, string> = { done: "Done:", running: "Now:", pending: "Next:", failed: "Failed:", skipped: "Skipped:" };
const final = $derived(["kept", "reverted", "failed", "needs_attention"].includes(apply.state));
</script>
{#if apply.state === "queued"}
<p class="ia-status" data-s="running">
<Icon name="clock" />
<span>
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}
</span>
</p>
{#if oncancel}<div><Button onclick={oncancel}>Cancel</Button></div>{/if}
{:else}
<ol class="steps">
{#each rows as r, i (i)}
<li class={r.s}>
{#if r.s === "done"}<Icon name="check" />{:else if r.s === "running"}<Icon name="clock" />{:else if r.s === "failed"}<Icon name="ring" />{:else}<span class="hollow" aria-hidden="true"></span>{/if}
<span><span class="sr-only">{prefix[r.s]}</span>{r.t[r.s as keyof typeof r.t]}</span>
</li>
{/each}
{#if st("watch") === "failed" && !final}
<li class="running"><Icon name="clock" /><span><span class="sr-only">Now:</span>Undoing the change</span></li>
{/if}
</ol>
{#if apply.state === "watching"}
<Progress label="Health watch" max={watchSeconds} now={watchSeconds - left} text="{left} seconds left" />
<p class="ia-hint">You can leave this screen. Other changes wait their turn; only one apply runs at a time.</p>
{/if}
{/if}
<style>
.steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.steps li { display: flex; gap: 10px; align-items: center; }
.steps li.pending { color: var(--muted); }
.steps li.running { color: var(--text); }
.steps li.running :global(svg) { color: var(--accent); }
.steps li.done { color: var(--text-2); }
.steps li.done :global(svg) { color: var(--kept); }
.steps li.failed :global(svg) { color: var(--down); }
.steps li.skipped { color: var(--muted); }
.hollow { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--muted); margin: 2px; }
</style>
+165
View File
@@ -0,0 +1,165 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
// applied banner that stands in for its first line.
import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, firstSentence, when } from "../lib/format";
import type { ApplyView } from "../lib/types";
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
const o = $derived(app.overview);
const last = $derived(o?.last_apply ?? null);
const active = $derived(o?.active_apply ?? null);
const undo = $derived(o?.undo ?? null);
let moved = $state<string | null>(null);
let undoing = $state(false);
let pushing = $state(false);
const dismissKey = $derived(last ? `apply:${last.id}` : "");
function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
if (!a) return summary;
const h = a.hosts[0] ?? "";
switch (a.kind) {
case "add": return `Adding ${h}`;
case "remove": return `Removing ${h}`;
case "edit": return `Changing ${h}`;
case "share_links": return `Turning on share links for ${h}`;
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
default: return summary;
}
}
async function doUndo() {
if (!undo?.target) return;
undoing = true;
moved = null;
try {
await post("/undo", { target_change_id: undo.target.change_id });
await refresh();
} catch (e) {
if (e instanceof ApiError && e.code === "undo.target_moved") {
moved = e.body.message;
await refresh();
} else {
moved = sentence(e);
}
} finally {
undoing = false;
}
}
async function pushNow() {
pushing = true;
try {
await call("POST", "/repo/push", {}, { idem: newKey() });
} catch {
/* the bar shows the push state on the next poll */
} finally {
pushing = false;
await refresh();
}
}
async function cancel(id: string) {
try {
await del(`/applies/${encodeURIComponent(id)}`);
toast("Cancelled before it started. Nothing changed.");
await refresh();
} catch (e) {
moved = sentence(e);
}
}
const keptLine = $derived.by(() => {
if (!last || last.state !== "kept") return "";
const t = when(last.finished_at ?? last.created_at, app.now);
const code = last.reason?.code ?? "";
if (code === "apply.kept.no_watch") return `${last.hosts[0] ?? ""} has no health check, so Ianitor only checked that it answers.`;
const what = code === "apply.kept.removed" ? "removed" : code === "apply.kept.no_edge" ? "saved, nothing checked (development mode)" : `health checks passed for ${o?.site?.watch_seconds ?? 60} s`;
const push = last.push?.state === "pushed" ? `pushed to Gitea as ${last.commit_short}` : last.push?.state === "pending" ? "sending to Gitea" : last.commit_short ? `saved as commit ${last.commit_short}` : "";
return [t, what, push].filter(Boolean).join(" · ");
});
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
// Ticks every second on the local clock (§7.2), not only on the 5 s poll.
const watchLeft = $derived(
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
);
// The outcome's offer, by code (§7.5).
const offer = $derived.by(() => {
const c = last?.reason?.code ?? "";
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
return null;
});
const pushLine = $derived.by(() => {
const p = last?.push;
const remote = "Gitea";
switch (p?.error_code) {
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
}
});
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
</script>
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
{@const parts = firstSentence(last.reason?.message ?? "")}
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
{#snippet actions()}
{#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
{/snippet}
</Banner>
{/if}
{#if last || active}
<section class="ia-bar" aria-label="Last change">
{#if active}
<div class="grow">
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
<span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
{#if active.state === "watching" && watchLeft != null}
{@const total = o?.site?.watch_seconds ?? 60}
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
{/if}
</div>
{#if active.state === "queued"}<Button onclick={() => cancel(active.id)}>Cancel</Button>{:else}<button type="button" class="domi-btn link" onclick={() => onshowsteps(active.id)}>Show steps</button>{/if}
{:else if last}
<div class="grow">
{#if last.state === "kept"}
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
{:else if undo?.target}
<div>Undo: {undo.target.summary}</div>
{/if}
{#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}<div class="ia-sub">{undo.effect}</div>{/if}
{#if moved}<div class="ia-sub" role="status">{moved}</div>{/if}
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
</div>
{#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
{#if undo?.target}
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
describedby={undoReason ? "undo-reason" : undefined}
label="Undo: {undo.target.summary}.{undo.effect ? ' ' + undo.effect + '.' : ''}">Undo</Button>
{/if}
{/if}
</section>
{/if}
<style>
.warn { color: var(--degraded); }
</style>
+29
View File
@@ -0,0 +1,29 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §2.4: the engine chip (click 1 of the switch). On the main screen's header on a
// desktop, in the top bar on a phone (§2.16).
import { Icon } from "@ianitor/ui";
import { app } from "../lib/app.svelte";
const o = $derived(app.overview);
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
const engineLabel = $derived(
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
);
</script>
{#if o}
<button type="button" class="ia-engine" data-engine-chip aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
<Icon name="chevron" />
</button>
{/if}
<style>
@media (max-width: 719.98px) { .desktop { display: none; } }
</style>
@@ -0,0 +1,121 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
// is the confirmation). The switch runs in control; this polls GET /engine until it ends.
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
import { call, get, newKey, sentence } from "../lib/api";
import { app, refresh } from "../lib/app.svelte";
import { whenInline } from "../lib/format";
import type { EngineView } from "../lib/types";
let { onclose }: { onclose: () => void } = $props();
const e = $derived(app.overview?.engine ?? null);
const running = $derived(e?.running ?? "pingora");
const name = $derived(running === "caddy" ? "Caddy" : "Pingora");
const other = $derived(running === "caddy" ? "Pingora" : "Caddy");
const target = $derived(running === "caddy" ? "pingora" : "caddy");
let switching = $state(false);
let problem = $state<string | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
onDestroy(() => clearTimeout(timer));
let activeLinks = $state(0);
onMount(async () => {
try {
const l = await get<{ items: { state: string }[] }>("/share-links", { quiet: true });
activeLinks = l.items.filter((x) => x.state === "active").length;
} catch {
/* the count is only a hint */
}
});
const fr = $derived(e?.fallback_ready ?? null);
const differs = $derived(fr ? fr.compared - fr.matched : 0);
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
async function doSwitch() {
problem = null;
switching = true;
const from = name;
const to = other;
try {
await call("POST", "/engine", { target }, { idem: newKey() });
const poll = async () => {
try {
const v = await get<EngineView>("/engine", { quiet: true });
if (v.state === "switching") {
timer = setTimeout(poll, 1000);
return;
}
switching = false;
await refresh();
if (v.last_error) {
app.switchResult = { ok: false, title: `${to} did not start, so ${from} is serving again.`, text: "Visitors had a short break and nothing else changed.", detail: v.last_error.detail ?? null };
} else {
app.switchResult = { ok: true, title: `Now serving with ${to}.`, text: "Switch back from the engine chip at any time; it is the same 2 clicks." };
}
onclose();
} catch {
// Contact may drop for a few seconds while the engines change (§9.2).
timer = setTimeout(poll, 1000);
}
};
timer = setTimeout(poll, 500);
} catch (err) {
switching = false;
problem = sentence(err);
}
}
</script>
<Dialog title={e?.state === "stopped" ? `${name} is not answering` : `Serving with ${name}`} kind="popover" modal={false} escape={!switching} toggle="[data-engine-chip]" {onclose}>
<p class="ia-label">Engine</p>
{#if e?.state === "stopped"}
<p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
{:else}
<p class="ia-text2">
{#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}
</p>
{#if running === "pingora" && !notReady && fr?.differences.length}
<Details detail={fr.differences.join("\n")} />
{/if}
{/if}
<div class="ia-card">
<p><strong>What happens</strong></p>
<ul>
<li>{name} stops and {other} starts. New visits reach {other} in about 2 seconds.</li>
<li>Open connections close; videos and uploads in progress restart.</li>
<li>Hosts and certificates stay the same.</li>
{#if running === "pingora"}
<li>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}</li>
<li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
{:else}
<li>Share links work again.</li>
{/if}
<li>This page may lose contact for a few seconds.</li>
</ul>
</div>
{#if switching}
<p class="ia-status" data-s="running" role="status"><Icon name="clock" /><strong>Switching to {other}</strong></p>
<Progress label="Switching engine" max={1} now={0} text="{name} stopping, starting {other}" />
{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if disabledReason}<p class="ia-hint" id="switch-reason">{disabledReason}</p>{/if}
{#snippet footer()}
<Button onclick={onclose}>Cancel</Button>
<Button variant={e?.state === "stopped" ? "primary" : "outline"} icon="swap" onclick={doSwitch} pending={switching}
disabled={!!disabledReason} describedby={disabledReason ? "switch-reason" : undefined}>Switch to {other}</Button>
{/snippet}
</Dialog>
<style>
ul { margin: 6px 0 0; padding-left: 1.1rem; color: var(--text-2); }
</style>
+142
View File
@@ -0,0 +1,142 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §2.5 and §5.1: the host list, sorted down, degraded, pending, unknown, healthy.
import { Status } from "@ianitor/ui";
import type { StatusKind } from "@ianitor/ui";
import HostMenu from "./HostMenu.svelte";
import { app, changesBlocked } from "../lib/app.svelte";
import { ago, duration } from "../lib/format";
import type { HostRow } from "../lib/types";
let {
hosts,
onedit,
onremove,
onshare,
onhistory,
onretry,
}: {
hosts: HostRow[];
onedit: (h: string) => void;
onremove: (h: string) => void;
onshare: (h: string) => void;
onhistory: (h: string) => void;
onretry: (h: string) => void;
} = $props();
const ORDER: Record<string, number> = { down: 0, degraded: 1, pending: 2, unknown: 3, healthy: 4 };
const sorted = $derived([...hosts].sort((a, b) => (ORDER[a.health.state] ?? 5) - (ORDER[b.health.state] ?? 5) || a.hostname.localeCompare(b.hostname)));
const running = $derived(app.overview?.active_apply ? (app.overview.last_apply?.hosts ?? []) : []);
const underCaddy = $derived(app.overview?.engine.running === "caddy");
function kind(h: HostRow): [StatusKind, string] {
switch (h.health.state) {
case "healthy": return ["healthy", "healthy"];
case "degraded": return ["degraded", "degraded"];
case "down": return ["down", "down"];
case "pending": return ["unknown", "waiting"];
default: return ["unknown", "not checked"];
}
}
function since(h: HostRow): string {
return h.health.since ? duration((app.now - Date.parse(h.health.since)) / 1000) : "a while";
}
function sub(h: HostRow): { text: string; problem: boolean } {
const f = h.health.failure;
const visitors = 'Visitors get an error page.';
switch (h.health.state) {
case "healthy": {
const added = h.added_at && app.now - Date.parse(h.added_at) < 86_400_000 ? "Added today · c" : "C";
const lat = h.health.latency_ms != null && !underCaddy ? ` · ${h.health.latency_ms} ms` : "";
return { text: `${added}hecked ${ago(h.health.last_check_at, app.now)}${lat}`, problem: false };
}
case "degraded": {
const ok = h.health.upstreams.filter((u) => u.state === "healthy").length;
const m = h.health.upstreams.length;
if (m > 1) return { text: `${ok} of ${m} addresses answer. Visitors are sent to the ones that do.`, problem: true };
return { text: `Answering only some checks.`, problem: true };
}
case "down":
if (f?.kind === "refused") return { text: `Connection refused for ${since(h)}. ${visitors}`, problem: true };
if (f?.kind === "timeout") return { text: `Not answering for ${since(h)}. ${visitors}`, problem: true };
if (f?.kind === "name") return { text: `The name ${f.upstream ?? ""} cannot be found. ${visitors}`, problem: true };
if (f?.kind === "tls") return { text: `The certificate of ${f.upstream ?? ""} cannot be checked.`, problem: true };
return { text: `Answering with an error page for ${since(h)}.`, problem: true };
case "pending": return { text: "Waiting for the first check.", problem: false };
default: return { text: "No health check set for this host.", problem: false };
}
}
function phoneDetail(h: HostRow): string {
if (h.health.state === "healthy" && h.health.latency_ms != null) return `${h.health.latency_ms} ms`;
if (h.health.state === "down" && h.health.failure?.kind === "refused") return `refused for ${since(h)}`;
if (h.health.state === "unknown") return "no health check";
if (h.added_at && app.now - Date.parse(h.added_at) < 86_400_000) return "added today";
return h.share_links ? "share links on" : "";
}
function chips(h: HostRow): string[] {
const c = [h.tls === "domi" ? "Domi certificate" : "Let's Encrypt"];
c.push(h.auth === "forward-auth" ? "Sign-in first" : "Open to anyone");
if (h.share_links) c.push("Share links on");
if (h.device_certs) c.push("Device certificate needed");
if (!h.websockets) c.push("No websockets");
return c;
}
const blocked = $derived(changesBlocked());
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are off while Caddy serves." : "Share links are not set up on this server.") : null);
</script>
<div class="ia-list" role="table" aria-label="Hosts">
<div class="ia-row head" role="row">
<span class="ia-label col-status" role="columnheader">Status</span>
<span class="ia-label" role="columnheader">Host</span>
<span class="ia-label desktop" role="columnheader">Sends traffic to</span>
<span role="columnheader"><span class="sr-only">More</span></span>
</div>
{#each sorted as h (h.hostname)}
{@const [k, w] = kind(h)}
{@const s = sub(h)}
<div class="ia-row" role="row">
<span class="col-status" role="cell"><Status kind={k} word={w} /></span>
<span role="cell">
<span class="phone-dot"><Status kind={k} word="" /></span>
<span class="ia-host">{h.hostname}</span>
<span class="ia-chips desktop">{#each chips(h) as c (c)}<span class="ia-chip">{c}</span>{/each}</span>
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
</span>
<span role="cell" class="desktop">
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1}{" "}<span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
{#if h.certificate.state === "failed"}
<span class="ia-sub" style="display:block;color:var(--down)">Let's Encrypt could not confirm <strong>{h.hostname}</strong>. The name must point to this server, and port 80 must be open from the internet.
<button type="button" class="domi-btn link" onclick={() => onretry(h.hostname)}>Try again</button></span>
{/if}
</span>
<span role="cell">
<HostMenu hostname={h.hostname} items={[
{ label: "Share link", icon: "link", reason: shareReason, run: () => 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) },
]} />
</span>
</div>
{/each}
</div>
<style>
.phone, .phone-dot { display: none; }
.problem { color: var(--text-2) !important; }
@media (max-width: 719.98px) {
.desktop { display: none !important; }
.phone { display: block; padding-left: 22px; }
.phone-dot { display: inline; }
}
</style>
+88
View File
@@ -0,0 +1,88 @@
<!-- 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/. -->
<script lang="ts" module>
import type { IconName } from "@ianitor/ui";
export interface Item {
label: string;
icon: IconName;
danger?: boolean;
reason?: string | null;
divider?: boolean;
run: () => void;
}
</script>
<script lang="ts">
// Handoff §2.6: the row's ⋯ menu (WAI-ARIA menu button).
import { tick } from "svelte";
import { Icon } from "@ianitor/ui";
let { hostname, items }: { hostname: string; items: Item[] } = $props();
let open = $state(false);
let btn: HTMLButtonElement | undefined = $state();
let list: HTMLUListElement | undefined = $state();
const id = "menu-" + Math.random().toString(36).slice(2, 9);
const nodes = () => Array.from(list?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? []);
async function show(focus: "first" | "last" = "first") {
open = true;
await tick();
const n = nodes();
(focus === "first" ? n[0] : n[n.length - 1])?.focus();
}
function close(back = true) {
open = false;
if (back) btn?.focus();
}
function key(e: KeyboardEvent) {
const n = nodes();
const i = n.indexOf(document.activeElement as HTMLElement);
if (e.key === "ArrowDown") { e.preventDefault(); n[(i + 1) % n.length]?.focus(); }
else if (e.key === "ArrowUp") { e.preventDefault(); n[(i - 1 + n.length) % n.length]?.focus(); }
else if (e.key === "Home") { e.preventDefault(); n[0]?.focus(); }
else if (e.key === "End") { e.preventDefault(); n[n.length - 1]?.focus(); }
else if (e.key === "Escape") { e.preventDefault(); close(); }
else if (e.key === "Tab") close(false);
}
function pick(it: Item) {
if (it.reason) return;
// Focus back on More first: a dialog the item opens returns focus there when it closes
// (§2.9), not to a menu item that no longer exists.
close(true);
it.run();
}
function outside(e: MouseEvent) {
if (open && !(e.target instanceof Node && (list?.contains(e.target) || btn?.contains(e.target)))) close(false);
}
</script>
<svelte:window onclick={outside} />
<div class="ia-menu-wrap">
<button bind:this={btn} type="button" class="ia-icon-btn" aria-label="More for {hostname}" aria-haspopup="menu"
aria-expanded={open} aria-controls={id}
onclick={() => (open ? close() : show())}
onkeydown={(e) => { if (e.key === "ArrowDown") { e.preventDefault(); show("first"); } else if (e.key === "ArrowUp") { e.preventDefault(); show("last"); } }}>
<Icon name="dots" />
</button>
{#if open}
<ul bind:this={list} class="ia-menu" role="menu" id={id} aria-label={hostname} tabindex="-1" onkeydown={key}>
{#each items as it (it.label)}
{#if it.divider}<li role="separator"><hr /></li>{/if}
<li role="none">
<button type="button" role="menuitem" tabindex="-1" class:danger={it.danger} aria-disabled={it.reason ? "true" : undefined} onclick={() => pick(it)}>
<Icon name={it.icon} />{it.label}
{#if it.reason}<span class="reason">{it.reason}</span>{/if}
</button>
</li>
{/each}
</ul>
{/if}
</div>
+538
View File
@@ -0,0 +1,538 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §6 and §7: the add/edit panel, its validation on blur, Apply, and the progress and
// outcome of the apply it starts. Every decision comes from control; the form only carries it.
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
import { FINAL, follow } from "../lib/applies";
import { firstSentence } from "../lib/format";
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
let {
hostname,
resume,
prefill,
focusField,
onclose,
}: {
hostname?: string;
resume?: string;
prefill?: HostSpec | null;
focusField?: string;
onclose: () => void;
} = $props();
const site = $derived(app.overview?.site ?? null);
const signinOk = $derived(site?.forward_auth_configured ?? false);
// ---- the form
type Rule = { action: "set" | "remove"; name: string; kind: "value" | "secret"; value: string; secret: string };
let host = $state({
hostname: "",
upstreams: [""],
tls: "domi" as "domi" | "letsencrypt",
auth: "forward-auth" as "forward-auth" | "none",
websockets: true,
share_links: false,
device_certs: false,
access_log: "off" as "off" | "truncated",
hc: false,
hcPath: "/",
hcEvery: 30,
req: [] as Rule[],
resp: [] as Rule[],
});
let rev = $state<string | null>(null);
let more = $state(false);
let loading = $state(true);
let notFound = $state<string | null>(null);
let errors = $state<Record<string, ErrorBody>>({});
let touched = $state<Record<string, boolean>>({});
let summary = $state("");
let underFooter = $state("");
let conflict = $state<ErrorBody | null>(null);
let topError = $state<ApiError | null>(null);
let idem = newKey();
let lastBody = "";
// ---- the apply
let apply = $state<ApplyView | null>(null);
let restoring = $state(false);
let restoreProblem = $state<string | null>(null);
let phase = $state<"form" | "progress">("form");
let stop: (() => void) | undefined;
let closeTimer: ReturnType<typeof setTimeout> | undefined;
function fromSpec(s: HostSpec) {
host.hostname = s.hostname;
host.upstreams = s.upstreams.length ? [...s.upstreams] : [""];
host.tls = s.tls;
host.auth = s.auth;
host.websockets = s.websockets;
host.share_links = s.share_links;
host.device_certs = !!s.device_certs;
host.access_log = s.access_log;
host.hc = !!s.health_check;
host.hcPath = s.health_check?.path ?? "/";
host.hcEvery = s.health_check?.interval_secs ?? 30;
const rule = (r: HeaderRule): Rule => ({ action: r.action, name: r.name, kind: r.secret ? "secret" : "value", value: r.value ?? "", secret: r.secret ?? "" });
host.req = (s.request_headers ?? []).map(rule);
host.resp = (s.response_headers ?? []).map(rule);
if (host.hc || host.req.length || host.resp.length || !host.websockets || host.share_links || host.access_log !== "off" || host.device_certs) more = true;
}
function spec(): HostSpec {
const rules = (rs: Rule[]): HeaderRule[] =>
rs.map((r) =>
r.action === "remove"
? { action: "remove", name: r.name }
: r.kind === "secret"
? { action: "set", name: r.name, secret: r.secret }
: { action: "set", name: r.name, value: r.value },
);
// The UI always sends every field explicitly (the schema's own defaults differ).
return {
hostname: host.hostname.trim(),
upstreams: host.upstreams.map((u) => u.trim()).filter((u, i) => u !== "" || i === 0),
tls: host.tls,
auth: host.auth,
websockets: host.websockets,
share_links: host.share_links,
device_certs: host.device_certs,
access_log: host.access_log,
health_check: host.hc ? { path: host.hcPath, interval_secs: Number(host.hcEvery) } : null,
request_headers: rules(host.req),
response_headers: rules(host.resp),
};
}
onMount(async () => {
if (resume) {
phase = "progress";
stop = follow(resume, onApply);
}
if (prefill) {
fromSpec(prefill);
} else if (hostname) {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
} catch (e) {
notFound = sentence(e);
}
} else {
rev = app.overview?.rev ?? null;
if (!signinOk) host.auth = "none";
}
// A form saved before this tab went to sign in comes back (App.svelte, signIn).
try {
const raw = sessionStorage.getItem(DRAFT);
const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
if (d && d.hostname === (hostname ?? "") && !resume) {
Object.assign(host, d.host);
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
}
sessionStorage.removeItem(DRAFT);
} catch {
/* no storage: nothing to bring back */
}
loading = false;
if (phase === "form") {
// The Dialog focused its heading while this said "Loading…": now the first field
// (Hostname; Send traffic to when editing), so typing right after opening works.
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
if (f.startsWith("health_check")) more = true;
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
window.addEventListener("ianitor:save-draft", saveDraft);
});
const DRAFT = "ianitor-draft";
function saveDraft() {
if (phase !== "form") return;
try {
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
} catch {
/* no storage */
}
}
onDestroy(() => {
stop?.();
clearTimeout(closeTimer);
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
});
function fieldId(f: string): string {
return "f-" + f.replace(/[^a-z0-9]+/gi, "-");
}
const errAt = (f: string) => errors[f];
function setErrors(list: ErrorBody[], only?: string) {
const next: Record<string, ErrorBody> = only ? { ...errors } : {};
if (only) {
for (const k of Object.keys(next)) if (k === only || k.startsWith(only + "[")) delete next[k];
}
for (const e of list) {
const f = e.field ?? "";
if (!f) continue;
if (only && !(f === only || f.startsWith(only + "["))) continue;
next[f] = e;
}
errors = next;
}
// Validation on blur (§2.10): only the field that lost focus, debounced.
let blurTimer: ReturnType<typeof setTimeout> | undefined;
function blur(field: string) {
touched[field] = true;
clearTimeout(blurTimer);
blurTimer = setTimeout(async () => {
try {
await call("POST", `/hosts/validate?mode=${hostname ? "edit" : "create"}`, spec());
setErrors([], field);
} catch (e) {
if (e instanceof ApiError) setErrors(e.errors.length ? e.errors : [e.body], field);
}
}, 300);
}
async function submit(e?: Event) {
e?.preventDefault();
if (changesBlocked()) return;
const body = spec();
const text = JSON.stringify(body);
if (text !== lastBody) {
idem = newKey();
lastBody = text;
}
underFooter = "";
conflict = null;
topError = null;
try {
const path = hostname ? `/hosts/${encodeURIComponent(hostname)}` : "/hosts";
const a = await call<{ apply: ApplyView }>(hostname ? "PUT" : "POST", path, { host: body, base_rev: rev }, { idem });
const ap = a.data?.apply;
if (!ap) return;
apply = ap;
phase = "progress";
stop?.();
stop = follow(ap.id, onApply);
} catch (err) {
if (!(err instanceof ApiError)) {
topError = null;
underFooter = sentence(err);
return;
}
if (err.code === "change.conflict") {
conflict = err.body;
return;
}
if (err.code === "change.unchanged") {
underFooter = "This is the same as what is live now, so nothing changed.";
return;
}
const list = err.errors.length ? err.errors : err.body.field ? [err.body] : [];
if (list.length) {
setErrors(list);
for (const x of list) if (x.field) touched[x.field] = true;
summary = `${list.length} ${list.length === 1 ? "thing" : "things"} to fix before Apply.`;
const first = list.find((x) => x.field)?.field;
if (first?.startsWith("health_check") || first?.includes("headers")) more = true;
if (first) setTimeout(() => document.getElementById(fieldId(first))?.focus(), 0);
} else {
topError = err;
}
}
}
function onApply(a: ApplyView) {
apply = a;
if (a.state === "kept") {
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
closeTimer = setTimeout(() => onclose(), 1500);
}
}
async function cancelQueued() {
if (!apply) return;
try {
await del(`/applies/${encodeURIComponent(apply.id)}`);
toast("Cancelled before it started. Nothing changed.");
stop?.();
phase = "form";
apply = null;
} catch (e) {
underFooter = sentence(e);
}
}
function editAgain(field?: string) {
stop?.();
phase = "form";
apply = null;
idem = newKey();
const f = field ?? "upstreams[0]";
if (f.startsWith("health_check")) {
more = true;
host.hc = true;
}
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
async function keepMine() {
if (!hostname) {
rev = app.overview?.rev ?? rev;
} else {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
rev = d.rev;
} catch {
/* keep the old rev */
}
}
await refresh();
if (!hostname) rev = app.overview?.rev ?? rev;
conflict = null;
}
async function useTheirs() {
if (!hostname) return;
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
conflict = null;
}
const name = $derived(host.hostname.trim() || hostname || "the host");
const heading = $derived.by(() => {
if (phase !== "progress" || !apply) return hostname ? `Edit ${hostname}` : "New host";
const h = apply.hosts[0] ?? name;
switch (apply.kind) {
case "add":
return `Adding ${h}`;
case "remove":
return `Removing ${h}`;
case "share_links":
return `Turning on share links for ${h}`;
case "undo":
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
case "restore":
return apply.summary.replace(/^Restored /, "Restoring ");
default:
return `Changing ${h}`;
}
});
const reasonOffer = $derived.by(() => {
const c = apply?.reason?.code ?? "";
if (/apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: "" };
if (c.startsWith("apply.reverted") || c === "apply.failed.validation" || c.startsWith("pki.")) return { label: "Edit and try again", field: apply?.reason?.field ?? undefined };
return null;
});
const blocked = $derived(changesBlocked());
const shareWarning = $derived(host.auth === "none" && host.share_links);
</script>
<Dialog title={heading} kind="panel" {onclose}>
{#if loading}
<p class="ia-muted">Loading…</p>
{:else if notFound}
<Banner tone="notice" live="status">{#snippet title()}{notFound}{/snippet}
{#snippet actions()}<Button onclick={onclose}>Back to hosts</Button>{/snippet}
</Banner>
{:else if phase === "progress" && apply}
<div aria-live="polite" class="sr-only">
{#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}
</div>
<ApplyProgress {apply} oncancel={cancelQueued} />
{#if apply.state === "kept"}
<Banner tone="kept">
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {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}
</Banner>
{:else if apply.state === "reverted" || apply.state === "failed"}
{@const parts = firstSentence(apply.reason?.message ?? "")}
<Banner tone="notice" live="status">
{#snippet title()}<span class="ia-status" data-s="reverted"><span class="word">{apply?.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#snippet actions()}
{#if reasonOffer}
<Button variant="outline" onclick={() => (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}</Button>
{/if}
{/snippet}
</Banner>
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
{:else if apply.state === "needs_attention"}
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
{#snippet actions()}
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if}
{:else}
<form id="host-form" onsubmit={submit} novalidate>
{#if summary}<p class="sr-only" role="alert">{summary}</p>{/if}
{#if conflict}
<Banner tone="notice" live="status">
{#snippet title()}{conflict?.message}{/snippet}
{#snippet actions()}<Button onclick={keepMine}>Keep my edits</Button>{#if hostname}<Button onclick={useTheirs}>Use the new version</Button>{/if}{/snippet}
</Banner>
{/if}
{#if topError}
<Banner tone="notice" live="status">{#snippet title()}{sentence(topError)}{/snippet}</Banner>
{#if topError.body.detail}<Details detail={topError.body.detail} reference={topError.requestId} />{/if}
{/if}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("hostname")}>Hostname</label>
<input id={fieldId("hostname")} class="domi-input" bind:value={host.hostname} readonly={!!hostname}
autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-invalid={errAt("hostname") && touched["hostname"] ? "true" : undefined}
aria-describedby="{fieldId('hostname')}-e {fieldId('hostname')}-h" onblur={() => blur("hostname")} />
{#if errAt("hostname") && touched["hostname"]}
<p class="domi-error" id="{fieldId('hostname')}-e"><Icon name="ring" />{errAt("hostname").message}
{#if errAt("hostname").params?.suggestion}
<button type="button" class="domi-btn link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button>
{/if}
</p>
{/if}
{#if hostname}<p class="ia-hint" id="{fieldId('hostname')}-h">To use another address, add a new host and remove this one.</p>{/if}
</div>
{#each host.upstreams as _, i (i)}
{@const f = `upstreams[${i}]`}
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
<div class="domi-field">
{#if i === 0}<label class="domi-field-label" for={fieldId(f)}>Send traffic to</label>{/if}
<div class="row">
<input id={fieldId(f)} class="domi-input" bind:value={host.upstreams[i]} autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-label={i === 0 ? undefined : `Also send traffic to, address ${i + 1}`}
aria-invalid={err && (touched[f] || touched["upstreams"]) ? "true" : undefined}
aria-describedby="{fieldId(f)}-e" onblur={() => blur(f)} />
{#if i > 0}<button type="button" class="ia-icon-btn" aria-label="Remove this address" onclick={() => host.upstreams.splice(i, 1)}><Icon name="trash" /></button>{/if}
</div>
{#if err && (touched[f] || touched["upstreams"])}
<p class="domi-error" id="{fieldId(f)}-e"><Icon name="ring" />{err.message}
{#if err.params?.suggestion}<button type="button" class="domi-btn link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button>{/if}
</p>
{/if}
{#if i === 0 && host.upstreams.length === 1}<p class="ia-hint">Add another address later for a second server.</p>{/if}
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => host.upstreams.push("")}>Add another address</button></div>
<Segmented legend="Certificate" name="tls" bind:value={host.tls}
options={[{ value: "domi", label: "Domi certificate" }, { value: "letsencrypt", label: "Let's Encrypt" }]} />
<p class="ia-hint">Domi for home devices only; Let's Encrypt for a public site.</p>
<Segmented legend="Who can open it" name="auth" bind:value={host.auth} disabled={signinOk ? [] : ["forward-auth"]}
options={[{ value: "forward-auth", label: "Sign in first" }, { value: "none", label: "Anyone" }]} />
{#if !signinOk}<p class="ia-hint">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.</p>{/if}
{#if errAt("auth")}<p class="domi-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
<div>
<button type="button" class="domi-btn link" aria-expanded={more} aria-controls="more-options" onclick={() => (more = !more)}>
More options: headers, websockets, health check, share links, visit log
</button>
</div>
{#if more}
<div id="more-options" class="more">
<div class="domi-field">
<span class="domi-field-label">Health check</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.hc} /> Check that it answers</label>
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
</div>
{#if host.hc}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.path")}>Health check address</label>
<input id={fieldId("health_check.path")} class="domi-input" bind:value={host.hcPath} aria-invalid={errAt("health_check.path") ? "true" : undefined} onblur={() => blur("health_check.path")} />
{#if errAt("health_check.path")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.path").message}</p>{/if}
<p class="ia-hint">Use an address that answers without signing in, like /health.</p>
</div>
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
<div class="row"><input id={fieldId("health_check.interval_secs")} class="domi-input narrow" type="number" min="1" max="3600" bind:value={host.hcEvery} onblur={() => blur("health_check.interval_secs")} /> <span class="ia-text2">seconds</span></div>
{#if errAt("health_check.interval_secs")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
</div>
{/if}
<div class="domi-field">
<span class="domi-field-label">Websockets</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.websockets} /> Allow websockets</label>
<p class="ia-hint">Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.</p>
</div>
<div class="domi-field">
<span class="domi-field-label">Share links</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.share_links} /> Allow share links</label>
<p class="ia-hint">Lets you make links that open this host without signing in, until they expire.</p>
{#if shareWarning}<p class="ia-hint">Anyone can already open {name}, so a share link changes nothing.</p>{/if}
</div>
<div class="domi-field">
<span class="domi-field-label">Device certificates</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.device_certs} /> Only devices with a Domi device certificate</label>
<p class="ia-hint">Phones, computers and apps need a certificate from Certificates before they can open it.</p>
</div>
<Segmented legend="Visit log" name="access_log" bind:value={host.access_log} options={[{ value: "off", label: "Off" }, { value: "truncated", label: "On" }]} />
<p class="ia-hint">On keeps a log on this server, with visitor addresses shortened.</p>
{#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)}
<div class="domi-field">
<span class="domi-field-label">{group.title}</span>
{#each group.rules as r, i (i)}
{@const p = `${group.list}[${i}]`}
<div class="rule ia-card">
<Segmented legend="Rule {i + 1}" name="{p}-action" bind:value={r.action} options={[{ value: "set", label: "Set" }, { value: "remove", label: "Remove" }]} />
<label class="domi-field-label" for={fieldId(p + ".name")}>Header name</label>
<input id={fieldId(p + ".name")} class="domi-input" bind:value={r.name} onblur={() => blur(p + ".name")} />
{#if r.action === "set"}
{#if group.secrets}
<Segmented legend="Value" name="{p}-kind" bind:value={r.kind} disabled={(site?.secrets.length ?? 0) === 0 ? ["secret"] : []} options={[{ value: "value", label: "Fixed value" }, { value: "secret", label: "Secret" }]} />
{/if}
{#if r.kind === "secret" && group.secrets}
<select class="domi-input" bind:value={r.secret} aria-label="Secret">
{#each site?.secrets ?? [] as s (s)}<option value={s}>{s}</option>{/each}
</select>
{:else}
<input class="domi-input" bind:value={r.value} aria-label="Value" onblur={() => blur(p + ".value")} />
{/if}
{/if}
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="domi-error"><Icon name="ring" />{e.message}</p>{/each}
<button type="button" class="ia-icon-btn" aria-label="Remove this rule" onclick={() => group.rules.splice(i, 1)}><Icon name="trash" /></button>
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => group.rules.push({ action: "set", name: "", kind: "value", value: "", secret: site?.secrets[0] ?? "" })}>Add a rule</button></div>
{#if group.secrets && (site?.secrets.length ?? 0) === 0}<p class="ia-hint">No secrets are listed in ianitor.toml.</p>{/if}
</div>
{/each}
</div>
{/if}
</form>
{/if}
{#snippet footer()}
{#if phase === "form" && !loading && !notFound}
{#if underFooter}<p class="ia-hint full" role="status">{underFooter}</p>{/if}
{#if blocked}<p class="ia-hint full" id="apply-blocked">{blocked}</p>{/if}
<Button onclick={onclose}>Cancel</Button>
<Button variant="primary" type="submit" form="host-form" disabled={!!blocked} describedby={blocked ? "apply-blocked" : undefined}>Apply</Button>
{:else if phase === "progress" && apply && FINAL.includes(apply.state)}
<Button onclick={onclose}>Close</Button>
{/if}
{/snippet}
</Dialog>
<style>
form { display: flex; flex-direction: column; gap: 16px; }
.row { display: flex; gap: 8px; align-items: center; }
.more { display: flex; flex-direction: column; gap: 16px; }
.rule { display: flex; flex-direction: column; gap: 8px; }
.narrow { max-width: 8rem; }
.full { flex-basis: 100%; }
</style>
@@ -0,0 +1,65 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §13.5: the intermediate banner. Renew is 1 click; the banner then shows the match
// code. Until Custos can sign (docs/custos-ticket.md) the request is signed by hand offline,
// so the waiting banner links to that page.
import { Banner, Button } from "@ianitor/ui";
import { del, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft } from "../lib/app.svelte";
import { duration, longDate } from "../lib/format";
import type { PkiRequest } from "../lib/types";
const i = $derived(app.overview?.intermediate ?? null);
let pending = $state(false);
let problem = $state<string | null>(null);
async function renew() {
pending = true;
problem = null;
try {
await post<PkiRequest>("/certs/intermediate/renewal");
await refresh();
} catch (e) {
problem = sentence(e);
} finally {
pending = false;
}
}
async function cancel(id: string) {
try {
await del(`/pki-requests/${encodeURIComponent(id)}`);
await refresh();
} catch (e) {
problem = sentence(e);
}
}
</script>
{#if app.renewedUntil}
<Banner tone="kept" live="status" ondismiss={() => (app.renewedUntil = null)}>
{#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet}
</Banner>
{:else if i?.renewal}
{@const r = i.renewal}
<Banner tone="notice" label="Domi intermediate certificate">
{#snippet title()}
<span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
{/snippet}
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
{#snippet actions()}
<Button variant="outline" onclick={() => navigate("/certificates/renew-by-hand")}>Sign it by hand</Button>
<Button onclick={() => cancel(r.request_id)}>Cancel request</Button>
{/snippet}
</Banner>
{:else if i?.banner}
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
{#snippet title()}<strong>{i.banner?.message}</strong>{/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()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
</Banner>
{/if}
+163
View File
@@ -0,0 +1,163 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §8.2: mint on open (click 2), Copy link (click 3). Changing an option re-mints with
// `replaces`, so one link from this dialog is valid at a time; closing without copying stops it.
// Links off: "Turn on share links" applies the change, then Copy link (4 clicks: open
// question Q1 is not decided, so this is the fallback path the design allows).
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, newKey, patch, sentence } from "../lib/api";
import { app } from "../lib/app.svelte";
import { follow } from "../lib/applies";
import { longDate } from "../lib/format";
import type { ApplyView, MintedLink } from "../lib/types";
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
// Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
// svelte-ignore state_referenced_locally
let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links);
let link = $state<MintedLink | null>(null);
let minting = $state(false);
let copied = $state(false);
let copiedBefore = $state(false);
let refused = $state(false);
let problem = $state<string | null>(null);
let fieldErr = $state<{ field: string; message: string } | null>(null);
let days = $state<"1" | "7" | "30">("7");
let prefix = $state("/");
let showPassword = $state(false);
let password = $state("");
let usingPassword = $state(false);
let turning = $state<ApplyView | null>(null);
let stopFollow: (() => void) | undefined;
let secretBox: HTMLTextAreaElement | undefined = $state();
onMount(() => {
if (on) void mint();
});
onDestroy(() => stopFollow?.());
async function mint() {
minting = true;
problem = null;
fieldErr = null;
try {
const body: Record<string, unknown> = { path_prefix: prefix || "/", expires_in_s: Number(days) * 86400 };
if (usingPassword && password) body.password = password;
if (link) body.replaces = link.id;
const a = await call<MintedLink>("POST", `/hosts/${encodeURIComponent(hostname)}/share-links`, body, { idem: newKey() });
if (link && copied) copiedBefore = true;
link = a.data;
copied = false;
} catch (e) {
if (e instanceof ApiError && e.body.field) {
fieldErr = { field: e.body.field, message: e.body.message };
if (e.body.field === "password") usingPassword = false;
}
else problem = sentence(e);
} finally {
minting = false;
}
}
async function copy() {
if (!link) return;
try {
await navigator.clipboard.writeText(link.url);
copied = true;
refused = false;
} catch {
refused = true;
secretBox?.select();
}
}
async function turnOn() {
try {
const a = await patch<{ apply: ApplyView }>(`/hosts/${encodeURIComponent(hostname)}`, { share_links: true, base_rev: app.overview?.rev ?? null });
turning = a.apply;
stopFollow = follow(a.apply.id, async (x) => {
turning = x;
if (x.state === "kept") {
on = true;
await mint();
}
});
} catch (e) {
problem = sentence(e);
}
}
function close() {
// A link nobody copied does not stay valid.
if (link && !copied) void del(`/share-links/${encodeURIComponent(link.id)}`, { keepalive: true }).catch(() => {});
onclose();
}
const underCaddy = $derived(app.overview?.engine.running === "caddy");
</script>
<Dialog title="Share {hostname}" onclose={close}>
{#if !on}
{#if turning}
<ApplyProgress apply={turning} />
{#if turning.state === "reverted" || turning.state === "failed"}
<Banner tone="notice" live="status">{#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet}</Banner>
{/if}
{:else}
<p><strong>Share links are off for {hostname}.</strong></p>
<p class="ia-text2">Turning them on is a change to the host, checked like any other.</p>
{#if problem}<p class="domi-error" role="alert"><Icon name="ring" />{problem}</p>{/if}
<div><Button variant="outline" onclick={turnOn} disabled={!!app.overview?.paused}>Turn on share links</Button></div>
{/if}
{:else}
<p class="ia-text2">Anyone with this link can open the site without signing in, until it expires.</p>
{#if underCaddy}
<Banner tone="notice">{#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}</Banner>
{/if}
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if link}
<textarea bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLTextAreaElement).select()}></textarea>
{:else if minting}
<p class="ia-muted">Making the link…</p>
{/if}
{#if copied}
<p class="ia-status" data-s="kept" role="status"><Icon name="check" /><span>Copied</span></p>
<p class="ia-hint">Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.</p>
{:else}
<Button variant="primary" full icon="copy" onclick={copy} disabled={!link || minting} data-autofocus>Copy link</Button>
{/if}
{#if refused}<p class="ia-hint" role="alert">Your browser did not allow copying. Press Ctrl+C to copy the selected link.</p>{/if}
{#if copiedBefore && !copied}<p class="ia-hint">The link you copied before is stopped. Copy this one.</p>{/if}
<Segmented legend="Expires after" name="expiry" bind:value={days} onchange={() => mint()}
options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
<div class="domi-field">
<label class="domi-field-label" for="share-prefix">Only addresses starting with</label>
<input id="share-prefix" class="domi-input" bind:value={prefix} onblur={() => mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }}
aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} />
{#if fieldErr?.field === "path_prefix"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
<p class="ia-hint">/ shares the whole site. Try /share/summer-2026 for one album.</p>
</div>
{#if usingPassword}
<p class="ia-hint">This link asks for the password.</p>
<div><button type="button" class="domi-btn link" onclick={() => { usingPassword = false; password = ""; void mint(); }}>Remove the password</button></div>
{:else if showPassword}
<div class="domi-field">
<label class="domi-field-label" for="share-password">Password</label>
<input id="share-password" class="domi-input" type="password" autocomplete="new-password" bind:value={password}
aria-invalid={fieldErr?.field === "password" ? "true" : undefined} />
{#if fieldErr?.field === "password"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
<p class="ia-hint">At least 8 characters. Send it to them separately.</p>
<div><Button onclick={() => { usingPassword = true; void mint(); }}>Use this password</Button></div>
</div>
{:else}
<div><button type="button" class="domi-btn link" onclick={() => (showPassword = true)}>Add a password</button></div>
{/if}
{/if}
</Dialog>
+86
View File
@@ -0,0 +1,86 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
// notice, then (on Hosts) the intermediate banner. First on every screen.
import { Banner, Button, Details } from "@ianitor/ui";
import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
import { atTime, whenInline } from "../lib/format";
const o = $derived(app.overview);
let restoring = $state(false);
let problem = $state<string | null>(null);
const restorable = $derived(canRestore());
async function restore() {
restoring = true;
problem = await restoreLastKept();
restoring = false;
}
// §7.6: the bold line and line 2 by the pause's underlying code.
const pause = $derived.by(() => {
const code = o?.paused_reason ?? "";
const message = o?.paused?.message ?? "";
if (code === "apply.needs_attention")
return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" };
if (code === "control.files_unwritten")
return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" };
// control.paused wraps the reason: "Changes are paused: <reason>"; show the reason itself.
const own = message.replace(/^Changes are paused: /, "");
if (/^(repo|file|site)\./.test(code))
return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" };
return { bold: own, line2: "", extra: "" };
});
// "Show details" for every pause (§7.6): the server's detail, the restart command, or the
// full message when there is nothing more.
const pauseDetail = $derived(
[o?.paused_detail, pause.extra].filter(Boolean).join("\n") || (o?.paused ? (o.paused.message ?? "") : ""),
);
async function retry() {
await refresh();
}
</script>
{#if o?.paused}
<Banner tone="down" live="alert">
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"}</span></span> <strong>{pause.bold}</strong>{/snippet}
{#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
{#if restorable && o.undo?.target}<p class="ia-hint">Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.</p>{/if}
{#if problem}<p role="status">{problem}</p>{/if}
{#if pauseDetail}<Details detail={pauseDetail} />{/if}
{#snippet actions()}
{#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if}
{#if app.lostContact}
<Banner tone="down" live="alert">
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/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()}<Button onclick={retry}>Try again now</Button>{/snippet}
</Banner>
{/if}
{#if o?.health_error}
<Banner tone="notice">{#snippet title()}{o.health_error?.message}{/snippet}</Banner>
{/if}
{#if app.switchResult}
{@const r = app.switchResult}
<Banner tone={r.ok ? "kept" : "down"} live="status" ondismiss={() => (app.switchResult = null)}>
{#snippet title()}<strong>{r.title}</strong>{/snippet}
{r.text}
{#if r.detail}<Details detail={r.detail} />{/if}
</Banner>
{/if}
{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)}
<Banner tone="notice">{#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet}</Banner>
{/if}
+184
View File
@@ -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<T> {
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<T>(
method: string,
path: string,
body?: unknown,
opts: CallOptions = {},
): Promise<Answer<T>> {
let rateRetried = false;
for (let attempt = 0; attempt < 12; attempt++) {
const headers: Record<string, string> = { "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 = <T>(path: string, opts?: CallOptions) => call<T>("GET", path, undefined, opts).then((a) => a.data as T);
export const post = <T>(path: string, body: unknown = {}, opts?: CallOptions) =>
call<T>("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const put = <T>(path: string, body: unknown, opts?: CallOptions) =>
call<T>("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const patch = <T>(path: string, body: unknown, opts?: CallOptions) =>
call<T>("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const del = (path: string, opts?: CallOptions) => call<unknown>("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.";
}
+180
View File
@@ -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<void> {
if (app.signedOut) return;
try {
const a = await call<Overview>("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<typeof setTimeout> | 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<string | null> {
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;
}
+63
View File
@@ -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<typeof setTimeout> | 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<ApplyView>(`/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);
};
}
+115
View File
@@ -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<string, string> = {
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;
}
+251
View File
@@ -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<string, string>;
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<string, string>;
}
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;
}
+11
View File
@@ -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 });
+257
View File
@@ -0,0 +1,257 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §13: Certificates → + Device → Issue (3 clicks), approval with the match code, then
// the install (the accepted 4th click). Until Custos can approve, approval is the server
// command control names (docs/pki.md).
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Segmented, Status } from "@ianitor/ui";
import HostMenu from "../components/HostMenu.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte";
import { ApiError, del, get, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, shortDate } from "../lib/format";
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
let { newDevice }: { newDevice: boolean } = $props();
let certs = $state<CertsView | null>(null);
let problem = $state<string | null>(null);
let name = $state("");
let kind = $state<"phone" | "computer" | "app">("phone");
let nameErr = $state<string | null>(null);
let issuing = $state(false);
let request = $state<PkiRequest | null>(null);
let bundle = $state<{ device: DeviceRow | { id: string; name: string; kind: string }; b: Bundle; format: string } | null>(null);
let confirmRevoke = $state<string | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
async function load() {
try {
certs = await get<CertsView>("/certs");
problem = null;
} catch (e) {
problem = sentence(e);
}
}
onMount(load);
onDestroy(() => clearTimeout(timer));
async function issue(e?: Event) {
e?.preventDefault();
issuing = true;
nameErr = null;
try {
request = await post<PkiRequest>("/certs/devices", { name, kind });
poll();
} catch (err) {
if (err instanceof ApiError && err.body.field === "name") nameErr = err.body.message;
else problem = sentence(err);
} finally {
issuing = false;
}
}
function poll() {
clearTimeout(timer);
timer = setTimeout(async () => {
if (!request) return;
try {
request = await get<PkiRequest>(`/pki-requests/${encodeURIComponent(request.request_id)}`);
} catch {
/* keep waiting */
}
if (request?.state === "waiting") poll();
else void load();
}, 2000);
}
async function cancelRequest() {
if (!request) return;
await del(`/pki-requests/${encodeURIComponent(request.request_id)}`).catch(() => {});
request = null;
closeForm();
}
async function install(d: { id: string; name: string; kind: string }, format: "qr" | "p12") {
try {
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
bundle = { device: d, b, format };
if (format === "p12") {
// The link's GET is only a page (so link previews cannot use it up); this browser is
// signed in on the same host, so it posts to the path and saves the file itself.
const res = await fetch(new URL(b.download_url, location.href).pathname, { method: "POST", credentials: "same-origin" });
if (!res.ok) {
problem = "The install file could not be downloaded. Choose Install again for a new link.";
return;
}
const href = URL.createObjectURL(await res.blob());
const a = document.createElement("a");
a.href = href;
a.download = `${d.name}.p12`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(href), 10_000);
}
} catch (e) {
problem = sentence(e);
}
}
async function revoke(d: DeviceRow) {
try {
await del(`/certs/devices/${encodeURIComponent(d.id)}`);
toast(`Revoked. ${d.name} can no longer get in.`);
confirmRevoke = null;
await load();
} catch (e) {
problem = sentence(e);
}
}
function closeForm() {
clearTimeout(timer);
name = "";
nameErr = null;
if (request?.state !== "approved") request = null;
navigate("/certificates");
}
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
// The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
const capped = $derived(
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
);
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
switch (certs?.intermediate?.state) {
case "ok": return ["healthy", "valid"];
case "due": return ["degraded", "renew soon"];
case "urgent": return ["down", "renew now"];
case "expired": return ["down", "expired"];
default: return ["unknown", "not set up"];
}
});
const kindIcon = (k: string) => (k === "phone" ? "phone" : k === "computer" ? "laptop" : "app") as "phone" | "laptop" | "app";
const issuedDevice = $derived(request?.state === "approved" && request.device_id ? { id: request.device_id, name: request.name ?? name, kind } : null);
</script>
<div class="head">
<h1 class="ia-display">Certificates</h1>
<Button variant="outline" icon="plus" label="Add a device certificate" onclick={() => navigate("/certificates/new")}>Device</Button>
</div>
<IntermediateBanner />
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if certs}
<section class="ia-card">
<p class="ia-label">Domi intermediate</p>
<p><Status kind={intState[0]} word={intState[1]} /> {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}</p>
<p class="ia-sub">Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).</p>
</section>
<p class="ia-label">Devices</p>
{#if certs.devices.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No device certificates yet</h2><p class="ia-text2">A device certificate lets a phone, computer or Domi app into hosts that ask for one.</p></div>
{:else}
<ul class="devices">
{#each certs.devices as d (d.id)}
<li>
<Icon name={kindIcon(d.kind)} />
<span class="dname">{d.name}</span>
<span class="ia-muted">until {shortDate(d.not_after)}</span>
{#if d.state === "revoked"}<Status kind="unknown" word="revoked {d.revoked_at ? shortDate(d.revoked_at) : ''}" />{:else if d.state === "expired"}<Status kind="down" word="expired" />{:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000}<Status kind="degraded" word="renew soon" />{/if}
{#if confirmRevoke === d.id}
<span class="confirm">Revoke the certificate of "{d.name}"? It can no longer get in.
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
<Button small variant="danger" onclick={() => revoke(d)}>Revoke</Button></span>
{:else if d.state === "valid"}
<HostMenu hostname={d.name} items={[
{ label: "Install on the device", icon: "key", run: () => install(d, d.kind === "computer" ? "p12" : "qr") },
{ label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
]} />
{/if}
</li>
{/each}
</ul>
{/if}
{/if}
{#if newDevice}
<Dialog title="New device certificate" kind="panel" onclose={closeForm}>
{#if !request}
<form id="device-form" onsubmit={issue} class="form">
<div class="domi-field">
<label class="domi-field-label" for="device-name">Device name</label>
<input id="device-name" class="domi-input" bind:value={name} autocomplete="off" aria-invalid={nameErr ? "true" : undefined} aria-describedby="device-name-h" />
{#if nameErr}<p class="domi-error"><Icon name="ring" />{nameErr}</p>{/if}
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
</div>
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
<p class="ia-hint">{#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.</p>
</form>
{:else if request.state === "waiting"}
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
<p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
<p class="ia-muted">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.</p>
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
{:else if issuedDevice}
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
<div class="buttons">
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
</div>
<p class="ia-hint">The file is protected with a one-time password shown next to the QR code.</p>
{:else}
<Banner tone="notice" live="status">{#snippet title()}{request?.message}{/snippet}
{#snippet actions()}<Button variant="outline" onclick={() => { request = null; void issue(); }}>Try again</Button>{/snippet}</Banner>
{/if}
{#snippet footer()}
{#if !request}
<Button onclick={closeForm}>Cancel</Button>
<Button variant="primary" type="submit" form="device-form" pending={issuing}>Issue</Button>
{:else if request.state !== "waiting"}
<Button onclick={() => { request = null; closeForm(); void load(); }}>Close</Button>
{/if}
{/snippet}
</Dialog>
{/if}
{#if bundle}
<Dialog title="Install on {bundle.device.name}" onclose={() => { bundle = null; void refresh(); }}>
<div class="install">
{#if bundle.b.qr_svg}
<div class="ia-qr" role="img" aria-label="QR code for downloading the certificate">{@html bundle.b.qr_svg}</div>
{/if}
<div>
<p class="ia-label">Password for the file</p>
<p class="otp">{bundle.b.one_time_password}</p>
<p class="ia-hint">Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).</p>
</div>
</div>
<p class="ia-text2">
{#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}
</p>
</Dialog>
{/if}
<style>
.head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
.devices { list-style: none; margin: 0; padding: 0; border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
.devices li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 56px; padding: 6px 10px 6px 16px; border-top: 1px solid var(--hairline); }
.devices li:first-child { border-top: 0; }
.dname { font-weight: 600; flex: 1 1 140px; }
.confirm { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; flex-basis: 100%; }
.form { display: flex; flex-direction: column; gap: 16px; }
.buttons { display: flex; gap: 8px; flex-wrap: wrap; }
.install { display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; }
.otp { font-weight: 700; font-size: 1.4rem; letter-spacing: 0.08em; }
</style>
+178
View File
@@ -0,0 +1,178 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §8.1: History → pick → Restore this version (3 clicks with the nav click).
import { onMount } from "svelte";
import { Banner, Button, Status } from "@ianitor/ui";
import type { StatusKind } from "@ianitor/ui";
import HostPanel from "../components/HostPanel.svelte";
import { get, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate } from "../lib/app.svelte";
import { FIELD_LABEL, fieldValue, when } from "../lib/format";
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
let { host, pick }: { host?: string; pick?: string } = $props();
let entries = $state<HistoryEntry[]>([]);
let next = $state<string | null>(null);
let loaded = $state(false);
let problem = $state<string | null>(null);
let chosen = $state<string | null>(null);
let preview = $state<RestorePreview | null>(null);
let attempt = $state<ApplyView | null>(null);
let restoring = $state(false);
let resume = $state<string | null>(null);
let editFrom = $state<HostSpec | null>(null);
async function load(before?: string) {
try {
const q = new URLSearchParams({ limit: "50" });
if (host) q.set("host", host);
if (before) q.set("before", before);
const r = await get<{ entries: HistoryEntry[]; next_before: string | null }>(`/history?${q}`);
entries = before ? [...entries, ...r.entries] : r.entries;
next = r.next_before;
problem = null;
} catch (e) {
problem = sentence(e);
} finally {
loaded = true;
}
}
async function choose(id: string) {
chosen = id;
preview = null;
attempt = null;
try {
preview = await get<RestorePreview>(`/history/${encodeURIComponent(id)}/restore-preview`);
if (preview.blocked?.code === "restore.not_kept") attempt = await get<ApplyView>(`/history/${encodeURIComponent(id)}`);
} catch (e) {
problem = sentence(e);
}
}
async function restore() {
if (!chosen) return;
restoring = true;
try {
const a = await post<{ apply: ApplyView }>("/restore", { change_id: chosen, base_rev: app.overview?.rev ?? null });
resume = a.apply.id;
} catch (e) {
problem = sentence(e);
} finally {
restoring = false;
}
}
onMount(() => {
void load().then(() => {
if (pick) void choose(pick);
});
const focus = () => void load();
window.addEventListener("focus", focus);
return () => window.removeEventListener("focus", focus);
});
function stateOf(e: HistoryEntry): [StatusKind, string] {
switch (e.state) {
case "kept": return ["kept", "kept"];
case "reverted": return ["reverted", "reverted"];
case "failed": return ["reverted", "not applied"];
case "queued": return ["running", "waiting"];
default: return ["running", "applying"];
}
}
const entry = $derived(entries.find((e) => e.change_id === chosen));
const n = $derived(preview?.changes.length ?? 0);
const paused = $derived(app.overview?.paused ? !["apply.needs_attention", "control.files_unwritten"].includes(app.overview.paused_reason ?? "") : false);
const blocked = $derived(paused ? "Changes are paused." : changesBlocked() && !app.overview?.paused ? changesBlocked() : null);
function key(e: KeyboardEvent, i: number) {
const btns = Array.from(document.querySelectorAll<HTMLButtonElement>(".entries button"));
if (e.key === "ArrowDown") { e.preventDefault(); btns[Math.min(btns.length - 1, i + 1)]?.focus(); }
if (e.key === "ArrowUp") { e.preventDefault(); btns[Math.max(0, i - 1)]?.focus(); }
}
</script>
<h1 class="ia-display">{host ? `History of ${host}` : "History"}</h1>
{#if host}<div><button type="button" class="domi-btn link" onclick={() => navigate("/history")}>Show all changes</button></div>{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
<div class="cols">
<div class="list">
{#if loaded && entries.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No changes yet</h2><p class="ia-text2">Every change you apply is listed here, newest first.</p></div>
{/if}
<ul class="entries">
{#each entries as e, i (e.change_id)}
{@const [k, w] = stateOf(e)}
<li>
<button type="button" class="entry" aria-current={chosen === e.change_id ? "true" : undefined} onclick={() => choose(e.change_id)} onkeydown={(ev) => key(ev, i)}>
<span class="sum">{e.summary}</span><Status kind={k} word={w} />
<span class="ia-sub">{when(e.at, app.now)} · {e.state === "kept" ? (e.commit_short ?? "") : (e.reason_short ?? "")}</span>
</button>
</li>
{/each}
</ul>
{#if next}<Button onclick={() => load(next ?? undefined)}>Show older changes</Button>{/if}
</div>
{#if chosen && preview}
<section class="detail" aria-label="Version">
<p class="ia-label">Version of {when(entry?.at, app.now)}</p>
{#if preview.blocked?.code === "restore.not_kept"}
<h2 class="ia-h3">This change did not stay</h2>
{#if attempt?.reason}<p>{attempt.reason.message}</p>{/if}
<p class="ia-text2">This change was undone at the time, so there is nothing to go back to.</p>
{#if attempt?.attempted_host}<div><Button variant="outline" onclick={() => (editFrom = attempt?.attempted_host ?? null)}>Edit and try again</Button></div>{/if}
{:else if preview.blocked?.code === "restore.same"}
<h2 class="ia-h3">Go back to this version?</h2>
<p class="ia-text2">This version is the same as the current one. Nothing to restore.</p>
<div class="buttons"><Button onclick={() => (chosen = null)}>Close</Button></div>
{:else}
<h2 class="ia-h3">Go back to this version?</h2>
<p>{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}</p>
<ul>
{#each preview.changes as c (c.hostname)}
{#if c.effect === "added"}<li><strong>{c.hostname}</strong> is added back</li>
{:else if c.effect === "removed"}<li><strong>{c.hostname}</strong> is removed</li>
{:else}
{#each c.fields as f (f.field)}
<li><strong>{c.hostname}</strong>: {#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}</li>
{/each}
{/if}
{/each}
</ul>
<p class="ia-hint">Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.</p>
{#if blocked}<p class="ia-hint" id="restore-blocked">{blocked}</p>{/if}
<div class="buttons">
<Button onclick={() => (chosen = null)}>Close</Button>
<Button variant="primary" onclick={restore} pending={restoring} disabled={!!blocked} describedby={blocked ? "restore-blocked" : undefined}>Restore this version</Button>
</div>
{/if}
</section>
{/if}
</div>
{#if resume}
<HostPanel resume={resume} onclose={() => { resume = null; void load(); }} />
{/if}
{#if editFrom}
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
{/if}
<style>
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
.list { flex: 1 1 360px; max-width: 520px; display: flex; flex-direction: column; gap: 8px; }
.entries { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
.entry { display: grid; grid-template-columns: 1fr auto; gap: 2px 12px; width: 100%; min-height: 44px; padding: 10px 12px; border-radius: var(--radius-sm); border: 1px solid transparent; background: none; color: var(--text); text-align: left; cursor: pointer; }
.entry:hover { background: var(--surface); }
.entry[aria-current="true"] { background: var(--surface-2); border-color: color-mix(in srgb, var(--accent) 55%, transparent); }
.sum { font-weight: 600; }
.detail { flex: 2 1 360px; background: var(--colonnade); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.detail ul { margin: 0; padding-left: 1.1rem; }
.buttons { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
</style>
+132
View File
@@ -0,0 +1,132 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §5: the main screen.
import { tick } from "svelte";
import { Banner, Button } from "@ianitor/ui";
import ChangeBar from "../components/ChangeBar.svelte";
import EngineChip from "../components/EngineChip.svelte";
import HostList from "../components/HostList.svelte";
import HostPanel from "../components/HostPanel.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte";
import ShareDialog from "../components/ShareDialog.svelte";
import { call, newKey, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
import { atTime, countsSentence } from "../lib/format";
import type { ApplyView, HostSpec } from "../lib/types";
let { route }: { route: { newHost: boolean; edit?: string } } = $props();
const o = $derived(app.overview);
let prefill = $state<HostSpec | null>(null);
let focusField = $state<string | undefined>(undefined);
let problem = $state<string | null>(null);
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
const blocked = $derived(changesBlocked());
async function closePanel() {
prefill = null;
focusField = undefined;
if (app.panel?.kind === "host") app.panel = null;
if (route.newHost || route.edit) navigate("/");
await refresh();
const h = app.focusHost;
app.focusHost = null;
if (h) {
await tick();
document.querySelector<HTMLElement>(`[aria-label="More for ${h.replace(/["\\]/g, "")}"]`)?.focus();
}
}
async function remove(h: string) {
problem = null;
try {
await call("DELETE", `/hosts/${encodeURIComponent(h)}?base_rev=${encodeURIComponent(o?.rev ?? "")}`, undefined, { idem: newKey() });
await refresh();
} catch (e) {
problem = sentence(e);
}
}
async function retry(h: string) {
try {
await post(`/hosts/${encodeURIComponent(h)}/certificate/retry`);
toast("Trying Let's Encrypt again.");
} catch (e) {
problem = sentence(e);
}
}
function editAgain(a: ApplyView, field?: string) {
prefill = a.attempted_host ?? null;
focusField = field;
if (a.kind === "add" || !a.hosts[0]) {
navigate("/hosts/new");
} else {
navigate(`/hosts/${encodeURIComponent(a.hosts[0])}/edit`);
}
}
</script>
<div class="head">
<div>
<h1 class="ia-display">Hosts</h1>
{#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
</div>
<div class="actions">
{#if !app.phone}<EngineChip />{/if}
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
</div>
</div>
<IntermediateBanner />
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
<ChangeBar onshowsteps={(id) => (app.panel = { kind: "host", resume: id })} onedit={editAgain} />
{#if !o && !app.loadError}
<div class="ia-list" aria-busy="true"><span class="sr-only">Loading hosts…</span>
{#each [0, 1, 2] as i (i)}<div class="ia-row"><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span></span></div>{/each}
</div>
{:else if app.loadError && !o}
<Banner tone="down" live="alert">{#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet}
{#snippet actions()}<Button onclick={() => refresh()}>Try again now</Button>{/snippet}</Banner>
{:else if o && o.hosts.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No hosts yet</h2><p class="ia-text2">Add the first one: the name people type, and where Ianitor should send them.</p></div>
{:else if o}
<HostList hosts={o.hosts}
onedit={(h) => 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}
<hr class="ia-ornament" />
<p class="ia-muted footer">
Routes live in the {o.repo.name} repository, one file per host.
{#if o.repo.last_push_at}Last pushed to Gitea {atTime(o.repo.last_push_at, app.now)}.{/if}
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
</p>
{/if}
{#if panelOpen}
{#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")}
<HostPanel hostname={route.edit} resume={app.panel?.kind === "host" ? app.panel.resume : undefined} {prefill} {focusField} onclose={closePanel} />
{/key}
{/if}
{#if app.panel?.kind === "share"}
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
{/if}
<style>
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.footer { text-align: center; }
</style>
+143
View File
@@ -0,0 +1,143 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §13.6: signing the intermediate by hand on the offline computer (the temporary step
// until Custos can sign, docs/pki.md). The root key never comes to this server.
import { Banner, Button, Icon } from "@ianitor/ui";
import { ApiError, post, put, sentence } from "../lib/api";
import { app, navigate, refresh } from "../lib/app.svelte";
import type { PkiRequest } from "../lib/types";
const r = $derived(app.overview?.intermediate?.renewal ?? null);
let pem = $state("");
let paste = $state(false);
let err = $state<string | null>(null);
let pending = $state(false);
let starting = $state(false);
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`);
const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`);
const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`);
let copied = $state(false);
// Groups of 8, easier to compare by eye; openssl prints it without spaces.
const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h;
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
copied = true;
setTimeout(() => (copied = false), 3000);
} catch {
err = "Your browser did not allow copying. Select the command and copy it.";
}
}
function save(text: string, name: string, type: string) {
const url = URL.createObjectURL(new Blob([text], { type }));
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function download() {
if (r?.csr_pem) save(r.csr_pem, `${base}.csr`, "application/pkcs10");
}
async function downloadExt() {
if (!r) return;
try {
const res = await fetch(`/api/v1/pki-requests/${encodeURIComponent(r.request_id)}/ext`, { headers: { "X-Ianitor-UI": "1" }, redirect: "manual", credentials: "same-origin" });
if (res.ok) save(await res.text(), `${base}.ext`, "text/plain");
else err = "The signing settings file could not be downloaded. Reload the page and try again.";
} catch {
err = "Ianitor's control service is not answering.";
}
}
async function file(e: Event) {
const f = (e.currentTarget as HTMLInputElement).files?.[0];
if (f) pem = await f.text();
}
async function use() {
if (!r) return;
pending = true;
err = null;
try {
const done = await put<PkiRequest>(`/pki-requests/${encodeURIComponent(r.request_id)}/certificate`, { certificate_pem: pem });
app.renewedUntil = done.not_after;
await refresh();
navigate("/certificates");
} catch (e) {
err = e instanceof ApiError ? e.body.message : sentence(e);
} finally {
pending = false;
}
}
async function start() {
starting = true;
try {
await post("/certs/intermediate/renewal");
await refresh();
} catch (e) {
err = sentence(e);
} finally {
starting = false;
}
}
</script>
<h1 class="ia-display">Sign the intermediate by hand</h1>
<p class="ia-text2">Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.</p>
{#if !r}
<Banner tone="notice">{#snippet title()}There is no open renewal request.{/snippet}
{#snippet actions()}<Button variant="outline" onclick={start} pending={starting}>Start a renewal</Button>{/snippet}</Banner>
{:else}
<section class="step">
<p class="ia-label">Step 1</p>
<h2 class="ia-h3">Download the request</h2>
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
<div class="row"><Button icon="download" onclick={download}>Download the request (.csr)</Button><Button icon="download" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
</section>
<section class="step">
<p class="ia-label">Step 2</p>
<h2 class="ia-h3">Sign it on the offline computer</h2>
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
<p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
<pre class="ia-secret ia-cmd">{checkCmd}</pre>
{#if r.csr_sha256}<p>openssl must print the same fingerprint as this page: <span class="ia-cmd fp" aria-label="Fingerprint {r.csr_sha256}">{group(r.csr_sha256)}</span></p>{/if}
<p class="ia-text2">Then sign it:</p>
<pre class="ia-secret ia-cmd">{signCmd}</pre>
<div class="row"><Button icon="copy" onclick={() => copy(signCmd)}>Copy command</Button>{#if copied}<span class="ia-status" data-s="kept" role="status"><Icon name="check" />Copied</span>{/if}</div>
<p class="ia-muted">On a computer with Ianitor installed, <code>ianitor-control ca sign</code> signs it instead and shows the match code {r.match_code}.</p>
</section>
<section class="step">
<p class="ia-label">Step 3</p>
<h2 class="ia-h3">Upload the signed certificate</h2>
{#if paste}
<div class="domi-field">
<label class="domi-field-label" for="cert-paste">Signed certificate</label>
<textarea id="cert-paste" class="domi-input" rows="8" bind:value={pem} aria-invalid={err ? "true" : undefined}></textarea>
</div>
{:else}
<div class="domi-field">
<label class="domi-field-label" for="cert-file">Signed certificate (.crt)</label>
<input id="cert-file" class="domi-input" type="file" accept=".crt,.pem" onchange={file} aria-invalid={err ? "true" : undefined} />
<div><button type="button" class="domi-btn link" onclick={() => (paste = true)}>Paste it instead</button></div>
</div>
{/if}
{#if err}<p class="domi-error" role="alert"><Icon name="ring" />{err}</p>{/if}
<div><Button variant="primary" onclick={use} {pending} disabled={!pem.includes("BEGIN CERTIFICATE")}>Use this certificate</Button></div>
</section>
{/if}
<style>
.row { display: flex; gap: 8px; flex-wrap: wrap; }
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.fp { word-break: break-all; color: var(--accent-strong); }
</style>
+280
View File
@@ -0,0 +1,280 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §8.3: Settings with General, API (⚙ → API → New token = 3 clicks, Copy token the
// accepted 4th), Share links and About.
import { onMount } from "svelte";
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
import { app, navigate, toast } from "../lib/app.svelte";
import { longDate, shortDate, whenInline } from "../lib/format";
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
let { tab }: { tab: string } = $props();
const TABS = [
{ id: "general", label: "General" },
{ id: "api", label: "API" },
{ id: "share-links", label: "Share links" },
{ id: "about", label: "About" },
];
let settings = $state<{ repo: { name: string; last_push_at: string | null } | null; watch_seconds: number } | null>(null);
let tokens = $state<TokenRow[]>([]);
let revoked = $state<Record<string, string>>({});
let links = $state<ShareLink[]>([]);
let problem = $state<string | null>(null);
let expiry = $state<"year" | "never">("year");
let made = $state<CreatedToken | null>(null);
let tokenName = $state("");
let tokenCopied = $state(false);
let askClose = $state(false);
let nameErr = $state<string | null>(null);
let confirmRevoke = $state<string | null>(null);
let confirmStopAll = $state(false);
let creating = $state(false);
async function load() {
try {
if (tab === "general") settings = await get("/settings");
if (tab === "api") tokens = (await get<{ items: TokenRow[] }>("/tokens")).items;
if (tab === "share-links") links = (await get<{ items: ShareLink[] }>("/share-links")).items;
problem = null;
} catch (e) {
problem = sentence(e);
}
}
$effect(() => {
void tab;
void load();
});
onMount(() => {
const f = () => void load();
window.addEventListener("focus", f);
return () => window.removeEventListener("focus", f);
});
function tabKey(e: KeyboardEvent, i: number) {
let j = i;
if (e.key === "ArrowRight") j = (i + 1) % TABS.length;
else if (e.key === "ArrowLeft") j = (i - 1 + TABS.length) % TABS.length;
else if (e.key === "Home") j = 0;
else if (e.key === "End") j = TABS.length - 1;
else return;
e.preventDefault();
navigate(`/settings/${TABS[j].id}`);
setTimeout(() => document.getElementById(`tab-${TABS[j].id}`)?.focus(), 0);
}
async function newToken() {
creating = true;
try {
const name = `Token made ${shortDate(new Date().toISOString())}`;
const body = expiry === "never" ? { name, never_expires: true } : { name, expires_in_days: 365 };
made = await post<CreatedToken>("/tokens", body);
tokenName = made.name;
tokenCopied = false;
askClose = false;
} catch (e) {
problem = sentence(e);
} finally {
creating = false;
}
}
async function copyToken() {
if (!made) return;
try {
await navigator.clipboard.writeText(made.token);
tokenCopied = true;
} catch {
problem = "Your browser did not allow copying. Select the token and press Ctrl+C.";
}
}
async function closeToken(force = false) {
if (!made) return;
if (!tokenCopied && !force) {
askClose = true;
return;
}
if (tokenName.trim() && tokenName !== made.name) {
try {
await patch(`/tokens/${encodeURIComponent(made.id)}`, { name: tokenName.trim() });
toast("Renamed.");
} catch (e) {
if (e instanceof ApiError && e.code === "token.name") {
nameErr = e.body.message;
return;
}
}
}
// The token leaves memory with the dialog.
made = null;
tokenName = "";
void load();
}
async function revoke(t: TokenRow) {
try {
await del(`/tokens/${encodeURIComponent(t.id)}`);
revoked = { ...revoked, [t.id]: new Date().toISOString() };
confirmRevoke = null;
toast(`Revoked. Anything using "${t.name}" stops working now.`);
} catch (e) {
problem = sentence(e);
}
}
async function stop(l: ShareLink) {
try {
await del(`/share-links/${encodeURIComponent(l.id)}`);
toast("Stopped. The link stops working within a few seconds.");
void load();
} catch (e) {
problem = sentence(e);
}
}
async function stopAll() {
try {
await call("POST", "/share-links/stop-all", {}, { idem: newKey() });
toast("All share links are stopped. New ones work as usual.");
confirmStopAll = false;
void load();
} catch (e) {
problem = sentence(e);
}
}
const active = $derived(links.filter((l) => l.state === "active"));
const ended = $derived(links.filter((l) => l.state !== "active"));
const viewer = $derived(app.overview?.viewer ?? null);
</script>
<h1 class="ia-display">Settings</h1>
<div class="tabs" role="tablist" aria-label="Settings">
{#each TABS as t, i (t.id)}
<button type="button" role="tab" id="tab-{t.id}" aria-selected={tab === t.id} aria-controls="panel-{t.id}" tabindex={tab === t.id ? 0 : -1}
onclick={() => navigate(`/settings/${t.id}`)} onkeydown={(e) => tabKey(e, i)}>{t.label}</button>
{/each}
</div>
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
{#if tab === "general"}
<p class="ia-label">Routes repository</p>
<p>{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."}</p>
<p class="ia-label">Health watch after apply</p>
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
<p class="ia-label">Signed in</p>
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}</p>
{#if app.overview?.site?.auth_logout_url}<p><a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a></p>{/if}
{:else if tab === "api"}
<div class="row">
<h2 class="ia-h3">API tokens</h2>
<Button variant="outline" icon="plus" onclick={newToken} pending={creating}>New token</Button>
<Segmented legend="New tokens expire after" name="token-expiry" bind:value={expiry} options={[{ value: "year", label: "1 year" }, { value: "never", label: "Never" }]} />
</div>
<p class="ia-hint">The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.</p>
{#if tokens.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No API tokens</h2><p class="ia-text2">Scripts and other Domi apps use a token to talk to Ianitor.</p></div>
{:else}
<ul class="rows">
{#each tokens as t (t.id)}
<li>
<div class="grow">
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
<span class="ia-sub" style="display:block">
{#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}
</span>
</div>
{#if !revoked[t.id] && !t.revoked_at}
{#if confirmRevoke === t.id}
<span>Revoke "{t.name}"? Anything using it stops working now.</span>
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
<Button small variant="danger" onclick={() => revoke(t)}>Revoke</Button>
{:else}
<Button small variant="danger" onclick={() => (confirmRevoke = t.id)}>Revoke</Button>
{/if}
{/if}
</li>
{/each}
</ul>
{/if}
{:else if tab === "share-links"}
<div class="row">
<h2 class="ia-h3">Share links</h2>
{#if active.length}<Button variant="danger" onclick={() => (confirmStopAll = true)}>Stop all share links</Button>{/if}
</div>
{#if app.overview?.engine.running === "caddy"}
<Banner tone="notice">{#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet}</Banner>
{/if}
{#if confirmStopAll}
<p>Stop all {active.length} active links? Every link made so far stops working. New ones work as usual.
<Button small onclick={() => (confirmStopAll = false)}>Cancel</Button> <Button small variant="danger" onclick={stopAll}>Stop all</Button></p>
{/if}
{#if links.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No share links</h2><p class="ia-text2">Make one from a host's menu (⋯), Share link.</p></div>
{:else}
<ul class="rows">
{#each active as l (l.id)}
<li>
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
<span class="ia-sub" style="display:block">Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
<Button small onclick={() => stop(l)}>Stop this link</Button>
</li>
{/each}
</ul>
{#if ended.length}
<details><summary>Ended ({ended.length})</summary>
<ul class="rows">{#each ended as l (l.id)}<li><span class="grow">{l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}</span><span class="ia-sub">{l.state} {shortDate(l.expires_at)}</span></li>{/each}</ul>
</details>
{/if}
{/if}
{:else}
<p>Ianitor Domi 0.1.0</p>
<p>MPL-2.0</p>
<p>Built, tested and signed by Fabrica Domi</p>
<p><a class="domi-btn link" href="https://gitea.marek-novak.cz/mnovak/Ianitor" rel="noreferrer">Source on Gitea</a></p>
{/if}
</div>
{#if made}
<Dialog title="Your new token" escape={false} onclose={() => closeToken()}>
<p><strong>Copy it now and save it in Custos.</strong></p>
<p class="ia-text2">Ianitor cannot show it again; if it is lost, make a new one and revoke this one.</p>
<input class="ia-secret" readonly value={made.token} aria-label="New API token" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
<div class="grid">
<div class="domi-field">
<label class="domi-field-label" for="token-name">Name</label>
<input id="token-name" class="domi-input" bind:value={tokenName} aria-invalid={nameErr ? "true" : undefined} />
{#if nameErr}<p class="domi-error">{nameErr}</p>{/if}
<p class="ia-hint">Rename it now or later, so you know what uses it.</p>
</div>
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
</div>
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
<p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
{#if askClose}
<p role="alert">Close without copying? The token cannot be shown again.
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
{/if}
{#snippet footer()}<Button onclick={() => closeToken()}>I have saved it</Button>{/snippet}
</Dialog>
{/if}
<style>
.tabs { display: flex; gap: 4px; overflow-x: auto; }
.tabs [role="tab"] { min-height: 44px; padding: 0 1rem; border-radius: var(--radius-sm); border: 0; background: none; color: var(--text-2); font-weight: 600; cursor: pointer; }
.tabs [role="tab"][aria-selected="true"] { background: var(--surface-2); color: var(--text); }
.panel { display: flex; flex-direction: column; gap: 10px; }
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
.rows { list-style: none; margin: 0; padding: 0; }
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
.grow { flex: 1 1 200px; min-width: 0; }
.tname { font-weight: 600; }
.struck { text-decoration: line-through; color: var(--muted); }
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
</style>
+33
View File
@@ -0,0 +1,33 @@
<!-- 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/. -->
<script lang="ts">
// Handoff §10.2: Authelia sends the sign-in tab back here; it tells the first tab and closes.
import { onMount } from "svelte";
onMount(() => {
const back = new URL(location.href).searchParams.get("back");
try {
const ch = new BroadcastChannel("ianitor-auth");
ch.postMessage("signed-in");
ch.close();
} catch {
/* the first tab rechecks with "I have signed in" */
}
if (back && back.startsWith("/") && !back.startsWith("//")) {
location.replace(back);
return;
}
setTimeout(() => window.close(), 300);
});
</script>
<main class="signed-in">
<p class="ia-wordmark">IANITOR DOMI</p>
<h1 class="ia-h3">You are signed in again.</h1>
<p class="ia-text2">You can close this tab and go back to Ianitor.</p>
</main>
<style>
.signed-in { max-width: 420px; margin: 20vh auto; padding: 0 16px; display: flex; flex-direction: column; gap: 12px; }
</style>
+7
View File
@@ -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() };
+245
View File
@@ -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<typeof userEvent.setup>;
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<string, unknown> };
// 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<string, string>;
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<string, unknown>;
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<string, string>;
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();
}
});
});
+174
View File
@@ -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<string, unknown>;
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: "<svg xmlns=\"http://www.w3.org/2000/svg\"></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;
}
+39
View File
@@ -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<string, unknown>;
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 () {};
+19
View File
@@ -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"]
}
+38
View File
@@ -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,
},
});
+15 -3
View File
@@ -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
+132 -22
View File
@@ -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<String>) {
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<Response, ApiError> {
pub async fn overview(
State(st): Shared,
Extension(actor): Extension<Actor>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
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<Response,
state: r.state.clone(),
summary: r.summary.clone(),
seconds_left: r.watch.as_ref().map(|w| w.ends.saturating_sub(now())),
kind: r.kind.clone(),
hosts: r.hosts.clone(),
watch_ends_at: r.watch.as_ref().map(|w| rfc3339(w.ends)),
queued: c.queued_count(),
});
let site = tree
@@ -179,40 +221,90 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response,
acme_configured: true,
secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(),
watch_seconds: c.cfg.watch_secs,
share_links_available: c.share_key.is_some(),
share_links_available: c.share_key.is_some() && c.engine_running() != "caddy",
auth_logout_url: c.cfg.ui.as_ref().and_then(|u| u.logout_url.clone()),
});
let es = super::pki::engine_view(c);
let on_caddy = es.running == "caddy";
let caddy_built = std::fs::metadata(&c.cfg.caddy.config)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| rfc3339(d.as_secs()));
let caddy_current = tree
.as_ref()
.and_then(|t| t.model().ok())
.and_then(|m| ianitor_core::compile::caddy(&m, &c.cfg.caddy_compile().options()).ok())
.is_some_and(|text| {
std::fs::read_to_string(&c.cfg.caddy.config).ok().as_deref() == Some(text.as_str())
});
let ov = Overview {
counts,
hosts,
engine: EngineView {
running: "pingora".into(),
state: if status.is_some() && error.is_none() {
"running"
state: if es.state == "switching" {
"switching".into()
} else if on_caddy || (status.is_some() && error.is_none()) {
"running".into()
} else {
"stopped"
}
.into(),
since: status.as_ref().map(|s| rfc3339(s.started_at)),
fallback_ready: None,
"stopped".into()
},
since: if on_caddy || es.state == "switching" {
Some(es.since.clone())
} else {
status.as_ref().map(|s| rfc3339(s.started_at))
},
running: es.running,
target: es.target,
switchable: es.switchable,
fallback_ready: Some({
let (compared, matched, differences) = tree
.as_ref()
.and_then(|t| t.model().ok())
.map(|m| fallback_differences(&m))
.unwrap_or_default();
FallbackReady {
built_at: caddy_built,
current: caddy_current,
compared,
matched,
differences,
}
}),
last_error: es.last_error,
notes: es.notes,
},
last_apply,
undo: undo_view(c),
active_apply: active,
repo: Some(repo_view(c, &head)),
intermediate: None,
intermediate: super::pki::intermediate_view(c),
site,
paused: c.paused().map(|p| Blocked {
paused_reason: c.effective_pause().map(|p| p.code),
paused_detail: c.effective_pause().and_then(|p| p.detail),
paused: c.effective_pause().map(|p| Blocked {
code: "control.paused".into(),
message: message("control.paused", &messages::params([("reason", p.message)])),
}),
health_error: error.filter(|_| c.edge.attached()).map(|_| Blocked {
code: "health.unavailable".into(),
message: message(
"health.unavailable",
&messages::params([("engine", "Pingora".into())]),
),
}),
// Under Caddy, health is not read (edge is stopped); the chip says Caddy serves.
health_error: error
.filter(|_| c.edge.attached() && !on_caddy)
.map(|_| Blocked {
code: "health.unavailable".into(),
message: message(
"health.unavailable",
&messages::params([("engine", "Pingora".into())]),
),
}),
rev: Some(head),
viewer: Some(Viewer {
via: if actor.token_id.starts_with("user:") {
"authelia".into()
} else {
"token".into()
},
name: actor.name.clone(),
}),
};
let body = serde_json::to_vec(&ov).map_err(|e| ApiError::internal(e.to_string()))?;
let etag = format!("\"{}\"", &sha256_hex(&body)[..32]);
@@ -1038,6 +1130,14 @@ async fn mint_inner(
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
})?;
let c = &st.ctl;
if c.engine_running() == "caddy" {
// G7: Caddy cannot check share links; control does not serve visitors itself.
return Err(ApiError::new(
StatusCode::CONFLICT,
"share.engine_caddy",
Params::new(),
));
}
let (_, _, model) = c.head_model()?;
let Some(host) = model
.hosts()
@@ -1138,6 +1238,9 @@ pub async fn list_share_links(State(st): Shared) -> Result<Response, ApiError> {
.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;
+125 -5
View File
@@ -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<Arc<AppState>>, mut req: Request, next: Next) -> Response {
let started = Instant::now();
@@ -367,6 +425,46 @@ async fn guard(State(st): State<Arc<AppState>>, 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::<serde_json::Value>(&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<AppState>) -> 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.
+839
View File
@@ -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<Arc<AppState>>;
fn json<T: serde::Serialize>(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<T: Send + 'static>(
st: &Arc<AppState>,
f: impl FnOnce(&Control) -> Result<T, PkiFail> + Send + 'static,
) -> Result<T, ApiError> {
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<String>,
pub device_id: Option<String>,
pub name: Option<String>,
/// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
pub csr_pem: Option<String>,
/// 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<String>,
/// Renewals, once installed: the new intermediate's expiry.
pub not_after: Option<String>,
/// 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<String>,
/// Renewals: the base name of the files (`<base>.csr`, `<base>.ext`, `<base>.crt`).
pub file_base: Option<String>,
/// Why it failed, when it did.
pub problem: Option<String>,
}
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<String>,
pub not_after: Option<String>,
pub days_left: Option<i64>,
pub renewal: Option<PkiRequestView>,
/// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
pub banner: Option<Blocked>,
}
pub fn intermediate_view(c: &Control) -> Option<IntermediateView> {
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<String>,
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<IntermediateView>,
pub root: RootView,
pub devices: Vec<DeviceView>,
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<String>,
pub server_lifetime_days: u32,
/// `manual` (on the server, until Custos can) or `custos`.
pub approval: String,
/// Open device requests.
pub requests: Vec<PkiRequestView>,
/// 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<Blocked>,
}
// ---------------------------------------------------------------- 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<Response, ApiError> {
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<Vec<PkiRequestView>, PkiFail> {
let path = crate::pki::requests_path(&c.cfg.state_dir);
let rs: Vec<Request> = 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<Actor>,
body: Body<DeviceRequestBody>,
) -> Result<Response, ApiError> {
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<String>) -> Result<Response, ApiError> {
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<String>,
) -> Result<Response, ApiError> {
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<String>) -> Result<Response, ApiError> {
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<String>,
body: Body<CertificateBody>,
) -> Result<Response, ApiError> {
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<Actor>,
) -> Result<Response, ApiError> {
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<Actor>,
Path(id): Path<String>,
) -> Result<Response, ApiError> {
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<String>,
}
/// 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<String>,
body: Body<BundleBody>,
) -> Result<Response, ApiError> {
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<AppState>, 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!(
"<h1>Install the certificate for {}</h1>\
<p>This link works once. After the download, open the file and enter the \
one-time password shown in Ianitor.</p>\
<form method=\"post\"><button type=\"submit\">Download domi-device.p12</button></form>",
html_escape(&n)
),
),
None => (
StatusCode::GONE,
format!(
"<h1>This link has been used</h1><p>{}</p>",
html_escape(&message("pki.bundle_used", &Params::new()))
),
),
};
let page = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
<meta name=\"robots\" content=\"noindex\"><title>Ianitor: device certificate</title>\
<style>body{{margin:0;padding:24px 16px;background:#0f1115;color:#e6e8ee;\
font:16px/1.5 system-ui,sans-serif}}main{{max-width:32rem;margin:0 auto}}\
h1{{font-size:1.25rem}}button{{font:inherit;padding:10px 16px;border-radius:8px;\
border:0;background:#7aa2ff;color:#0f1115;cursor:pointer}}\
button:focus-visible{{outline:2px solid #e6e8ee;outline-offset:2px}}</style>\
</head><body><main>{body}</main></body></html>"
);
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("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&#39;"),
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<String>,
) -> Result<Response, ApiError> {
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<String>,
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<crate::records::Reason>,
/// What changes while Caddy serves.
pub notes: Vec<Blocked>,
}
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<Actor>,
body: Body<EngineBody>,
) -> Result<Response, ApiError> {
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<String>) -> Result<Response, ApiError> {
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)
}
+124
View File
@@ -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<Arc<AppState>>, 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
}
+52 -8
View File
@@ -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<String>,
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<String>,
#[schema(value_type = Option<Object>)]
pub fallback_ready: Option<serde_json::Value>,
/// The engine a running switch goes to.
pub target: Option<String>,
/// 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<FallbackReady>,
/// Why the last switch did not happen.
pub last_error: Option<Reason>,
/// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`).
pub notes: Vec<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct FallbackReady {
pub built_at: Option<String>,
/// 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<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -477,6 +500,11 @@ pub struct ActiveApply {
pub state: String,
pub summary: String,
pub seconds_left: Option<u64>,
/// `add`, `edit`, `remove`, `undo`, `restore`, `share_links`: the UI writes the heading.
pub kind: String,
pub hosts: Vec<String>,
/// When the health watch ends (only while watching), for a local countdown.
pub watch_ends_at: Option<String>,
pub queued: usize,
}
@@ -496,6 +524,8 @@ pub struct SiteView {
pub secrets: Vec<String>,
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<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -507,14 +537,27 @@ pub struct Overview {
pub undo: UndoView,
pub active_apply: Option<ActiveApply>,
pub repo: Option<RepoView>,
/// The Domi intermediate; arrives in phase 3.
#[schema(value_type = Option<Object>)]
pub intermediate: Option<serde_json::Value>,
/// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
pub intermediate: Option<super::pki::IntermediateView>,
pub site: Option<SiteView>,
pub paused: Option<Blocked>,
/// 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<String>,
/// The technical detail behind the pause, for "Show details" (never a secret).
pub paused_detail: Option<String>,
/// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>,
pub rev: Option<String>,
/// Who is looking: the Authelia user (through edge) or the API token's name.
pub viewer: Option<Viewer>,
}
#[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<String> {
@@ -526,7 +569,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
}
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()),
+269
View File
@@ -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<TrialDeadline> {
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::<Journal>(&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<bool, String> {
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<bool, String> {
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<bool, String> {
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);
}
}
+366
View File
@@ -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<u8>), 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::<String>()
))
}
}
/// The config Caddy runs now.
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> {
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<bool, String> {
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<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
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::<u16>().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<String, String> {
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 <path>` 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<u16>,
pub latency_ms: Option<u64>,
}
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<rustls::RootCertStore> {
static ROOTS: std::sync::OnceLock<Arc<rustls::RootCertStore>> = 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<S: AsyncRead + AsyncWrite + Unpin>(
mut s: S,
req: &[u8],
) -> Result<Option<u16>, 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::<u16>().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),
}
}
}
}
+103
View File
@@ -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<Compile>,
/// 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<PkiConfig>,
/// The web UI behind edge (sign-in through Authelia, see docs/api.md).
#[serde(default)]
pub ui: Option<UiConfig>,
/// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)]
pub engine: Option<EngineConfig>,
}
#[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<SocketAddr>,
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
#[serde(default)]
pub trusted_proxies: Vec<std::net::IpAddr>,
}
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<ianitor_core::Model> {
)
.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 <code>` 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<String>,
/// 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<String>,
/// The built web UI (served at `/`).
pub static_dir: Option<PathBuf>,
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
#[serde(default)]
pub logout_url: Option<String>,
}
#[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()
}
+25 -4
View File
@@ -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=<stage>` 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=<file name>` 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(())
}
+54 -40
View File
@@ -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::<String>::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 <code> --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);
+7
View File
@@ -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
+118 -2
View File
@@ -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<ShareKey>,
/// The Domi CA, when `[pki]` is configured.
pub pki: Option<crate::pki::Pki>,
/// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`.
pub ui_proof: Option<Vec<u8>>,
/// Which engine serves (see `switch`).
pub engine: Mutex<crate::switch::EngineState>,
/// How control starts and stops the engines; `None` without `[engine]`.
pub units: Option<Arc<dyn crate::switch::Units>>,
records: Mutex<Vec<ApplyRecord>>,
queue: Mutex<VecDeque<Job>>,
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<Option<String>>,
}
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<ApplyRecord> =
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<String> = 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<Option<String>, 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}");
}
+466
View File
@@ -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<ianitor_core::Upstream>,
path: String,
has_check: bool,
}
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
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<String, Rule> {
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<String> = 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<String> = 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<String> = 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<String> = 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<String, Rule>,
plan: &Plan,
addr: SocketAddr,
ends: u64,
) -> Result<(), Reason> {
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
let mut seq = 0u64;
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
let paths: HashMap<String, String> = 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(())
}
}
+9
View File
@@ -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<HealthCheckSpec>| 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(),
+6
View File
@@ -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());
+198 -1
View File
@@ -9,6 +9,11 @@
//! ianitor-control token list (--config <c> | --state-dir <d>)
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
//! ianitor-control openapi print the OpenAPI document
//! ianitor-control pki approve|deny <code> (--config <c> | --state-dir <d>) approve a device request
//! ianitor-control pki install <intermediate.crt> (--config <c>) install a signed intermediate
//! ianitor-control pki status (--config <c>) open requests
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
//! ianitor-control check --config <control.toml> 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 <control.toml> | --dev [--edge-bin <path>] | \
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
token list (...) | token revoke <id> (...) | openapi | check --config <c>"
token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
caddy-revert --config <c> | caddy-guard --config <c>"
);
ExitCode::from(2)
}
@@ -197,6 +203,174 @@ fn token(args: &[String]) -> Result<(), String> {
}
}
fn arg_after(args: &[String], name: &str) -> Option<String> {
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<String, String> {
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 <dir>")?);
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 <dir> --csr <file> --out <file>")?,
);
let csr_path = arg_after(args, "--csr").ok_or("--csr <file> is required")?;
let out = PathBuf::from(arg_after(args, "--out").ok_or("--out <file> 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 <dir> | ca sign --root <dir> --csr <file> --out <file>".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::<Vec<_>>()
.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 <intermediate.crt>")?;
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::pki::Request> =
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 <code> | pki deny <code> | pki install <cert> | pki status (--config <c> | --state-dir <d>)".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)) {
+125
View File
@@ -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.",
}
File diff suppressed because it is too large Load Diff
+270
View File
@@ -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<bool, Fail> {
let Some(p) = &self.pki else {
return Ok(false);
};
let t = now();
let domi: Vec<String> = 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<Self>) {
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())])),
)
}
}
+412
View File
@@ -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<bool, String>;
}
/// `systemctl --no-ask-password <verb> <unit>`, as the control user (polkit decides).
pub struct Systemctl {
pub bin: PathBuf,
}
impl Systemctl {
fn run(&self, args: &[&str]) -> Result<std::process::Output, String> {
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<bool, String> {
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<Vec<String>>,
pub active: Mutex<HashSet<String>>,
pub fail_start: Mutex<HashSet<String>>,
}
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<bool, String> {
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<String>,
/// Why the last switch did not happen.
pub last_error: Option<Reason>,
}
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<Self>, target: &str) -> Result<EngineState, Fail> {
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<Self>, 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<dyn Units>, 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<T: Send + 'static>(
f: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
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<dyn Units>,
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<Reason> {
self.paused()
}
}
/// What control.toml's `[engine]` asks for.
pub fn units_for(cfg: Option<&EngineConfig>) -> Option<Arc<dyn Units>> {
let c = cfg?;
match c.units.as_str() {
"systemctl" => Some(Arc::new(Systemctl {
bin: c.systemctl.clone(),
})),
_ => None,
}
}
+9 -3
View File
@@ -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);
+7 -2
View File
@@ -66,6 +66,8 @@ pub struct EnvSpec {
pub watch_secs: u64,
pub site: String,
pub remote: Option<String>,
/// 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");
File diff suppressed because it is too large Load Diff
+769
View File
@@ -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("<?xml"));
let path = url
.split_once("/api/v1/")
.map(|(_, p)| format!("/api/v1/{p}"))
.unwrap();
// Opening the link (GET, as a link preview or prefetcher would) shows a page and
// uses nothing up; its button posts.
for _ in 0..2 {
let g = env.call_with("GET", &path, &[], None).await;
assert_eq!(g.status, 200, "{}", g.text);
assert!(g.text.contains("<form method=\"post\">"), "{}", g.text);
assert!(g.text.contains("Mark&#39;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<std::path::PathBuf> {
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);
}
}
+283
View File
@@ -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::<String>()
);
assert!(!r.text().contains("allory"), "{}", r.text());
}
}
+7
View File
@@ -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
+56 -9
View File
@@ -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<Value> = domi
// One policy per host that needs one: a Domi certificate, device certificates, or both.
let mut policies: Vec<Value> = 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::<Vec<_>>()
}),
);
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<String, Value> = 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"
})
}
+13 -3
View File
@@ -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(),
}
+18
View File
@@ -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<SocketAddr>,
/// 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<String>,
/// 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<std::net::IpAddr>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -68,6 +80,12 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileE
}
fn check_options(o: &CompileOptions) -> 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),
+19 -1
View File
@@ -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<EdgeAcme>,
pub forward_auth: Option<EdgeForwardAuth>,
/// Device certificates (mTLS); present when any host has `device_certs`.
pub device_certs: Option<EdgeDeviceCerts>,
/// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub trusted_proxies: Vec<String>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
@@ -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,
}
+7
View File
@@ -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,
}
}
+3 -1
View File
@@ -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};
+6
View File
@@ -171,6 +171,8 @@ pub struct Host {
pub health_check: Option<HealthCheck>,
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.
+853
View File
@@ -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
//! ├ <hostname> 90 days, serverAuth tls = "domi" hosts
//! └ <device name> 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<u8> {
self.0.serialize_der()
}
pub fn from_pem(pem: &str) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::from_pem(pem)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
pub fn from_der(der: &[u8]) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::try_from(der)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
/// SubjectPublicKeyInfo DER.
pub fn public_key_der(&self) -> Vec<u8> {
use rcgen::PublicKeyData as _;
self.0.subject_public_key_info()
}
}
pub fn generate_key() -> Result<KeyPair, PkiError> {
rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)
.map(KeyPair)
.map_err(build)
}
fn random<const N: usize>() -> Result<[u8; N], PkiError> {
let mut b = [0u8; N];
SystemRandom::new()
.fill(&mut b)
.map_err(|_| PkiError::Random)?;
Ok(b)
}
fn serial() -> Result<SerialNumber, PkiError> {
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, PkiError> {
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<String, PkiError> {
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<String, PkiError> {
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 <this file>`.
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<String, PkiError> {
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<String> {
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<Intermediate, PkiError> {
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<Issued, PkiError> {
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<Issued, PkiError> {
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<Issued, PkiError> {
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<u32>,
pub dns_names: Vec<String>,
pub serial_hex: String,
pub sha256_hex: String,
/// keyUsage: `None` when the extension is absent.
pub key_usage: Option<KeyUsageInfo>,
/// extendedKeyUsage: `None` when the extension is absent (any use).
pub eku: Option<EkuInfo>,
}
#[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<Vec<Vec<u8>>, 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<Vec<Vec<u8>>, PkiError> {
ders(pem)
}
/// The first certificate of a PEM chain, as PEM.
pub fn first_pem(pem: &str) -> Result<String, PkiError> {
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<x509_parser::certificate::X509Certificate<'_>, 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<CertInfo, PkiError> {
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<CertInfo, PkiError> {
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<Vec<u8>, 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<bool, PkiError> {
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<Vec<u8>, 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<Vec<u8>, 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<ring::aead::LessSafeKey, PkiError> {
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<String, PkiError> {
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<String, PkiError> {
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<KeyPair, PkiError> {
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<String, PkiError> {
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<String, PkiError> {
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<String, PkiError> {
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
}
}
+13 -1
View File
@@ -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<RawHealthCheck>,
#[serde(default)]
@@ -500,6 +502,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
}
});
// 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<E>
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,
+90
View File
@@ -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")
);
}
@@ -1,2 +1,3 @@
hostname = "status.example.org"
upstreams = ["http://[::1]:3001"]
device_certs = true
+46
View File
@@ -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": [
+11 -4
View File
@@ -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
}
]
}
+359
View File
@@ -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<CertificateDer<'static>> {
use rustls_pki_types::pem::PemObject;
CertificateDer::pem_slice_iter(pem.as_bytes())
.collect::<Result<_, _>>()
.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());
}
}
+3
View File
@@ -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");
+1
View File
@@ -36,6 +36,7 @@ form_urlencoded = "1.2"
[dev-dependencies]
ianitor-testkit.workspace = true
ring.workspace = true
rcgen.workspace = true
[lints]
workspace = true
+8 -1
View File
@@ -235,6 +235,10 @@ async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> 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();
}
}
}
}
+9 -4
View File
@@ -121,13 +121,18 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
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(),
+114 -9
View File
@@ -75,11 +75,46 @@ pub fn hostname(host_header: &str) -> String {
name.to_ascii_lowercase()
}
pub fn client_ip(session: &Session) -> Option<IpAddr> {
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<IpAddr> {
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::<IpAddr>().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::<crate::tls::ConnSni>() {
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");
+55
View File
@@ -97,6 +97,9 @@ pub struct HostRt {
pub response_ops: Vec<Op>,
/// Values of the secrets this host injects; a response header containing one is dropped.
pub secret_values: Vec<Vec<u8>>,
/// 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<String, i64>,
/// Loaded when any host has share links.
pub share_key: Option<Arc<ShareKey>>,
/// Loaded when any host has `device_certs`.
pub device_trust: Option<Arc<crate::tls::DeviceTrust>>,
/// Peers whose X-Forwarded-For names the client.
pub trusted_proxies: Vec<std::net::IpAddr>,
/// 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<Runtime,
let mut secret_values = Vec::new();
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
let response_ops = ops(&h.response_headers, &secrets, &mut secret_values)?;
let sends_proof = h.request_headers.iter().any(|op| {
matches!(op, EdgeHeaderOp::Set { value: EdgeValue::Secret { name }, .. } if name == ianitor_core::UI_PROOF_SECRET)
});
let upstreams = h
.upstreams
.iter()
@@ -396,10 +406,43 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
request_ops,
response_ops,
secret_values,
sends_proof,
}),
);
}
let device_hosts: std::collections::HashSet<String> = 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("<config>"),
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<Runtime,
} else {
None
};
let trusted_proxies = cfg
.trusted_proxies
.iter()
.map(|s| {
s.parse().map_err(|_| EdgeError::Config {
path: PathBuf::from("<config>"),
message: format!("trusted_proxies: {s:?} is not an IP address"),
})
})
.collect::<Result<Vec<std::net::IpAddr>, _>>()?;
Ok(Runtime {
cfg,
trusted_proxies,
hosts,
forward_auth,
access_log,
file_certs,
file_cert_expiry,
share_key,
device_trust,
sha256: String::new(),
})
}
+100
View File
@@ -94,6 +94,12 @@ pub enum AdminError {
pub struct Shared {
current: ArcSwap<Runtime>,
pub certs: Arc<CertStore>,
/// The listener's device-certificate check; its trust follows the runtime.
pub devices: Arc<crate::tls::DeviceVerifier>,
/// 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<Option<DeviceStamp>>,
generation: AtomicU64,
changed: tokio::sync::watch::Sender<u64>,
trial: Mutex<Option<Trial>>,
@@ -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<Runtime>) {
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<Option<Arc<crate::tls::DeviceTrust>>, String> {
let Some(dc) = &rt.cfg.device_certs else {
return Ok(None);
};
let hosts: std::collections::HashSet<String> = 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<usize, String> {
// 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<std::time::SystemTime>)>;
type DeviceStamp = (FileStamp, FileStamp);
+254 -4
View File
@@ -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<Arc<CertifiedKey>> {
// 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<i64> {
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<Option<String>> = 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<String> {
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<dyn ClientCertVerifier>,
/// SHA-256 of every allowed device certificate (DER).
allow: HashSet<[u8; 32]>,
/// Hosts that ask for a device certificate.
hosts: HashSet<String>,
}
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<String>) -> Result<Self, String> {
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<Option<Arc<DeviceTrust>>>,
/// 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<Arc<DeviceTrust>>) {
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<Arc<DeviceTrust>> {
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<rustls::server::danger::ClientCertVerified, rustls::Error> {
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<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
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<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
let t = self.current().ok_or_else(no_devices)?;
t.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
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<String>);
/// 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<Arc<dyn std::any::Any + Send + Sync>> {
Some(Arc::new(ConnSni(
tls.server_name().map(|s| s.to_ascii_lowercase()),
)))
}
}
+11
View File
@@ -108,6 +108,10 @@ pub struct EdgeSpec<'a> {
pub extra_args: Vec<String>,
/// Fixed HTTP port (e.g. one Pebble was told to validate against).
pub http_port: Option<u16>,
/// Extra files written into the edge directory before it starts (path relative to it).
pub files: Vec<(String, Vec<u8>)>,
/// Peers whose X-Forwarded-For edge believes.
pub trusted_proxies: Vec<std::net::IpAddr>,
}
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();
+339
View File
@@ -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()
);
}
}
+210
View File
@@ -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<ServerConfig>,
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<ClientConfig> {
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<'static>> =
CertificateDer::pem_slice_iter(w.dev_chain.as_bytes())
.collect::<Result<_, _>>()
.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<ServerConfig>, cc: &Arc<ClientConfig>, name: &str) -> Result<bool, String> {
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:?}"
);
}
+84
View File
@@ -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<std::net::IpAddr>, 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}");
}
}
+435
View File
@@ -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.<system>.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 ]
);
};
}
+54
View File
@@ -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;
};
}
+247
View File
@@ -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
'';
};
}
+44
View File
@@ -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
'';
})
+122
View File
@@ -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"
+38 -3
View File
@@ -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 <code>` (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/<hostname>.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).
+127 -3
View File
@@ -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 <API token>`. 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 <API token>`. 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:<port>`, `localhost:<port>`, `[::1]:<port>` 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/<id>" # 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 <path>`,
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 |
+94
View File
@@ -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": "<PEM PKCS#10>",
"profile": "intermediate",
"pub": "<one-time X25519 public key>",
"context": { "service": "ianitor", "host": "<server name>", "request_id": "<Ianitor pki request id>",
"csr_sha256": "<hex>" } }
```
Answer (sealed, handed out once): `{ "ok": true, "certificate": "<PEM>", "sha256": "<hex of the DER>" }`
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=<CN from the CSR>`; 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 <host> asks for a new Domi intermediate certificate, valid until <date>."
- 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`.
+150
View File
@@ -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/<merged commit hash>/" 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/<id>
```
(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 </dev/null | openssl x509 -noout -issuer`
shows a `(STAGING)` issuer; `GET /api/v1/hosts/ianitor-le.marek-novak.cz` shows
`certificate.state = "ok"`.
5. Remove the name, the Caddy block and the `[acme]` line afterwards.
+119
View File
@@ -0,0 +1,119 @@
diff --git a/hyperv-infra/flake.nix b/hyperv-infra/flake.nix
index 0d30b91..4302dc7 100644
--- a/hyperv-infra/flake.nix
+++ b/hyperv-infra/flake.nix
@@ -60,6 +60,11 @@
# full commit rather than by branch: `nixos-unstable` drifts, and drifting is precisely the
# failure mode that produced G-27 on production in the first place.
nixpkgs-gitea.url = "github:nixos/nixpkgs/6368eda62c9775c38ef7f714b2555a741c20c72d";
+
+ # Ianitor (the Pingora reverse proxy), beside Caddy on two low-risk hosts. Its packages are
+ # built from its own pinned nixpkgs; only the module is evaluated against this one. Pin to a
+ # reviewed commit: MERGED_COMMIT is replaced by the merged hash before the first lock.
+ ianitor.url = "git+https://gitea.marek-novak.cz/mnovak/Ianitor.git?ref=main&rev=MERGED_COMMIT";
};
outputs = { self, nixpkgs, sops-nix, nixpkgs-gitea, ... }@inputs: {
@@ -86,6 +91,8 @@
# Application modules
./modules/caddy.nix
+ # Ianitor beside Caddy: flowers and esp32 go through it (modules/ianitor.nix).
+ ./modules/ianitor.nix
./modules/home-assistant.nix
# ./modules/nextcloud.nix
diff --git a/hyperv-infra/modules/caddy.nix b/hyperv-infra/modules/caddy.nix
index e79f6b2..6fb5a49 100644
--- a/hyperv-infra/modules/caddy.nix
+++ b/hyperv-infra/modules/caddy.nix
@@ -225,6 +225,21 @@ in
Referrer-Policy "strict-origin-when-cross-origin"
}
'';
+ # The Ianitor trial (modules/ianitor.nix): Caddy keeps the public side and hands the request
+ # to Ianitor edge on loopback, over TLS with a Domi certificate it checks against the Domi
+ # root. Host and SNI are the visitor's name.
+ viaIanitor = host: {
+ extraConfig = ''
+ tls internal
+ ${secureHeaders "SAMEORIGIN"}
+ reverse_proxy https://127.0.0.1:18443 {
+ transport http {
+ tls_server_name ${host}
+ tls_trusted_ca_certs ${../ianitor/domi-root.crt}
+ }
+ }
+ '';
+ };
simple = { frame ? "SAMEORIGIN", upstream }: {
extraConfig = ''
tls internal
@@ -252,7 +267,11 @@ in
# flowers - was `localhost:8085`, which is PRODUCTION's port. On the mirror the app is
# published on 127.0.0.1:8092 and fronted by nginx on 8091, matching production's topology
# (nginx in front, not Caddy straight to the container). Proxying to 8085 reached nothing.
- "flowers.stage.marek-novak.cz" = simple { upstream = "127.0.0.1:8091"; };
+ # Through Ianitor (trial); before: simple { upstream = "127.0.0.1:8091"; }.
+ "flowers.stage.marek-novak.cz" = viaIanitor "flowers.stage.marek-novak.cz";
+
+ # Through Ianitor (trial). Explicit, so it wins over the `projects` entry below.
+ "esp32.stage.marek-novak.cz" = viaIanitor "esp32.stage.marek-novak.cz";
# supabase - the whole block previously proxied to 172.18.0.3 / .6 / .9.
#
diff --git a/hyperv-infra/modules/ianitor.nix b/hyperv-infra/modules/ianitor.nix
new file mode 100644
index 0000000..cd23016
--- /dev/null
+++ b/hyperv-infra/modules/ianitor.nix
@@ -0,0 +1,49 @@
+{ config, lib, inputs, ... }:
+
+# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32,
+# go through Ianitor's edge; every other host stays on Caddy exactly as before.
+#
+# Shape, chosen to keep decision D-21a ("Caddy is the only thing on 80/443 and the only service
+# exposed beyond loopback"):
+#
+# visitor -> 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"; } ]; }
+ ];
+}
+117
View File
@@ -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
├ <hostname> 90 days, serverAuth tls = "domi" hosts, renewed by control
└ <device name> 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-<id>.key` | the new key of an open renewal, encrypted the same way |
| `devices.json`, `devices/<id>.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/`: `<host>.crt` (leaf + intermediate) and `<host>.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 <dir>` 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-<date>.csr` and
`domi-intermediate-<date>.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-<date>.csr -outform DER | openssl dgst -sha256
openssl req -in domi-intermediate-<date>.csr -noout -subject # CN=Ianitor Domi Intermediate <yyyy-mm>
openssl x509 -req -in domi-intermediate-<date>.csr -CA domi-root.crt -CAkey domi-root.key \
-days 365 -sha256 -extfile domi-intermediate-<date>.ext -out domi-intermediate-<date>.crt
```
(`ianitor-control ca sign --root <dir> --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-<date>.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 <code>` 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).
+39
View File
@@ -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 <code>`, 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").
+15
View File
@@ -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 <code>`, 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).
+1443
View File
File diff suppressed because it is too large Load Diff
+159
View File
@@ -0,0 +1,159 @@
# Ianitor Domi web UI: open questions for Mark
Each has a recommendation. The UI can be built now with the recommended answer behind a typed client;
none of these blocks the first screens (Hosts, Add host, Undo, History, Share links on, Tokens).
Q1 and Q2 matter most.
---
## Q1. Share link on a host where share links are off: 3 clicks or 4?
**Today (Phase 1 note, ui-api G10):** ⋯ (1) → Share link (2) → "Turn on share links and apply" (3) →
wait about 60 s for the apply → Copy link (4). Copy needs its own click because a browser only allows
writing to the clipboard within a few seconds of a click, and the apply takes a minute.
**Proposal: 3 clicks.** Click 3 is **"Turn on share links and copy link"**. In that one click:
1. The UI calls `POST /hosts/{h}/share-links {path_prefix, expires_in_s, turn_on: true}`.
2. Control mints the link at once (a share token is a stateless HMAC; minting does not need the host's
setting to be on), and in the same call queues the apply that sets `share_links = true`. It answers
in well under a second with the link and the apply.
3. The UI writes the link to the clipboard inside the click (`ClipboardItem` holding the pending
response, the pattern Safari requires and Chrome and Firefox accept when the answer comes within a
second or two). If a browser still refuses, the dialog shows the link selected with a "Copy link"
button, so only that browser takes a 4th click. Test it in Chrome, Firefox and Safari on iOS.
4. The dialog says "Copied. The link starts working in about a minute, when the change is kept." and
shows the watch. On kept: "Share links are on. The link works now."
5. If the apply is reverted or not applied, control stops that link itself (deny list), so it never
starts working later, even if share links are turned on another day. The dialog says so.
Why it is safe: until the apply is kept, edge strips the token on that host and the visitor gets the
normal sign-in: nothing is opened early. The link is tied to the apply, so a failed apply leaves no
valid link behind. The click still says plainly that it changes the host.
What it costs: one API change in control (accept `turn_on` on the mint call, mint while off, queue the
PATCH, stop the link if that apply ends anything but kept). About a day's work with tests.
The one rough edge: someone who opens the link within that first minute gets the sign-in page. The
dialog's "starts working in about a minute" covers it for the person sending.
**Recommendation: accept the 3-click design.** If you prefer no API change, the fallback is the
current 4-click path, which the UI also supports (the button then reads "Turn on share links" and Copy
appears when the apply is kept).
## Q2. How does the UI prove who it is to control (G14)?
Control trusts only API tokens today and refuses `Remote-User`. The UI cannot call control until this
is decided. Options:
- (a) **Edge adds a secret header for the admin host.** The admin host's file sets a request header
from a systemd-credential secret (an existing feature); control requires it, then trusts
`Remote-User` / `Remote-Name` from Authelia for who did it (history's `actor`, the sidebar's "Signed
in as mark"). The browser never holds a token.
- (b) Control on a Unix socket only edge can reach, plus (a)'s Remote-User trust.
- (c) The UI holds an API token in memory, fetched from a bootstrap endpoint. A token in the browser
is the worst of the three.
**Recommendation: (a) now, (b) in Phase 4 hardening.** Plus `X-Ianitor-UI` as today against CSRF.
Also add `site.auth_logout_url` so the UI can show "Sign out".
## Q3. Engine switch: allowed when Caddy's comparison is not perfect?
The popover shows "{matched} of {compared} requests matched". What if some differ, or the comparison is
old?
**Recommendation:** allow the switch with the differences listed under "Show details" (the fallback is
for emergencies, when Pingora itself may be the problem); refuse only when Caddy's settings were never
built (`engine.not_ready`). A switch waits in the same queue as applies, one change at a time.
The API (`GET/POST /engine`, ui-api §1.9) is not built; the shape I designed against is in handoff §9.
## Q4. Share links while Caddy serves (G7)
Under Caddy no one checks share tokens, so a visitor with a link gets the normal sign-in (fails closed).
Options: (a) accept for v1 and say so plainly in the engine popover, the share dialog and Settings
(designed, handoff §9.1, §8.2); (b) build the small loopback validator that Caddy calls through
`forward_auth`, from the same core code, so links work under both engines.
**Recommendation: (a) for v1**, because Caddy is the rarely used fallback and the failure is safe;
(b) before v1.1's monthly switch rehearsal, since then links would break once a month.
## Q5. Device certificates: what if Custos cannot approve?
ROADMAP §4 puts a Custos approval on every device certificate. If Custos is unreachable, or has no
approval operation yet (§8.6), nothing can be issued.
**Recommendation:** a server-side fallback, `sudo ianitor-control pki approve <code>`, shown in the UI
with the match code to compare (handoff §13.4). It keeps the "a second factor approves every
certificate" rule (shell access on the server), and needs no new secret handling. Alternative: no
fallback, issuing waits for Custos.
## Q6. Intermediate renewal signed by hand: accept the extra steps?
When Custos cannot sign, the designed fallback (handoff §13.6) is: download the request and a signing
settings file, sign on the offline computer with the root, upload the signed certificate. That is about
4 clicks plus work away from the UI, against a budget of 1.
**Recommendation:** accept it as an exception to §4 that applies only while Custos lacks the signing
operation, the same way the Phase 3 plan already allows a "temporary manual offline signing step".
The exact command is owned by the PKI work (the UI shows what control returns). Confirm the root lives
on an offline machine that can run openssl (or tell me what it runs instead).
## Q7. Device certificate lifetime
The device board has a placeholder. Phase 3 is to decide and justify it.
**Recommendation: 1 year (365 days)**, with the row turning "renew soon" 30 days before. Long enough
that a family tablet is not a chore; short enough that a lost device's certificate dies within a year
even if nobody revokes it. If the intermediate is renewed with the same key each year, existing device
certificates keep validating across the renewal; if it is renewed with a new key, devices must be
re-issued and the lifetime should not pass the intermediate's end date. Please confirm which renewal
(same key or new key) the PKI work will do.
## Q8. Confirmations for Stop all share links and Revoke token
Your decision: "Stop is immediate". I read that as: a stopped link stops working at once (no apply).
In the UI I kept a single "Stop this link" one click with no confirmation, but put a short inline
confirmation on **"Stop all share links"** and on **"Revoke"** for an API token, because both are
irreversible and break things beyond one link (other people's links; a script). Neither is in the §4
budget.
**Recommendation: keep these two confirmations.** If you want Stop all to be one click too, say so.
## Q9. Polling keeps the Authelia session alive
The main screen polls every 5 s (30 s when hidden). Each poll goes through Authelia, which counts it as
activity, so an open tab never reaches the inactivity timeout; only the absolute expiration ends it.
**Recommendation:** stop polling after 15 minutes in a hidden tab (resume when it is shown), so an
unattended tab signs out by inactivity as Authelia intends. A visible tab keeps polling.
## Q10. Lifetime of new API tokens
Tokens are made with defaults on click 3, so there is no field for expiry before the token exists.
Design: a small "New tokens expire after: 1 year | Never" choice next to the New token button, default
1 year, not saved. The default path stays 3 clicks (+1 to copy).
**Recommendation: accept.** Alternative: always 1 year, and "never" only from the CLI.
## Q11. Show a chip for hosts open to anyone?
The board shows "Sign-in first" on protected hosts and nothing on open ones. Being open to anyone is the
more important fact to notice.
**Recommendation:** add a chip "Open to anyone" on hosts with `auth = none`, same quiet chip style (no
warning colour, because many open hosts are intended). Small change to the approved board.
## Q12. Server sentences missing for eight codes
`file.syntax`, `file.too_large`, `repo.duplicate_file`, `site.field.unknown`, `site.forward_auth`,
`site.forward_auth.header`, `site.secret.name`, `site.acme` answer "Something went wrong." from
control's messages.rs. The UI writes its own sentence for them (handoff §12.2), but curl users still get
the generic one.
**Recommendation:** add the handoff's sentences to messages.rs in Phase 3, so the UI and the API say the
same thing, and drop the UI's copies.
## Q13. Fonts
The boards load Cinzel, Cormorant Garamond and Manrope from Google Fonts. On a home server behind
Authelia the UI should make no outside requests.
**Recommendation:** self-host the Latin woff2 files in packages/ui (all OFL). No visual change.

Some files were not shown because too many files have changed in this diff Show More